国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

瀏覽:86日期:2024-03-20 18:53:58
功能介紹

本項(xiàng)目通過(guò)使用jsp和servlet實(shí)現(xiàn)簡(jiǎn)單的用戶登錄。主要邏輯為:

如果用戶不存在,則首先進(jìn)行注冊(cè)(注冊(cè)信息同步到數(shù)據(jù)庫(kù)中)。 進(jìn)行注冊(cè)后,可進(jìn)入登錄頁(yè)面對(duì)賬號(hào)進(jìn)行登錄。 如果賬號(hào)存在,則正確跳轉(zhuǎn)到歡迎界面,否則提示用戶賬號(hào)信息輸入錯(cuò)誤。 用戶進(jìn)行登錄頁(yè)面時(shí)需要填寫(xiě)驗(yàn)證碼同時(shí)可勾選是否兩周內(nèi)免登陸。 用戶進(jìn)入歡迎界面,則會(huì)顯示這是用戶第幾次登錄,如果不是第一次登錄則會(huì)顯示上次登錄時(shí)間。 如果用戶直接進(jìn)入welcome,(沒(méi)有進(jìn)行登錄,直接打開(kāi)welcome.jsp)則會(huì)跳轉(zhuǎn)到登錄頁(yè)面,防止非法登錄。前期工作準(zhǔn)備

1.安裝了Tomcat并可以成功使用。2.由于需要與數(shù)據(jù)庫(kù)連接,本項(xiàng)目使用的是mysql數(shù)據(jù)庫(kù),需要引入mysql-connector-java-5.1.9.jar包(可在官方下載或者通過(guò)maven引入mysql依賴),需要注意mysql-connector-java-5.1.9.jar需要放在C:Program FilesJavajdk1.8.0_201jrelibext路徑下,否則會(huì)出現(xiàn)連接數(shù)據(jù)庫(kù)異常。引入maven依賴:

<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency>創(chuàng)建數(shù)據(jù)庫(kù)

如果在DOS窗口下創(chuàng)建表的話則應(yīng)該加上ENGINE=InnoDB DEFAULT CHARSET=utf-8:表示可以添加中文字符,否則直接添加中文字符會(huì)出現(xiàn)亂碼 。

CREATE TABLE `usert` ( `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf-8

此時(shí)數(shù)據(jù)庫(kù)為空,無(wú)數(shù)據(jù)需要先進(jìn)行注冊(cè)才能登陸成功。

Bean封裝的數(shù)據(jù)信息

User:

public class User { private String name; private String pd; public User(){} public String getPd() { return pd; } public void setPd(String pd) { this.pd = pd; } public String getName() { return name; } public void setName(String name) { this.name = name; }}

Count:

public class Counter { private int count=1; public Counter(){} public int getCount() { return count++; } public void setCount(int count) { this.count = count; }}Dao對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作

package Dao;import java.sql.*;import java.util.ArrayList;public class UserDao { public boolean SearchUser(String u,String p) throws SQLException { PreparedStatement preparedStatement = null; ResultSet rs =null; Connection con = null; //啟動(dòng)mysql驅(qū)動(dòng)器 try { Class.forName('com.mysql.jdbc.Driver'); con = DriverManager.getConnection('jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8', 'root', '123456'); String sql = 'select * from usert where username=? and password=?'; preparedStatement = con.prepareStatement(sql); preparedStatement.setString(1, u); preparedStatement.setString(2, p); rs = preparedStatement.executeQuery(); if(rs.next()){ return true; } else { return false; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if(rs!=null) { rs.close(); } if(preparedStatement!=null) { preparedStatement.close(); } if(con!=null){ con.close(); } } return false; } public void insertUser(String u,String p) throws SQLException { ArrayList users=new ArrayList(); PreparedStatement preparedStatement = null; Connection con = null; //啟動(dòng)mysql驅(qū)動(dòng)器 try { Class.forName('com.mysql.jdbc.Driver'); con = DriverManager.getConnection('jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8', 'root', '123456'); preparedStatement = con.prepareStatement('insert into usert values(?,?)'); preparedStatement.setString(1,u); preparedStatement.setString(2,p); preparedStatement.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if(con!=null) { con.close(); } if(preparedStatement!=null) { preparedStatement.close(); } } }}實(shí)現(xiàn)登錄頁(yè)面三個(gè)頁(yè)面處理

歡迎界面(LoginServlet.jsp)

1.代碼

<%@ page import='java.net.URLEncoder' %><%@ page contentType='text/html;charset=utf-8' pageEncoding='utf-8' language='java' %><html><head> <title>LoginServlet</title></head><body><script type='text/javascript'> function validate() { if(login.username1.value===''){ alert('賬號(hào)不能為空'); return; } if(login.passwd.value===''){ alert('密碼不能為空'); return; } if(login.code.value===''){ alert('請(qǐng)輸入正確的驗(yàn)證碼'); return; } login.submit(); } function refresh() { login.imgValidate.src='http://www.intensediesel.com/bcjs/index.jsp?id='+Math.random(); }</script><% response.setCharacterEncoding('utf-8'); %><form name='login' action='/LoginCl' method='post'> 用戶名:<input type='text' name='username1'><br> 密碼:<input type='password' name='passwd'><br> <input type='checkbox' name='keep' >兩周內(nèi)免登陸<br> 驗(yàn)證碼:<input type='text' name='code' size=10> <%--點(diǎn)擊圖片可進(jìn)行驗(yàn)證碼刷新--%> <img name='imgValidate' src = 'http://www.intensediesel.com/bcjs/index.jsp' onclick='refresh()' ><br> <%--注意此處的button和submit的區(qū)別--%> <input type='button' value='登錄' onclick='validate()'> <% String username = null; String password = null; Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { if ('username'.equals(cookies[i].getName())) { username = cookies[i].getValue(); } else if ('password'.equals(cookies[i].getName())) { password = cookies[i].getValue(); } } if (username != null && password != null) { response.sendRedirect('welcome.jsp?uname=' +URLEncoder.encode(username,'utf-8')+ '&password=' + password); } %></form> <form action='register.jsp' method='post'> <input type='submit' value='注冊(cè)'></form></body></html>

2.頁(yè)面如下:

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

驗(yàn)證碼(index.jsp)

(點(diǎn)擊驗(yàn)證碼可以實(shí)現(xiàn)更新驗(yàn)證碼)

<script type='text/javascript'> function refresh() { src='http://www.intensediesel.com/bcjs/index.jsp?id='+Math.random(); }</script><%@ page contentType='charset=UTF-8' language='java' import ='java.awt.*' import ='java.awt.image.BufferedImage' import='java.util.*' import='javax.imageio.ImageIO' pageEncoding='gb2312'%><%response.setHeader('Cache-Control','no-cache');//在內(nèi)存中創(chuàng)建圖像 int width=60,height=20; BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //獲取畫(huà)筆 Graphics g=image.getGraphics(); //設(shè)置背景色 g.setColor(new Color(200,200,200)); g.fillRect(0,0,width,height); //取隨機(jī)產(chǎn)生的驗(yàn)證碼(4位數(shù)字) Random rnd=new Random(); int randNum=rnd.nextInt(8999)+1000; String randStr=String.valueOf(randNum); //將驗(yàn)證碼存入session session.setAttribute('randStr',randStr); //將驗(yàn)證碼顯示到圖像中 g.setColor(Color.black); g.setFont(new Font('', Font.PLAIN,20)); g.drawString(randStr,10,17); //隨機(jī)產(chǎn)生100個(gè)干擾點(diǎn),使圖像中的驗(yàn)證碼不易被其他程序探測(cè)到 for (int i = 0; i < 100; i++) { int x=rnd.nextInt(width); int y=rnd.nextInt(height); g.drawOval(x,y,1,1); } //輸出圖像到頁(yè)面 ImageIO.write(image,'JPEG',response.getOutputStream()); out.clear(); out=pageContext.pushBody();%>

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

登錄處理頁(yè)面(LoginCl.java(servlet))

業(yè)務(wù)邏輯處理頁(yè)面

package Register;import Dao.UserDao;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.*;import java.io.IOException;import java.io.PrintWriter;import java.net.URLEncoder;import java.sql.*;@WebServlet('/LoginCl')public class LoginCl extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { //中文亂碼解決方法 response.setContentType('text/html;charset=utf-8'); request.setCharacterEncoding('utf-8'); //防止非法登錄 得到session HttpSession httpSession = request.getSession(true); //修改session的存在時(shí)間為20s httpSession.setMaxInactiveInterval(20); httpSession.setAttribute('pass', 'ok'); //獲取用戶名的賬號(hào)和密碼 String u = null; //針對(duì)jsp 其username為username1 u = request.getParameter('username1'); String p = null; p = request.getParameter('passwd'); //得到提交的驗(yàn)證碼 String code = request.getParameter('code'); //獲取session驗(yàn)證碼 HttpSession session = request.getSession(); String randStr = (String) session.getAttribute('randStr'); //獲取到 if (code.equals(randStr)) { //訪問(wèn)數(shù)據(jù)庫(kù) UserDao userDao=new UserDao(); try { if (!userDao.SearchUser(u,p)) { response.getWriter().println('<a href=LoginServlet.jsp>抱歉:賬號(hào)或密碼錯(cuò)誤,請(qǐng)注意核實(shí)信息重新輸入</a>'); return; } else { String keep = request.getParameter('keep'); if (keep != null) { //創(chuàng)建cookie Cookie cookie1 = new Cookie('username', u); Cookie cookie2 = new Cookie('password', p); //設(shè)置關(guān)聯(lián)路徑 cookie1.setPath(request.getContextPath()); cookie2.setPath(request.getContextPath()); //設(shè)置cookie的消亡時(shí)間 兩周 cookie1.setMaxAge(2 * 7 * 24 * 60 * 60); cookie1.setMaxAge(2 * 7 * 24 * 60 * 60); //把cookie信息寫(xiě)給瀏覽器 response.addCookie(cookie1); response.addCookie(cookie2); } response.sendRedirect('welcome.jsp?uname=' + URLEncoder.encode(u, 'utf-8') + '&password=' + p); } } catch (SQLException e) { e.printStackTrace(); } } } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ this.doGet(request,response); }}

如果當(dāng)前不存在該用戶,則會(huì)輸出賬號(hào)密碼錯(cuò)誤等信息,存在該用戶則會(huì)跳轉(zhuǎn)到歡迎界面。

歡迎界面(welcome.jsp)

<%@ page import='java.util.Date' %><%@ page contentType='text/html;charset=gb2312' pageEncoding='gb2312' language='java' import='bean.*'%><%@ page import='java.net.URLDecoder' %><html><head> <title>welcome</title></head><body><% request.setCharacterEncoding('gb2312'); HttpSession httpSession=request.getSession(true); String val=(String)httpSession.getAttribute('pass'); if(val==null){ response.sendRedirect('LoginServlet.jsp'); } application.setAttribute('COUNTER',new Integer(counter));%><jsp:useBean scope='session'/><jsp:useBean scope='session'> <jsp:setProperty name='user' property='name' param='uname'/> <jsp:setProperty name='user' property='pd' param='password'/></jsp:useBean><h1>主界面</h1><%--welcome name =<%=u%> password =<%=p%><br>--%><%--welcome name :<jsp:getProperty name='user' property='name' />--%>welcome name :<%out.println(URLDecoder.decode(user.getName(),'utf-8'));%> password:<jsp:getProperty name='user' property='pd' /><br><%--welcome name :<%out.println(session.getAttribute('username'));%>password:<%out.println(session.getAttribute('password'));%><br>--%><%--這是你第:<%=counter%>次訪問(wèn)本網(wǎng)站!<br>--%>這是你第:<jsp:getProperty name='mycount' property='count'/>次訪問(wèn)本網(wǎng)站!<br><a href=’LoginServlet.jsp’>返回重新登錄</a><br><% Cookie[] cookies = request.getCookies(); if(cookies!=null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals('lastAccessTime')) { out.println('您上次訪問(wèn)的時(shí)間是:'); Long lastAccessTime = Long.parseLong(cookies[i].getValue()); Date date = new Date(lastAccessTime); out.println(date.toLocaleString()); } } } //用戶訪問(wèn)過(guò)后重新設(shè)置用戶的訪問(wèn)時(shí)間,存儲(chǔ)在cookie中,然后發(fā)送到客戶端瀏覽器 Cookie cookie=new Cookie('lastAccessTime',System.currentTimeMillis()+''); //設(shè)置cookie的有效期為5min cookie.setMaxAge(300); //將cookie對(duì)象添加到response對(duì)象中,這樣服務(wù)器在輸出response對(duì)象中的內(nèi)容時(shí) // 就會(huì)把cookie也輸入到客戶端瀏覽器 response.addCookie(cookie);%></body></html>實(shí)現(xiàn)注冊(cè)頁(yè)面

信息注冊(cè)(register.jsp)

注冊(cè)信息時(shí)需要對(duì)用戶輸入的密碼進(jìn)行判斷:必須有數(shù)字和大小寫(xiě)英文且長(zhǎng)度在6-20之間,為了簡(jiǎn)化代碼這里使用的是正則表達(dá)式進(jìn)行判斷。

<%@ page language='java' pageEncoding='gb2312' %><html><head> <title>register</title></head><body> <h1>歡迎您進(jìn)行注冊(cè)</h1> <script language='JavaScript' type='text/javascript'> function checkPassword() { var ps=/^[A-Za-z0-9]{6,20}$/; if (!ps.exec(register.password1.value)) { alert('密碼必須同時(shí)包含大小寫(xiě)字母和數(shù)字且長(zhǎng)度應(yīng)該在6-20之間'); return; } register.submit(); } </script><form name='register' action='registerMessage.jsp' method='post'> 請(qǐng)輸入賬號(hào):<input type='text' name='name'><br> 請(qǐng)輸入密碼(要求:必須包含大小寫(xiě)英文和數(shù)字無(wú)非法字符,長(zhǎng)度大于6位小于20位):<input type='password' name='password1'><br> 請(qǐng)選擇性別:<input name='sex' type='radio' value='男' checked>男 <input name='sex' type='radio' value='女' >女<br> 請(qǐng)選擇家鄉(xiāng):<select name='home' > <option value='北京'>北京</option> <option value='上海'>上海</option> <option value='陜西'>陜西</option> </select> <br> 請(qǐng)選擇您的愛(ài)好:<input name='fav' type='checkbox' value='唱歌'>唱歌 <input name='fav' type='checkbox' value='跳舞'>跳舞 <input name='fav' type='checkbox' value='打球'>打球 <input name='fav' type='checkbox' value='玩游戲'>玩游戲<br> <input type='button' value='注冊(cè)' onclick='checkPassword()'></form></body></html>

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

點(diǎn)擊注冊(cè)后則會(huì)跳轉(zhuǎn)到注冊(cè)成功頁(yè)面,將其賬號(hào)和密碼進(jìn)行存儲(chǔ)到數(shù)據(jù)庫(kù)中,后可以直接進(jìn)行登錄。

注冊(cè)成功頁(yè)面(registerMessage.jsp)

<%@ page import='java.sql.*' %><%@ page import='Dao.UserDao' %><%@ page language='java' pageEncoding='gb2312' %><html><head> <title>message</title></head><body><h2>信息注冊(cè)成功!該用戶注冊(cè)信息如下:</h2><% request.setCharacterEncoding('gb2312'); String name=request.getParameter('name'); String password=request.getParameter('password1'); String sex = request.getParameter('sex'); String home = request.getParameter('home'); out.println('賬號(hào):'+name); out.println('密碼:'+password); out.println('性別:'+sex); out.println('家鄉(xiāng):'+home); out.println('興趣愛(ài)好:'); String[] fav = request.getParameterValues('fav'); for (int i = 0; i < fav.length; i++) { out.print(fav[i]+' '); } try { UserDao userDao=new UserDao(); userDao.insertUser(name,password); out.println('<a href=LoginServlet.jsp>信息注冊(cè)成功,點(diǎn)擊此處進(jìn)行登錄</a>'); } catch (SQLException e) { e.printStackTrace(); }%></body></html>

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

(如下所示,數(shù)據(jù)添加成功)

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

功能演示

至此此項(xiàng)目結(jié)束,我演示一下登錄時(shí)的場(chǎng)景。

1.數(shù)據(jù)庫(kù)數(shù)據(jù)

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

2.輸入數(shù)據(jù)庫(kù)中沒(méi)有的信息

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

3.賬號(hào)密碼正確

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

ps:需要注意一定要填寫(xiě)賬戶或者密碼或者驗(yàn)證碼,否則則會(huì)彈出錯(cuò)誤窗口。

eg:

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面

總結(jié)

此項(xiàng)目需要用到的知識(shí)點(diǎn)比較多,其中包括 jsp,servlet,mysql,cookie, Javabean等。需要將學(xué)到的web知識(shí)聯(lián)系起來(lái)。

到此這篇關(guān)于jsp+dao+bean+servlet(MVC模式)實(shí)現(xiàn)簡(jiǎn)單用戶登錄和注冊(cè)頁(yè)面的文章就介紹到這了,更多相關(guān)jsp servlet登錄注冊(cè)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: JSP
主站蜘蛛池模板: 珠海市| 五原县| 九江县| 新郑市| 竹山县| 武强县| 洪泽县| 临漳县| 石嘴山市| 湟源县| 乐都县| 阳江市| 夹江县| 龙南县| 昌乐县| 巴林左旗| 湖北省| 佛山市| 连山| 忻城县| 繁峙县| 启东市| 竹山县| 龙江县| 临海市| 瑞金市| 武平县| 宾阳县| 资溪县| 喀喇| 马山县| 长丰县| 新津县| 仁怀市| 常州市| 安塞县| 闽侯县| 富民县| 北辰区| 阳曲县| 蒙阴县|