1. 程式人生 > >JSP登入功能

JSP登入功能

這篇部落格向大家詳解如何在jsp頁面實現登入功能,登陸的賬號密碼資料是從資料庫中拿到的,匹配則登陸成功。

首先在school資料庫下建立user表,欄位如下:

在這裡插入圖片描述

然後,建立web專案,搭建環境如下:

在這裡插入圖片描述

然後就開始我們的程式碼了。

1.首先把BaseDao.java貼上到com.tao.dao包下,lib下貼上mysql-connector-java-5.1.19.jar;在entity包下建立User類

因為 src的內容已經在上篇部落格寫了,詳情請點選JSP向資料庫插入資料(簡單註冊功能),直接拿過來用就行,所以再次不在展示了。

登入頁面

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="dologin.jsp" method="post" >
<%  
	//獲得Cookie(陣列)
	Cookie cs[]=request.getCookies();
	String username="";
	if(cs!=null){
	 	//遍歷陣列拿到名為“username”的cookie
		for(Cookie c:cs){
			if("username".equals(c.getName())){
				username=c.getValue();  //拿到cookie的value
			}
		}
	}
%>
		使用者名稱:<input name="username" value="<%=username %>"><!-- 填充上次的登入名 -->
		密碼:<input name="password">
		<hr>
		<input type="submit" value="提交" >
		<input type="reset" >
		<%	String msg=(String)request.getAttribute("aa");
		if(msg!=null){
			out.print(msg);
		}
	%>
</form>
</body>
</html>

登入處理頁面

<%@page import="com.tao.entity.User"%>
<%@page import="com.tao.dao.UserDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%   //獲取引數
	String name=request.getParameter("username");
	String pass=request.getParameter("password");
	UserDao udao=new UserDao();
	User u=udao.dologin(name, pass);
	/*
	利用Cookie實現儲存上次登入名的功能
	*/
	Cookie c=new Cookie("username",name); //獲取name命名為username
	c.setMaxAge(60*60);//單位為秒,設定Cookie保留時間為1h
	c.setPath("/"); //當前路徑下
	response.addCookie(c);
	String msg="";
	if(u!= null){
		
		//response.sendRedirect("success.jsp");  //重定向 
		/*
		登陸成功跳轉到success.jsp
		*/
		msg="登入成功,歡迎"+name;
		request.setAttribute("aa", msg); //
		request.getRequestDispatcher("/success.jsp").forward(request, response);  //轉發
	}else{
		//登入失敗還退回到登入頁面
		msg="賬號或密碼錯誤,請重新登入";
		//response.sendRedirect("login.jsp");
		request.setAttribute("aa", msg);
		request.getRequestDispatcher("/login.jsp").forward(request, response);
	}
	%>
</body>
</html>

登陸成功頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	String msg=(String)request.getAttribute("aa");
	out.print(msg);
%>
</body>
</html>
由於本篇部落格涉及到了web層共享資料的request。下篇部落格將講到這些。

有不懂得隨時評論問博主呦