重大改版
 鱼翔空 2012-04-26 servlet/jsp|   0 1004 
文章评分 90 次,平均分 5.0

使用过滤器和session,cookies写的自动登录

autoLogin.jsp页面


<%@ page language="java"  contentType="text/html;charset=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>
    <title>自动登录</title>
  </head>
  <%
      String username="";
      String userpwd="";
      Integer maxTime=0;
                                                
      Cookie[] cookies=request.getCookies();
      if(cookies!=null&&cookies.length>0){
          for(Cookie c:cookies){
              if("username".equals(c.getName())){
                  username=c.getValue();
              }
              if("userpwd".equals(c.getName())){
                  userpwd=c.getValue();
              }
              if("maxTime".equals(c.getName())){
                  String smaxTime=c.getValue();
                  if(smaxTime!=null&&!"".equals(smaxTime)){
                      maxTime=Integer.parseInt(smaxTime);
                      pageContext.setAttribute("maxTime",maxTime);
                  }
              }
          }
      }
                                                
  %>
  <body>
    <form action="${pageContext.request.contextPath }/autoLoginServlet" method="post">
       用户名:<input type="text" name="username"  value="<%=username %>"><br/>
       密 码:<input type="password" name="userpwd" value="<%=userpwd %>"><br>
       记住密码:<input type="checkbox" name="flag" checked=false> 保存时间
       <input type="radio" name="maxTime" value="${60*60*24 }" ${(maxTime==60*60*24)?"checked":"" } >一天
       <input type="radio" name="maxTime" value="${60*60*24*7 }" ${(maxTime==60*60*24*7)?"checked":"" }  >一周
       <input type="radio" name="maxTime" value="${60*60*24*30 }" ${(maxTime==60*60*24*30)?"checked":"" } >一月
       <input type="radio" name="maxTime" value="${60*60*24*180 }" ${(maxTime==60*60*24*180)?"checked":"" } >半年<br>
       ${maxTime }
     <input type="submit" name="btn" value="提交"/>
     </form>  
    </body>
</html>

web.xml内容

<?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">
                
 <context-param>
    <description>不登录就可以访问的连接</description>
    <param-name>noCheckUrl</param-name>
    <param-value>/autoLogin.jsp,/autoLoginServlet</param-value>
 </context-param>
                
  <!-- 配置粗粒度权限过滤器 -->
 <filter>
    <filter-name>AtuoLoginFilter</filter-name>
    <filter-class>com.yxkong.filter.AtuoLoginFilter</filter-class>
 </filter>
 <filter-mapping>
    <filter-name>AtuoLoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>
                
  <servlet>
    <servlet-name>AutoLoginServlet</servlet-name>
    <servlet-class>com.yxkong.web.AutoLoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AutoLoginServlet</servlet-name>
    <url-pattern>/autoLoginServlet</url-pattern>
  </servlet-mapping>
                 
</web-app>

自动登录拦截器

public class AtuoLoginFilter implements Filter {
              
    // 不登录允许访问的连接
    private List<String> list = null;
              
    public void init(FilterConfig filterConfig) throws ServletException {
        list = new ArrayList<String>();
        ServletContext sc = filterConfig.getServletContext();
              
        String noCheckUrl = sc.getInitParameter("noCheckUrl");
        String[] noCheckUrlArr = noCheckUrl.split(",");
              
        list = Arrays.asList(noCheckUrlArr);
              
    }
              
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
              
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
              
        String path = req.getRequestURI();
                      
        path = path.substring(path.indexOf("/", 1));
        // 只要是list集合中的,不管登录没有登录都可以访问
        if (list != null && list.size() > 0 && list.contains(path)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果session存在获取,不存在不新建session
        HttpSession session = req.getSession(false);
        User user = null;
        if (session != null) {
            user = (User) session.getAttribute("user");
        }
              
        // 已经存在用户的session
        if (user != null) {
            chain.doFilter(request, response);
            return;
        } else {
            // 获取客户端cookie
            user = new User();
            String username = "";
            String userpwd = "";
            String smaxTime = "";
            Cookie[] cookies = req.getCookies();
            // 遍历cookies,如果存在对应的cookie则取出
            if (cookies!=null&&cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if ("username".equals(cookie.getName())) {
                        username = cookie.getValue();
                    }
                    if ("userpwd".equals(cookie.getName())) {
                        userpwd = cookie.getValue();
                    }
                    if ("maxTime".equals(cookie.getName())) {
                        smaxTime = cookie.getValue();
                    }
                }
            }
            // 客户端存在对应的cookie
            if (!"".equals(username) && !"".equals(userpwd)
                    && !"".equals(smaxTime)) {
                // 这里可以判断得到的用户名和密码是否和数据库中的相同,如果相同则存入session,如果不同则跳转到登录页面并提示
                user.setUsername(username);
                user.setUserpwd(userpwd);
                // 将从cookie中获得到得值存到session中
                              
                session=req.getSession();
                session.setAttribute("user", user);
              
                chain.doFilter(request, response);
                return;
            } else {
                resp.sendRedirect(req.getContextPath() + "/autoLogin.jsp");
            }
        }
    }
    public void destroy() {
    }
}

自动登录servlet

public class AutoLoginServlet 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 userpwd = request.getParameter("userpwd");
        String sflag = request.getParameter("flag");
        String smaxTime = request.getParameter("maxTime");
            
        // 是否保存用户名和密码的标记
        Boolean flag = false;
        if (sflag != null && !"".equals(sflag)) {
            flag = true;
        }
        // 保存密码的时间
        int maxTime = 0;
        if (smaxTime != null && !"".equals(smaxTime)) {
            maxTime = Integer.parseInt(smaxTime);
            // 如果没有选上记住密码,但是选上了记住时间,则默认记住密码
            flag = true;
        }
        User user = null;
        // 输入用户名和密码则执行下面的
        if (username != null && !"".equals(username) && userpwd != null
                && !"".equals(userpwd)) {
            
            // 在此处可以添加用户名和密码的验证,如果用户名和密码正确则保存用户到bean并保存用户名和密码到session中
            user = new User();
            user.setUsername(username);
            user.setUserpwd(userpwd);
            
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            
            // 如果选中了记住密码,且记住时间不为空 执行记住cookie
            if (flag && maxTime > 0) {
                Cookie usernameCookie = new Cookie("username", username);
                // 设置cookie保存路径
                usernameCookie.setPath(request.getContextPath());
                usernameCookie.setMaxAge(maxTime);
            
                Cookie userpwdCookie = new Cookie("userpwd", userpwd);
                userpwdCookie.setPath(request.getContextPath());
                userpwdCookie.setMaxAge(maxTime);
            
                Cookie maxTimeCookie = new Cookie("maxTime", smaxTime);
                maxTimeCookie.setPath(request.getContextPath());
                maxTimeCookie.setMaxAge(maxTime);
                response.addCookie(maxTimeCookie);
            
                // 将cookie添加到响应头
                response.addCookie(usernameCookie);
                response.addCookie(userpwdCookie);
            }
            request.getRequestDispatcher("main.jsp").forward(request, response);
        } else {
            // 提示用户输入用户名和密码
        }
    }
}


 

除特别注明外,本站所有文章均为我要编程原创,转载请注明出处来自http://5ycode.com/article/123.html

关于
该用户很懒!
切换注册

登录

忘记密码 ?

切换登录

注册

扫一扫二维码分享