1. 程式人生 > >利用Session完成使用者的登入和登出

利用Session完成使用者的登入和登出

使用者的登入和登出是最常見的Web應用案例,當一個應用的客戶登入了以後,其他所有的會話都得知道這個使用者已經登入還很有可能得提取使用者的暱稱予以顯示等等,所以,只有把登入成功的使用者的資訊放入到Session中才能夠辦到使所有的Servlet都能訪問到使用者的登入狀態,下面把這個案例放上來。

第一是登入的介面,是HTML的一個表單,非常的簡單

[html] view plaincopyprint?
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
  5. <title>登陸介面</title>
  6. </head>
  7. <body>
  8. <formaction="/Web/servlet/LoginServlet"method="post">
  9. 帳號:<inputtype="text"name="username"><br>
  10. 密碼:<inputtype="password"name="password">
    <br>
  11. <inputtype="submit"value="登入">
  12. </form>
  13. </body>
  14. </html>
<!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>登陸介面</title>
</head>
<body>
	<form action="/Web/servlet/LoginServlet" method="post">
	帳號:<input type="text" name="username"><br>
	密碼:<input type="password" name="password"><br>
	<input type="submit" value="登入">
	</form>
</body>
</html>

第二是處理登入資訊的LoginServlet [java] view plaincopyprint?
  1. package com.bird.login;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. publicclass LoginServlet extends HttpServlet {
  11. /**
  12. * @category 使用Session處理使用者登陸
  13. * @author Bird
  14. */
  15. privatestaticfinallong serialVersionUID = 1L;
  16. publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
  17. throws ServletException, IOException {
  18. response.setCharacterEncoding("UTF-8");
  19. response.setContentType("text/html;charset=UTF-8");
  20. PrintWriter out = response.getWriter();
  21. String username = request.getParameter("username");
  22. String password = request.getParameter("password");
  23. List<User> list = Db.getAll();
  24. for(User u: list){
  25. if(u.getUsername().equals(username) && u.getPassword().equals(password)){
  26. request.getSession().setAttribute("user", u);//登入成功,將使用者資料放入到Session中
  27. response.sendRedirect("/Web/index.jsp");
  28. return;//進行重定向,並且下面的程式碼不再執行
  29. }
  30. }
  31. out.write("您的應戶名或密碼錯誤");
  32. }
  33. publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
  34. throws ServletException, IOException {
  35. doGet(request,response);
  36. }
  37. }
  38. class Db{
  39. publicstatic List<User> list = new ArrayList<User>();
  40. static{
  41. list.add(new User("aaa","123"));
  42. list.add(new User("bbb","123"));
  43. list.add(new User("ccc","123"));
  44. }
  45. publicstatic List<User> getAll(){
  46. return list;
  47. }
  48. }
package com.bird.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

	/**
	 * @category 使用Session處理使用者登陸
	 * @author Bird
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		List<User> list = Db.getAll();
		for(User u: list){
			if(u.getUsername().equals(username) && u.getPassword().equals(password)){
				request.getSession().setAttribute("user", u);//登入成功,將使用者資料放入到Session中
				response.sendRedirect("/Web/index.jsp");
				return;//進行重定向,並且下面的程式碼不再執行
			}
		}
		
		out.write("您的應戶名或密碼錯誤");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}

}

class Db{
	public static List<User> list = new ArrayList<User>();
	static{
		list.add(new User("aaa","123"));
		list.add(new User("bbb","123"));
		list.add(new User("ccc","123"));
	}
	
	public static List<User> getAll(){
		return list;
	}
}

第三,使用者的資訊封裝在User物件中 [java] view plaincopyprint?
  1. package com.bird.login;
  2. /**
  3. * @category 封裝使用者的資料的物件
  4. * @author Bird
  5. *
  6. */
  7. publicclass User {
  8. private String username;
  9. private String password;
  10. public User() {
  11. }
  12. public User(String username, String password) {
  13. this.username = username;
  14. this.password = password;
  15. }
  16. public String getUsername() {
  17. return username;
  18. }
  19. publicvoid setUsername(String username) {
  20. this.username = username;
  21. }
  22. public String getPassword() {
  23. return password;
  24. }
  25. publicvoid setPassword(String password) {
  26. this.password = password;
  27. }
  28. }
package com.bird.login;

/**
 * @category 封裝使用者的資料的物件
 * @author Bird
 *
 */
public class User {
	private String username;
	private String password;
	
	
	public User() {
		
	}
	public User(String username, String password) {
		
		this.username = username;
		this.password = password;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

第四是處理使用者登出的Servlet [java] view plaincopyprint?
  1. package com.bird.login;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import javax.servlet.http.HttpSession;
  8. publicclass LoginOutServlet extends HttpServlet {
  9. /**
  10. * @category 退出登入的Servlet,登出
  11. * @author Bird
  12. */
  13. privatestaticfinallong serialVersionUID = 1L;
  14. publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
  15. throws ServletException, IOException {
  16. HttpSession session = request.getSession(false);//防止建立Session
  17. if(session == null){
  18. response.sendRedirect("/Web/index.jsp");
  19. return;
  20. }
  21. session.removeAttribute("user");
  22. response.sendRedirect("/Web/index.jsp");
  23. }
  24. publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
  25. throws ServletException, IOException {
  26. }
  27. }
package com.bird.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginOutServlet extends HttpServlet {

	/**
	 * @category 退出登入的Servlet,登出
	 * @author Bird
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession(false);//防止建立Session
		if(session == null){
			response.sendRedirect("/Web/index.jsp");
			return;
		}
		
		session.removeAttribute("user");
		response.sendRedirect("/Web/index.jsp");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

}

第五是最終的顯示介面 [html] view plaincopyprint?
  1. <%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  3. <html>
  4. <head>
  5. <title>My JSP 'index.jsp' starting page</title>
  6. </head>
  7. <body>
  8. 歡迎您,${user.username} <br>
  9. <ahref="/Web/servlet/LoginOutServlet">退出登入</a>
  10. </body>
  11. </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    
    <title>My JSP 'index.jsp' starting page</title>
	
  </head>
  
  <body>
    歡迎您,${user.username}  <br>
    <a href="/Web/servlet/LoginOutServlet">退出登入</a>
  </body>
</html>

效果如下

登入成功後


登出後