Filter过滤器+cookie实现自动登录和安全登录

实现思想:

我们只要登陆成功就把登录信息存储到cookie中,将用户名存入session中,下一次进入界面只要通过AutoLoginfilter拦截获取cookie,如果有登录信息的cookie就取出来,进行自动登录处理,每一次访问通过secureLogin的filter进行拦截,查询session中的name属性值的容器中有没有值,如果没有重定向到登录页面,如果有就放行

登录界面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>


  </head>

  <body>
  <c:if test="${!empty error}"><!-- 如果有登录错误信息则显示以下内容 -->
    ${error }<br/>
    <c:remove var="error" scope="session"/><!-- 之后要清除掉error信息 -->

  </c:if>
  <c:if test="${empty sessionScope.name}" var="boo"><!-- 如果没有登录则显示登录页面 -->
     <form action="<c:url value="/LoginServlet"/>" method="post">
        <input type="text" name="name" /> 
        <input type="password" name="password" /> 
        <input type="submit" value="登录" />
            自动登录:
            <input type="radio" name="time" value="0"/>不自动登录
            <input type="radio" name="time" value="1"/>1天内自动登录
            <input type="radio" name="time" value="7" checked="checked"/>7天内自动登录
    </form>
  </c:if>
  <c:if test="${!boo}"><!-- 如果登录成功就显示以下内容 -->
    欢迎你,${sessionScope.name }<br/>
    <a href="<c:url value='/jsps/safe/1.jsp'/>">会员页面1</a>
    <a href="<c:url value='/jsps/safe/2.jsp'/>">会员页面2</a>
    <a href="<c:url value='/autocancelservlet'/>">清除自动登录</a>
  </c:if>
  </body>
</html>

LoginServlet:

package cn.hncu.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

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

/**
 * 自动登录的方法,在登录时把用户信息放到cookie中,在下次访问页面时,通过过滤器获取cookie 自动登录
 * 
 * 
 **/
public class LoginServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

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

        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String time = request.getParameter("time");

        if (name != null && name.startsWith("hncu")) {
            if (password != null && password.length() > 3) {
                request.getSession().setAttribute("name", name);// 往session容器中存放代表登录的信息

                // ///下面为实现自动登录,创建一个cookie
                name = URLEncoder.encode(name, "utf-8");// 设置写入cookie时的编码
                password = URLEncoder.encode(password, "utf-8");
                Cookie c = new Cookie("autoLogin", name + "," + password);
                c.setPath(request.getContextPath());

                // 设置时间
                int t = 60 * 60 * 24 * Integer.valueOf(time);
                // 设置cookie最大时间
                c.setMaxAge(t);
                // 添加cookie
                response.addCookie(c);
            } else {
                request.getSession().setAttribute("error", "密码错误");
            }
        } else {
            request.getSession().setAttribute("error", "用户名不存在");
        }
        response.sendRedirect(request.getContextPath()
                + "/jsps/safe/welcome.jsp");
    }

}

secureLogin:

package cn.hncu.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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 这个过滤器是用来做防未登录访问的
 * */
public class secureLogin implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (req.getSession().getAttribute("name") == null) {
            resp.sendRedirect(req.getContextPath() + "/jsps/login.jsp");
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}

AutoLoginFilter:

package cn.hncu.filter;

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

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 AutoLoginFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (req.getSession().getAttribute("name") == null) {// 还没登录,尝试从cookie中获取name和pwd来登录
            Cookie cs[] = req.getCookies();
            if (cs != null) {
                for (Cookie c : cs) {
                    if (c.getName().equals("autoLogin")) {
                        System.out.println("找到了自动登录的cookie");
                        String val = c.getValue();
                        String vals[] = val.split(",");
                        String name = URLDecoder.decode(vals[0], "utf-8");// 设置读取解析编码
                        String password = URLDecoder.decode(vals[1], "utf-8");
                        if (name != null && name.startsWith("hncu")
                                && password != null && password.length() > 3) {
                            req.getSession().setAttribute("name", name);
                            break;
                        }
                    }
                }
            }
        }
        chain.doFilter(request, response);// 放行
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值