1. 程式人生 > >Servlet通過Cookie儲存使用者資訊,實現自動登入的demo.

Servlet通過Cookie儲存使用者資訊,實現自動登入的demo.

開始介面HTML,跳轉到判斷是否有Cookie的Servlet.

SessionStartPage.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="sessionindex.do" method="post">
		<input type="submit" value="登入">
	</form>
</body>
</html>

判斷是否有Cookie的Servlet.此處獲取Cookie的資料。

package cc.session;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;


/**
 * Servlet implementation class Index
 */
@WebServlet("/sessionindex.do")
public class Index extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Index() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
    {
    	Cookie[] cookies=request.getCookies();//查詢瀏覽器儲存的本地Cookie,返回結果是陣列。
		if(cookies!=null)
		{
			for(Cookie cookie:cookies)
			{//Cookie由name和value兩部分組成
				String name=cookie.getName();
				String value=cookie.getValue();
				if("user".equals(name)&&"Daniel".equals(value)) {
					request.setAttribute(name,value );
					request.getRequestDispatcher("/sessionuser.view").forward(request, response);
					return;
				}
			}
		}
		response.sendRedirect("SessionLogin.html");
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		processRequest(request,response);
		
	}

}

登入介面的Html

SessionLogin.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<form action="sessionlogin.do" method="post">
			<label>名稱<input type="text" name="user" width="100"></label><br>
			<label>密碼<input type="password" name="password" width="100" title="長度6-10字元,必須包含字母和數字。"></label><br>
			自動登入:<input type="radio" name="autologin" value="auto"><br>
			<input type="submit" value="登入">
		</form>
	</body>
</html>

登入的Servlet,此處建立Cookie,並將使用者存到Cookie中。

package cc.session;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SessionLogin
 */
@WebServlet("/sessionlogin.do")
public class SessionLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SessionLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		request.setCharacterEncoding("UTF-8");
		String user=URLDecoder.decode(request.getParameter("user"),"UTF-8");
		String password=request.getParameter("password");
		String autologin=request.getParameter("autologin");
		if(user.equals("Daniel")&&password.equals("2018Daniel"))
		{
			if("auto".equals(autologin))
			{//自動登入時,建立Cookie,儲存使用者名稱。
				Cookie cookieLogin=new Cookie("user", user);
				cookieLogin.setMaxAge(3*60);//設定儲存時間為3分鐘
				response.addCookie(cookieLogin);
			}
			request.setAttribute("user", user);
			request.setAttribute("password",password);
			request.getRequestDispatcher("sessionuser.view").forward(request, response);
		}
		else {
			response.sendRedirect("SessionLogin.html");
		}
	
	}

}

獲取Cookie和登入成功後的Servlet

package cc.session;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * Servlet implementation class SessionUser
 */
@WebServlet("/sessionuser.view")
public class SessionUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SessionUser() {
        super();
        // TODO Auto-generated constructor stub
    }
    private void processRequest(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
 
		String user=(String) request.getAttribute("user");//forward過來的request,需要通過getAttribute方法獲得,不是getParameter
		PrintWriter out= response.getWriter();
		if(user==null)
		{
			response.sendRedirect("SessionLogin.html");
		}
		else {
			out.println("<html><head><title>Servlet User</title></head><body>"+user+"  Welcome!</body></html>");
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		//processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		processRequest(request,response);
		
	}

}