JavaWeb基础(自动登陆案例实现Cookie)

1自动登陆的html页面



   
    First.html

    
    
    

  
  
  
  

登陆

用户名:
密码:
自动登陆
验证码

2自动登陆的验证Servlet

	public class AutoLoginServlet extends HttpServlet {
	UserService userService=new UserService();
	/**
	   完成自动登录    /autologin 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取Cookie数据,如果没有则sz=null;Cookie中存入的是用户名和密码
		Cookie sz[]= request.getCookies();
		String name=null;
		String pass=null;
		//如果数组不为null,则循环遍历数组
		for(int i=0;sz!=null&&i

3如果登陆成功,则会种下Cookie,Servlet实现页面

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");		
		//接收网页的信息
		String name=request.getParameter("stname");
		String pass=request.getParameter("stpass");
		String auto=request.getParameter("auto");
		//传递验证用户名密码.
		boolean ok=userService.login(name,pass);
		if(ok){  //成功就去首页
			//你是否勾选自动登陆
			if(auto!=null){
				//如果勾选,则设置Cookie值,然后传递
				Cookie c1=new Cookie("name", name); 
				Cookie c2=new Cookie("pass", pass);
				c1.setMaxAge(3600*24*7);
				c2.setMaxAge(3600*24*7);
				response.addCookie(c1);
				response.addCookie(c2);			
			}		
			response.sendRedirect("index.jsp");		 
		}else{
			response.sendRedirect("login.html");
		} 	 
	}

你可能感兴趣的:(JavaWeb)