首页 > 代码库 > java代码实现自动登录功能

java代码实现自动登录功能

通常我们登录某网站,会有选择保存几天,或者是几个星期不用登录,之后输入该网站地址无需登录直接进入主页面,那么这就叫做自动登录,怎么实现呢,下面我以一个小例子来演示一下

登录页面:login.jsp

Html代码 复制代码 收藏代码
  1. <SPAN style="FONT-SIZE: medium"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <html>  
  3.   <head>  
  4.   </head>  
  5.   <body>  
  6.   <form action="login.do">  
  7.     用户名:<input type="text" name="username" ><br/>  
  8.     密    码:<input type="text" name="password" ><br/>  
  9.        
  10.     <input type="submit" value=http://www.mamicode.com/"登录" /><select name="saveTime">  
  11.     <option value=http://www.mamicode.com/"366">一年</option>  
  12.     <option value=http://www.mamicode.com/"183">半年</option>  
  13.      <option value=http://www.mamicode.com/"30">一个月</option>    
  14.      <option value=http://www.mamicode.com/"7">一周</option>  
  15.     </select>  
  16.   </form>  
  17.   </body>  
  18. </html>  
  19. </SPAN>  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html>  <head>  </head>  <body>  <form action="login.do">    用户名:<input type="text" name="username" ><br/>    密    码:<input type="text" name="password" ><br/>        <input type="submit" value="http://www.mamicode.com/登录" /><select name="saveTime">    <option value="http://www.mamicode.com/366">一年</option>    <option value="http://www.mamicode.com/183">半年</option>     <option value="http://www.mamicode.com/30">一个月</option>      <option value="http://www.mamicode.com/7">一周</option>    </select>  </form>  </body></html>

 

那么从上面可看到可选择保存自动登录的期限,可以是一年,半年,一个月,一周,当然这都是以天为单位的

服务类:LoginService

Java代码 复制代码 收藏代码
  1. <SPAN style="FONT-SIZE: medium">package com.login.servlet;   
  2.   
  3. public class LoginService {   
  4.   
  5.     public static boolean login(String username, String password) {   
  6.         if ("admin".equals(username) && "123456".equals(password)) {   
  7.             return true;   
  8.         } else {   
  9.             return false;   
  10.         }   
  11.     }   
  12. }   
  13. </SPAN>  
package com.login.servlet;public class LoginService {	public static boolean login(String username, String password) {		if ("admin".equals(username) && "123456".equals(password)) {			return true;		} else {			return false;		}	}}

业务处理servlet:LoginServlet

Java代码 复制代码 收藏代码
  1. <SPAN style="FONT-SIZE: medium">package com.login.servlet;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. import javax.servlet.ServletException;   
  6. import javax.servlet.http.Cookie;   
  7. import javax.servlet.http.HttpServlet;   
  8. import javax.servlet.http.HttpServletRequest;   
  9. import javax.servlet.http.HttpServletResponse;   
  10.   
  11. public class LoginServlet extends HttpServlet {   
  12.   
  13.   
  14.     public void doGet(HttpServletRequest request, HttpServletResponse response)   
  15.             throws ServletException, IOException {   
  16.         this.doPost(request, response);   
  17.     }   
  18.   
  19.     public void doPost(HttpServletRequest request, HttpServletResponse response)   
  20.             throws ServletException, IOException {   
  21.          String username=request.getParameter("username");   
  22.            String password=request.getParameter("password");   
  23.            String savetime=request.getParameter("saveTime");   
  24.            if(LoginService.login(username, password)){   
  25.                if(null!=savetime&&!savetime.isEmpty()){   
  26.                    int saveTime=Integer.parseInt(savetime);//这里接受的表单值为天来计算的   
  27.                    int seconds=saveTime*24*60*60;   
  28.                    Cookie cookie = new Cookie("user", username+"=="+password);   
  29.                    cookie.setMaxAge(seconds);                      
  30.                    response.addCookie(cookie);   
  31.                }   
  32.                request.setAttribute("username",username);   
  33.                request.getRequestDispatcher("/main.jsp").forward(request,response);   
  34.            }else{   
  35.                request.getRequestDispatcher("/index.jsp").forward(request,response);   
  36.            }   
  37.     }   
  38.   
  39. }   
  40. </SPAN>  
package com.login.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet {	public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {        this.doPost(request, response);	}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		 String username=request.getParameter("username");		   String password=request.getParameter("password");		   String savetime=request.getParameter("saveTime");		   if(LoginService.login(username, password)){			   if(null!=savetime&&!savetime.isEmpty()){				   int saveTime=Integer.parseInt(savetime);//这里接受的表单值为天来计算的				   int seconds=saveTime*24*60*60;				   Cookie cookie = new Cookie("user", username+"=="+password);				   cookie.setMaxAge(seconds);									   response.addCookie(cookie);			   }			   request.setAttribute("username",username);			   request.getRequestDispatcher("/main.jsp").forward(request,response);		   }else{			   request.getRequestDispatcher("/index.jsp").forward(request,response);		   }	}}

 

看清上面处理Cookie的方式步骤:其实这是为第一次登录该网站时【前提是选择了保存自动登录期限时间】处理Cookie,只要这一步处理成功,以后都无需经过这个Servlet因为我们接下来要在请求到达前,从Cookie中取出我们的用户名和密码,这样的话就需要一个过滤器了

Java代码 复制代码 收藏代码
  1. <SPAN style="FONT-SIZE: medium">package com.login.servlet;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. import javax.servlet.Filter;   
  6. import javax.servlet.FilterChain;   
  7. import javax.servlet.FilterConfig;   
  8. import javax.servlet.ServletException;   
  9. import javax.servlet.ServletRequest;   
  10. import javax.servlet.ServletResponse;   
  11. import javax.servlet.http.Cookie;   
  12. import javax.servlet.http.HttpServletRequest;   
  13. import javax.servlet.http.HttpServletResponse;   
  14.   
  15. public class IndexFilter implements Filter {   
  16.   
  17.     public void destroy() {   
  18.         // TODO Auto-generated method stub   
  19.   
  20.     }   
  21.   
  22.     public void doFilter(ServletRequest arg0, ServletResponse arg1,   
  23.             FilterChain arg2) throws IOException, ServletException {   
  24.         HttpServletRequest request = (HttpServletRequest) arg0;   
  25.         HttpServletResponse response = (HttpServletResponse) arg1;   
  26.         Cookie[] cookies = request.getCookies();   
  27.         String[] cooks = null;   
  28.         String username = null;   
  29.         String password = null;   
  30.         if (cookies != null) {   
  31.             for (Cookie coo : cookies) {   
  32.                 String aa = coo.getValue();   
  33.                 cooks = aa.split("==");   
  34.                 if (cooks.length == 2) {   
  35.                     username = cooks[0];   
  36.                     password = cooks[1];   
  37.                 }   
  38.             }   
  39.         }   
  40.         if (LoginService.login(username, password)) {   
  41.             request.getSession().setAttribute("username",username);   
  42.             response.sendRedirect("main.jsp");   
  43.             //request.getRequestDispatcher("/main.jsp").forward(request, response);   
  44.         }else{   
  45.             arg2.doFilter(request,response );   
  46.         }   
  47.        
  48.   
  49.     }   
  50.   
  51.     public void init(FilterConfig arg0) throws ServletException {   
  52.         // TODO Auto-generated method stub   
  53.   
  54.     }   
  55.   
  56. }   
  57. </SPAN>  
package com.login.servlet;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class IndexFilter implements Filter {	public void destroy() {		// TODO Auto-generated method stub	}	public void doFilter(ServletRequest arg0, ServletResponse arg1,			FilterChain arg2) throws IOException, ServletException {		HttpServletRequest request = (HttpServletRequest) arg0;		HttpServletResponse response = (HttpServletResponse) arg1;		Cookie[] cookies = request.getCookies();		String[] cooks = null;		String username = null;		String password = null;		if (cookies != null) {			for (Cookie coo : cookies) {				String aa = coo.getValue();				cooks = aa.split("==");				if (cooks.length == 2) {					username = cooks[0];					password = cooks[1];				}			}		}		if (LoginService.login(username, password)) {			request.getSession().setAttribute("username",username);			response.sendRedirect("main.jsp");			//request.getRequestDispatcher("/main.jsp").forward(request, response);		}else{			arg2.doFilter(request,response );		}		}	public void init(FilterConfig arg0) throws ServletException {		// TODO Auto-generated method stub	}}

 

我这里所说的请求到达之前,不是指的某个路径匹配的servlet而是指的就是在输入网址到达登录页面前就要进行自动登录的处理,那么web.xml中应该怎么配置呢

Xml代码 复制代码 收藏代码
  1. <SPAN style="FONT-SIZE: medium"><?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"    
  3.     xmlns="http://java.sun.com/xml/ns/javaee"    
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee    
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <filter>  
  8.   <filter-name>loginFilter</filter-name>  
  9.   <filter-class>com.login.servlet.IndexFilter</filter-class>  
  10.   </filter>  
  11.   <filter-mapping>  
  12.   <filter-name>loginFilter</filter-name>  
  13.   <url-pattern>/index.jsp</url-pattern>  
  14.   </filter-mapping>  
  15.   <servlet>  
  16.     <servlet-name>LoginServlet</servlet-name>  
  17.     <servlet-class>com.login.servlet.LoginServlet</servlet-class>  
  18.   </servlet>  
  19.   
  20.   <servlet-mapping>  
  21.     <servlet-name>LoginServlet</servlet-name>  
  22.     <url-pattern>/login.do</url-pattern>  
  23.   </servlet-mapping>  
  24.   <welcome-file-list>  
  25.     <welcome-file>login.jsp</welcome-file>  
  26.   </welcome-file-list>  
  27. </web-app>  
  28. </SPAN>  
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" 	xmlns="http://java.sun.com/xml/ns/javaee" 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <filter>  <filter-name>loginFilter</filter-name>  <filter-class>com.login.servlet.IndexFilter</filter-class>  </filter>  <filter-mapping>  <filter-name>loginFilter</filter-name>  <url-pattern>/index.jsp</url-pattern>  </filter-mapping>  <servlet>    <servlet-name>LoginServlet</servlet-name>    <servlet-class>com.login.servlet.LoginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/login.do</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>login.jsp</welcome-file>  </welcome-file-list></web-app>

 看见了没有,上面的filter匹配路径只是针对一个页面,与通常写/*匹配所有请求到达之前是不一样的写法哦

  主页面:main.jsp

Html代码 复制代码 收藏代码
  1. <SPAN style="FONT-SIZE: medium"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <html>  
  3.   <head>  
  4.      <title>My JSP ‘maiin.jsp‘ starting page</title>  
  5.   </head>  
  6.   <body>  
  7.     登录成功,欢迎${username}的到来   
  8.   </body>  
  9. </html>  
  10. </SPAN>  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html>  <head>     <title>My JSP ‘maiin.jsp‘ starting page</title>  </head>  <body>    登录成功,欢迎${username}的到来  </body></html>

 

 输入地址:http://localhost:8080/WebApp/login.jsp出现登录页面

 然后输入:admin,123456 ,选择一个保存日期

 这样第一次登录成功之后,是经由LoginServlet处理了,由于选择了日期,所以Cookie中保存了用户信息,所以之后再输入同样地址后,不会出现登录页面,就不再经过LoginServlet处理【因为LoginServlet处理的是登陆页面上登录按钮请求的】,而直接提前交由IndexFilter处理,直接进入主页面,明白了么