首页 > Java开发 > 使用过滤器实现自动登录

使用过滤器实现自动登录

使用过滤器实现自动登录

一、自动登录实现原理。

(1)当用户勾选“记住密码”时,先登录,然后把账号密码记录到客户端的Cookie中,下次访问任意页面的时候使用过滤器从客户端的Cookie中获取账号密码进行登录,最后把Cookie时间刷新一遍。

(2)当用户不勾选“记住密码”时,先登录,然后把Cookie从客户端中销毁。

二、自动登录简单案例。

登录的Servlet:

package com.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;

import com.service.UserService;

public class LoginServlet extends HttpServlet {

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

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取登录页面的属性
        String userName=request.getParameter("userName");
        String passWord=request.getParameter("passWord");
        String autoLogin=request.getParameter("autoLogin");
        //实例化自己定义的登录Service类
        UserService loginService=new UserService();
        boolean flag=loginService.login(userName, passWord);
        if(flag){//登录成功执行该语句块
            if(autoLogin!=null&&!autoLogin.equals("null")){//如果勾选了“记录密码”,把账号密码存到客户端Cookie中
                Cookie c1=new Cookie("userName",userName);
                Cookie c2=new Cookie("passWord",passWord);
                c1.setMaxAge(60*60);
                c2.setMaxAge(60*60);
                response.addCookie(c1);
                response.addCookie(c2);
            }else{//如何不勾选“记录密码”则把客户端的Cookie替换掉,并设置生存周期为0
                Cookie c1=new Cookie("userName",null);
                Cookie c2=new Cookie("passWord",null);
                c1.setMaxAge(0);
                c2.setMaxAge(0);
                response.addCookie(c1);
                response.addCookie(c2);
            }
            request.getSession().setAttribute("userName", userName);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }else{
            response.sendRedirect("login.jsp");
        }
    }
}

过滤器:

package com.filter;

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;

import com.service.UserService;

public class LoginFilter 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;
        String userName=(String) request.getSession().getAttribute("userName");//获取Session的值
        String passWord=null;
        if(userName==null){//如果未登录,获取客户端Cookie,并登录
            Cookie[] cookies=request.getCookies();
            if(cookies!=null){//获取客户端Cookie
                for(Cookie c:cookies){
                    if(c.getName().equals("userName")){
                        userName=c.getValue();
                    }
                    if(c.getName().equals("passWord")){
                        passWord=c.getValue();
                    }
                }
            }
            if(userName!=null&&passWord!=null){//如何账号密码获取成功,则进行登录
                UserService loginService=new UserService();
                boolean flag=loginService.login(userName, passWord);
                if(flag){//登录成功刷新客户端Cookie
                    Cookie c1=new Cookie("userName",userName);
                    Cookie c2=new Cookie("passWord",passWord);
                    c1.setMaxAge(60*60);
                    c2.setMaxAge(60*60);
                    response.addCookie(c1);
                    response.addCookie(c2);
                    request.getSession().setAttribute("userName", userName);
                }
            }
        }
        arg2.doFilter(request,response);
    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }
}

配置文件:

<?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">
  <display-name></display-name>

  <filter>
      <filter-name>login</filter-name>
      <filter-class>com.filter.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>login</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.servlet.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

login.jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'login.jsp' starting page</title>
</head>

<body>
    <form action="login" method="post">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="userName" /></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="passWord" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="checkbox" name="autoLogin" value="auto">记住密码</td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" name="submit" value="登录" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

index.jsp页面:

<%@ 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>
        登录成功,欢迎${sessionScope.userName}的到来
  </body>
</html>

本文固定链接: http://www.devba.com/index.php/archives/591.html | 开发吧

使用过滤器实现自动登录:目前有2 条留言

  1. 沙发
    Birdy:

    請問大大import com.service.UserService;
    這裡面的UserService內容部分是?
    我自己亂猜想說是不是類似下面這樣子 因為你的code部分沒有貼出來
    所以想問問看
    public class UserService {
    public boolean login(String gen_id, String gen_pwd) {
    return true;
    }
    }

    2013-07-31 下午 11:24
    • 孤风一剑:

      :smile: 可以这样,你可以自由发挥,也许你写出来的比我的还好的多呢。

      2013-08-01 下午 1:37