必威体育Betway必威体育官网
当前位置:首页 > IT技术

使用过滤器(Filter)实现用户自动登录

时间:2019-09-04 08:40:00来源:IT技术作者:seo实验室小编阅读:76次「手机版」
 

自动登录

使用过滤器(Filter)实现用户自动登录

应用场景:现在大部分网站都支持一段时间类用户自动登陆功能,移动端APP应用几乎都需要自动登陆,试想一下如果你每天打开微信或者QQ等APP时每次都需要手动输入用户名密码然后在登录,内心早已是一万匹草泥马.所以说自动登录功能对于提高用户体验时非常重要的.

那么下面我们就来自己实现一个简单的用户自定登录案列吧!

自动登陆案列分析

开发平台:Win10 64

开发语言:java

开发工具:Eclipse Oxygen版(2018 3月发布) 服务器: tomcat 7.0 , jdk1.8 数据库:mysql 5.5

相关工具包:

c3p0-0.9.1.2.jar(c3p0连接池jar包)commons-dbutils-1.4.jar(简化数据处理jar包,可以自己封装)jstl.jar(jstl jar包)mysql-connector-java-5.1.39-bin.jar(mysql驱动)standard.jar(jstl jar包)


1.准备数据

  
  create database autologin;
      use autologin;
      create table user(
          id int primary key auto_increment,
              username varchar(20),
              password varchar(20),
              birthday date,
              email varchar(60)
          );
          
      insert into user values(null,'Tom','123456','1990-10-18','[email protected]');
      insert into user values(null,'Jack','123456','1921-07-01','[email protected]');
      insert into user values(null,'Bob','123456','1990-02-22','[email protected]');

前端页面 login.jsp

  
  <%@page import="com.utils.CookieUtil"%>
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>登录页面</title>
  </head>
  <body>
      <%--如果用户已登录,直接掉转到首页 --%>
      <c:if test="${not empty user }">
          <jsp:forward page="/index.jsp"></jsp:forward>
      </c:if>
      <%--如果用户未登录就显示下面的页面 --%>
      <form action="${pagecontext.request.contextpath }/login" method="post">
          用户名<input type="text" name="username"><br>
          密码<input type="password" name="pwd"><br>
          自动登录<input type="checkbox" name="auto" value="on"><br>
          <input type="submit" value="登录">
      </form>
  </body>
  </html>

index.jsp

  
  <%@page import="com.bean.User"%>
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>首页</title>
  </head>
  <body>
   
      <%--判断是否已登录,如果已登录则显示欢迎XXX登录  注销   购物车 
          如果未登录,则显示  注册   登录
          
          怎么判断是否已登录?只要登录成功,就会将user对象存放到session中,所以判断session中是否有user就可以知道是否已登录
      --%>
      <c:if test="${not empty user }">
          <h1>欢迎你回来${user.username }!</h1>
          <a href="${pageContext.request.contextPath }/logout">注销</a>
          <a href="${pageContext.request.contextPath }/car.jsp">购物车</a>
      </c:if>
      
      <c:if test="${empty user }">
          <a href="${pageContext.request.contextPath }/register.jsp">注册</a>
          <a href="${pageContext.request.contextPath }/login.jsp">登录</a>
      </c:if>
      
  </body>
  </html>

car.jsp

  
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Insert title here</title>
  </head>
  <body>
      <c:if test="${empty user}">
          <jsp:forward page="/login.jsp"></jsp:forward>
      </c:if>
      <c:if test="${not empty user}">
      <h1>${user.username }欢迎来到我的购物车</h1>
      </c:if>
  </body>
  </html>

register.jsp

  
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>注册页面</title>
  </head>
  <body>
      <h1>欢迎加入我们!</h1>
  </body>
  </html>

服务端代码

LoginServlet.java

  package com.servlet;
  ​
  import java.io.IOException;
  import java.io.printwriter;
  ​
  import javax.servlet.ServletContext;
  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 javax.servlet.http.HttpSession;
  ​
  import com.bean.User;
  import com.service.UserService;
   
  import com.utils.CookieUtil;
  ​
  /**
   * 处理用户登录的Servlet
   */
  public class LoginServlet extends HttpServlet {
      private static final long serialversionuid = 1L;
   
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          response.setcontenttype("text/html;charset=utf-8");
          String username = request.getparameter("username");
          String password = request.getParameter("pwd");
      
          String auto = request.getParameter("auto");
          HttpSession session = request.getSession();
          //调用业务层方法登录
          UserService service=new UserService();
          User user=service.doLogin(username,password);
          
           System.out.println(user);
          
          if (user!=null) {
              
              //当用户选择自动登陆后,我们怎样才能实现用户自动登陆成功呢?首先将用户登录成功的用户名和密码存入cookie并发送到客户端
              Cookie cookie = CookieUtil.createCookie("info",username+"#"+password,7*24*60*60,request.getContextPath());
              //判断用户是否选择了自动登陆
              if (!"on".equalsignorecase(auto)) {
                  //如果用户没有选择自动登陆,则需要把cookie清空
                  cookie.setMaxAge(0);
              }
              //把cookie发送到客服端
              response.addCookie(cookie);
               
              //登录成功,把user存入session中
              session.setattribute("user",user);
              response.sendredirect(request.getContextPath()+"/index.jsp");
          }else {
              
              response.sendRedirect(request.getContextPath()+"/login.jsp");
          }
      
      }
  ​
       
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doGet(request, response);
      }
  ​
  }

UserService.java

  
  package com.service;
  ​
  import java.sql.SQLException;
  import java.util.List;
  ​
  import com.bean.User;
  import com.dao.UserDao;
  ​
  public class UserService {
  ​
      public User doLogin(String username, String password) {
          UserDao dao = new UserDao();
          User user=null;
          try {
              user = dao.doLogin(username, password);
          } catch (SQLException e) {
              e.printstacktrace();
          }
          return user;
      }
  ​
  ​
  }

UserDao.java

  
  package com.dao;
  ​
  import java.sql.SQLException;
  import org.apache.commons.dbutils.QueryRunner;
  import org.apache.commons.dbutils.handlers.BeanHandler;
  import com.bean.User;
  import com.utils.C3P0Utils;
  ​
  public class UserDao {
  ​
      public User doLogin(String username, String password) throws SQLException {
          QueryRunner runner = new QueryRunner(C3P0Utils.getdatasource());
          String sql = "select * from user where username=? and password=?";
       
          User user = runner.query(sql, new BeanHandler<>(User.class), username, password);
  ​
          return user;
      }
  ​
  }

AutoLoginFilter.java

  
  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.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.HttpSession;
  ​
  import com.bean.User;
  import com.service.UserService;
  import com.utils.CookieUtil;
  ​
  /**
   * 如果进入这个过滤器之前已经登录成功,直接放行,怎么判断有没有登录成功,就看Session中是否有user对象
   */
  public class AutoLoginFilter implements Filter {
  ​
      public void destroy() {
  ​
      }
  ​
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
              throws IOException, ServletException {
          // 1.判断是否已登录
          // 1.1将request对象强转成HttpServletRequest类型
          HttpServletRequest rqs = (HttpServletRequest) request;
          // 1.2获取session对象
          HttpSession session = rqs.getSession();
          // 1.3获取session中存放的user
          User user = (User) session.getattribute("user");
          // 1.4判断user是否为null
          if (user == null) {
              // 未登录
              // 判断是否需要自动登录----->就看cookie中是否有"info"
              String info = CookieUtil.getCookieValue(rqs, "info");
              if (info != null) {
                  // 需要自动登录,如果不需要自动登录同样也放行
                  // 取出用户名和密码
                  String username = info.split("#")[0];
                  String password = info.split("#")[1];
  ​
                  // 调用业务层方法登录
                  UserService service = new UserService();
                  user = service.doLogin(username, password);
  ​
                  // 很重要的一步,将user存放到session中
                  session.setAttribute("user", user);
              }
          }
  ​
          chain.doFilter(request, response);
      }
  ​
      public void init(FilterConfig fConfig) throws ServletException {
      }
  ​
  }

LogoutServlet.java

  
  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 javax.servlet.http.HttpSession;
  ​
  import com.utils.CookieUtil;
  ​
  /**
   * 处理注销功能servlet
   */
  public class LogoutServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
  ​
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          //注销其实就是将用户从session中移出
          HttpSession session = request.getSession();
          //立即销毁Session,并且清楚客服端的cookie
          session.invalidate();
          Cookie cookie = CookieUtil.createCookie("info","hello", 0, request.getContextPath());
          response.addCookie(cookie);
          //跳转到登录页面
          response.sendRedirect(request.getContextPath()+"/login.jsp");
      }
  ​
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          doGet(request, response);
      }
  ​
  }

工具类

CookieUtil

  
  package com.utils;
  ​
  import javax.servlet.http.Cookie;
  import javax.servlet.http.HttpServletRequest;
  ​
  public class CookieUtil {
      /**
       * 创建并配置Cookie
       * @param name  cookie的name
       * @param value  cookie的value
       * @param time  有效期,秒
       * @param path  有效范围
       * @return
       */
      public static Cookie createCookie(String name,String value,int time,String path){
          Cookie cookie = new Cookie(name, value);
          //Cookie的一些其他设置,可以设置最大有效期,可以设置有效范围(在哪里能够获取到该Cookie信息)
          //设置有效期
          cookie.setMaxAge(time);
          //设置有效范围
          cookie.setPath(path);//只能在CookieDemo02这个Servlet中获取该Cookie的信息
          return cookie;
      }
      
      /**
       * 获取Cookie里面的值
       */
      public static String getCookieValue(HttpServletRequest request,String cookieName){
          Cookie[] cookies = request.getCookies();
          String value = null;
          if (cookies != null) {
              for (Cookie cookie : cookies) {
                  if (cookieName.equals(cookie.getName())) {
                      //确实是咱们要获取的那个名为username的cookie对象
                      value = cookie.getValue();
                  }
              }
          }
          return value;
      }
  }

C3P0Utils.java

  
  package com.utils;
  ​
  import java.sql.Connection;
  import java.sql.Preparedstatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  ​
  import javax.sql.DataSource;
  ​
  import com.mchange.v2.c3p0.CombopooledDataSource;
  ​
  public class C3P0Utils {
  /**
   * c3p0连接池工具类
   */
      
      private static ComboPooledDataSource dataSource;
      
      static {
          dataSource=new ComboPooledDataSource();
      }
      
      public static DataSource getDataSource() {
          
          return dataSource;
      }
      
      public static Connection getConnection() {
          Connection con=null;
          try {
               con= dataSource.getConnection();
          } catch (SQLException e) {
               System.out.println(e);
               
               throw new runtimeexception("数据库链接异常,请联系技术人员");
          }
          return con;
      }
      
      public static void close(ResultSet resultSet,PreparedStatement ps,Connection con) {
          
          if (resultSet!=null) {
              try {
                  resultSet.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
          
          if (ps!=null) {
              try {
                  ps.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
          
          if (con!=null) {
              try {
                  con.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
      }
  }

数据库连接池配置文件

c3p0-config.xml

  
  <?xml version="1.0" encoding="UTF-8"?>
  <c3p0-config>
      <default-config>
          <property name="initialPoolSize">10</property>
          <property name="user">root</property>
          <property name="password">root</property>
          <property name="jdbcUrl">jdbc:mysql://localhost:3306/autologin?characterEncoding=utf8</property>
          <property name="driverClass">com.mysql.jdbc.Driver</property>
      </default-config> 
  </c3p0-config>

使用过滤器(Filter)实现用户自动登录

应用场景:现在大部分网站都支持一段时间类用户自动登陆功能,移动端APP应用几乎都需要自动登陆,试想一下如果你每天打开微信或者QQ等APP时每次都需要手动输入用户名密码然后在登录,内心早已是一万匹草泥马.所以说自动登录功能对于提高用户体验时非常重要的.

那么下面我们就来自己实现一个简单的用户自定登录案列吧!

自动登陆案列分析

使用过滤器(Filter)实现用户自动登录

应用场景:现在大部分网站都支持一段时间类用户自动登陆功能,移动端APP应用几乎都需要自动登陆,试想一下如果你每天打开微信或者QQ等APP时每次都需要手动输入用户名密码然后在登录,内心早已是一万匹草泥马.所以说自动登录功能对于提高用户体验时非常重要的.

那么下面我们就来自己实现一个简单的用户自定登录案列吧!

自动登陆案列分析

开发平台:win10 64位

开发语言:Java

开发工具:Eclipse Oxygen版(2018 3月发布) 服务器: tomcat 7.0 , jdk1.8 数据库:Mysql 5.5

相关工具包:

c3p0-0.9.1.2.jar(c3p0连接池jar包)commons-dbutils-1.4.jar(简化数据处理jar包,可以自己封装)jstl.jar(jstl jar包)mysql-connector-java-5.1.39-bin.jar(mysql驱动)standard.jar(jstl jar包)


1.准备数据

  
  create database autologin;
      use autologin;
      create table user(
          id int primary key auto_increment,
              username varchar(20),
              password varchar(20),
              birthday date,
              email varchar(60)
          );
          
      insert into user values(null,'Tom','123456','1990-10-18','[email protected]');
      insert into user values(null,'Jack','123456','1921-07-01','[email protected]');
      insert into user values(null,'Bob','123456','1990-02-22','[email protected]');

前端页面 login.jsp

  
  <%@page import="com.utils.CookieUtil"%>
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>登录页面</title>
  </head>
  <body>
      <%--如果用户已登录,直接掉转到首页 --%>
      <c:if test="${not empty user }">
          <jsp:forward page="/index.jsp"></jsp:forward>
      </c:if>
      <%--如果用户未登录就显示下面的页面 --%>
      <form action="${pageContext.request.contextPath }/login" method="post">
          用户名<input type="text" name="username"><br>
          密码<input type="password" name="pwd"><br>
          自动登录<input type="checkbox" name="auto" value="on"><br>
          <input type="submit" value="登录">
      </form>
  </body>
  </html>

index.jsp

  
  <%@page import="com.bean.User"%>
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>首页</title>
  </head>
  <body>
   
      <%--判断是否已登录,如果已登录则显示欢迎XXX登录  注销   购物车 
          如果未登录,则显示  注册   登录
          
          怎么判断是否已登录?只要登录成功,就会将user对象存放到session中,所以判断session中是否有user就可以知道是否已登录
      --%>
      <c:if test="${not empty user }">
          <h1>欢迎你回来${user.username }!</h1>
          <a href="${pageContext.request.contextPath }/logout">注销</a>
          <a href="${pageContext.request.contextPath }/car.jsp">购物车</a>
      </c:if>
      
      <c:if test="${empty user }">
          <a href="${pageContext.request.contextPath }/register.jsp">注册</a>
          <a href="${pageContext.request.contextPath }/login.jsp">登录</a>
      </c:if>
      
  </body>
  </html>

car.jsp

  
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Insert title here</title>
  </head>
  <body>
      <c:if test="${empty user}">
          <jsp:forward page="/login.jsp"></jsp:forward>
      </c:if>
      <c:if test="${not empty user}">
      <h1>${user.username }欢迎来到我的购物车</h1>
      </c:if>
  </body>
  </html>

register.jsp

  
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>注册页面</title>
  </head>
  <body>
      <h1>欢迎加入我们!</h1>
  </body>
  </html>

服务端代码

LoginServlet.java

  package com.servlet;
  ​
  import java.io.IOException;
  import java.io.PrintWriter;
  ​
  import javax.servlet.ServletContext;
  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 javax.servlet.http.HttpSession;
  ​
  import com.bean.User;
  import com.service.UserService;
   
  import com.utils.CookieUtil;
  ​
  /**
   * 处理用户登录的Servlet
   */
  public class LoginServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
   
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("text/html;charset=utf-8");
          String username = request.getParameter("username");
          String password = request.getParameter("pwd");
      
          String auto = request.getParameter("auto");
          HttpSession session = request.getSession();
          //调用业务层方法登录
          UserService service=new UserService();
          User user=service.doLogin(username,password);
          
           System.out.println(user);
          
          if (user!=null) {
              
              //当用户选择自动登陆后,我们怎样才能实现用户自动登陆成功呢?首先将用户登录成功的用户名和密码存入cookie并发送到客户端
              Cookie cookie = CookieUtil.createCookie("info",username+"#"+password,7*24*60*60,request.getContextPath());
              //判断用户是否选择了自动登陆
              if (!"on".equalsIgnoreCase(auto)) {
                  //如果用户没有选择自动登陆,则需要把cookie清空
                  cookie.setMaxAge(0);
              }
              //把cookie发送到客服端
              response.addCookie(cookie);
               
              //登录成功,把user存入session中
              session.setAttribute("user",user);
              response.sendRedirect(request.getContextPath()+"/index.jsp");
          }else {
              
              response.sendRedirect(request.getContextPath()+"/login.jsp");
          }
      
      }
  ​
       
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doGet(request, response);
      }
  ​
  }

UserService.java

  
  package com.service;
  ​
  import java.sql.SQLException;
  import java.util.List;
  ​
  import com.bean.User;
  import com.dao.UserDao;
  ​
  public class UserService {
  ​
      public User doLogin(String username, String password) {
          UserDao dao = new UserDao();
          User user=null;
          try {
              user = dao.doLogin(username, password);
          } catch (SQLException e) {
              e.printStackTrace();
          }
          return user;
      }
  ​
  ​
  }

UserDao.java

  
  package com.dao;
  ​
  import java.sql.SQLException;
  import org.apache.commons.dbutils.QueryRunner;
  import org.apache.commons.dbutils.handlers.BeanHandler;
  import com.bean.User;
  import com.utils.C3P0Utils;
  ​
  public class UserDao {
  ​
      public User doLogin(String username, String password) throws SQLException {
          QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
          String sql = "select * from user where username=? and password=?";
       
          User user = runner.query(sql, new BeanHandler<>(User.class), username, password);
  ​
          return user;
      }
  ​
  }

AutoLoginFilter.java

  
  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.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.HttpSession;
  ​
  import com.bean.User;
  import com.service.UserService;
  import com.utils.CookieUtil;
  ​
  /**
   * 如果进入这个过滤器之前已经登录成功,直接放行,怎么判断有没有登录成功,就看Session中是否有user对象
   */
  public class AutoLoginFilter implements Filter {
  ​
      public void destroy() {
  ​
      }
  ​
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
              throws IOException, ServletException {
          // 1.判断是否已登录
          // 1.1将request对象强转成HttpServletRequest类型
          HttpServletRequest rqs = (HttpServletRequest) request;
          // 1.2获取session对象
          HttpSession session = rqs.getSession();
          // 1.3获取session中存放的user
          User user = (User) session.getAttribute("user");
          // 1.4判断user是否为null
          if (user == null) {
              // 未登录
              // 判断是否需要自动登录----->就看cookie中是否有"info"
              String info = CookieUtil.getCookieValue(rqs, "info");
              if (info != null) {
                  // 需要自动登录,如果不需要自动登录同样也放行
                  // 取出用户名和密码
                  String username = info.split("#")[0];
                  String password = info.split("#")[1];
  ​
                  // 调用业务层方法登录
                  UserService service = new UserService();
                  user = service.doLogin(username, password);
  ​
                  // 很重要的一步,将user存放到session中
                  session.setAttribute("user", user);
              }
          }
  ​
          chain.doFilter(request, response);
      }
  ​
      public void init(FilterConfig fConfig) throws ServletException {
      }
  ​
  }

LogoutServlet.java

  
  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 javax.servlet.http.HttpSession;
  ​
  import com.utils.CookieUtil;
  ​
  /**
   * 处理注销功能servlet
   */
  public class LogoutServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
  ​
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          //注销其实就是将用户从session中移出
          HttpSession session = request.getSession();
          //立即销毁Session,并且清楚客服端的cookie
          session.invalidate();
          Cookie cookie = CookieUtil.createCookie("info","hello", 0, request.getContextPath());
          response.addCookie(cookie);
          //跳转到登录页面
          response.sendRedirect(request.getContextPath()+"/login.jsp");
      }
  ​
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          doGet(request, response);
      }
  ​
  }

工具类

CookieUtil

  
  package com.utils;
  ​
  import javax.servlet.http.Cookie;
  import javax.servlet.http.HttpServletRequest;
  ​
  public class CookieUtil {
      /**
       * 创建并配置Cookie
       * @param name  cookie的name
       * @param value  cookie的value
       * @param time  有效期,秒
       * @param path  有效范围
       * @return
       */
      public static Cookie createCookie(String name,String value,int time,String path){
          Cookie cookie = new Cookie(name, value);
          //Cookie的一些其他设置,可以设置最大有效期,可以设置有效范围(在哪里能够获取到该Cookie信息)
          //设置有效期
          cookie.setMaxAge(time);
          //设置有效范围
          cookie.setPath(path);//只能在CookieDemo02这个Servlet中获取该Cookie的信息
          return cookie;
      }
      
      /**
       * 获取Cookie里面的值
       */
      public static String getCookieValue(HttpServletRequest request,String cookieName){
          Cookie[] cookies = request.getCookies();
          String value = null;
          if (cookies != null) {
              for (Cookie cookie : cookies) {
                  if (cookieName.equals(cookie.getName())) {
                      //确实是咱们要获取的那个名为username的cookie对象
                      value = cookie.getValue();
                  }
              }
          }
          return value;
      }
  }

C3P0Utils.java

  
  package com.utils;
  ​
  import java.sql.Connection;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  ​
  import javax.sql.DataSource;
  ​
  import com.mchange.v2.c3p0.ComboPooledDataSource;
  ​
  public class C3P0Utils {
  /**
   * c3p0连接池工具类
   */
      
      private static ComboPooledDataSource dataSource;
      
      static {
          dataSource=new ComboPooledDataSource();
      }
      
      public static DataSource getDataSource() {
          
          return dataSource;
      }
      
      public static Connection getConnection() {
          Connection con=null;
          try {
               con= dataSource.getConnection();
          } catch (SQLException e) {
               System.out.println(e);
               
               throw new RuntimeException("数据库链接异常,请联系技术人员");
          }
          return con;
      }
      
      public static void close(ResultSet resultSet,PreparedStatement ps,Connection con) {
          
          if (resultSet!=null) {
              try {
                  resultSet.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
          
          if (ps!=null) {
              try {
                  ps.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
          
          if (con!=null) {
              try {
                  con.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
      }
  }

数据库连接池配置文件

c3p0-config.xml

  
  <?xml version="1.0" encoding="UTF-8"?>
  <c3p0-config>
      <default-config>
          <property name="initialPoolSize">10</property>
          <property name="user">root</property>
          <property name="password">root</property>
          <property name="jdbcUrl">jdbc:mysql://localhost:3306/autologin?characterEncoding=utf8</property>
          <property name="driverClass">com.mysql.jdbc.Driver</property>
      </default-config> 
  </c3p0-config>

使用过滤器(Filter)实现用户自动登录

应用场景:现在大部分网站都支持一段时间类用户自动登陆功能,移动端APP应用几乎都需要自动登陆,试想一下如果你每天打开微信或者QQ等APP时每次都需要手动输入用户名密码然后在登录,内心早已是一万匹草泥马.所以说自动登录功能对于提高用户体验时非常重要的.

那么下面我们就来自己实现一个简单的用户自定登录案列吧!

自动登陆案列分析

使用过滤器(Filter)实现用户自动登录

应用场景:现在大部分网站都支持一段时间类用户自动登陆功能,移动端APP应用几乎都需要自动登陆,试想一下如果你每天打开微信或者QQ等APP时每次都需要手动输入用户名密码然后在登录,内心早已是一万匹草泥马.所以说自动登录功能对于提高用户体验时非常重要的.

那么下面我们就来自己实现一个简单的用户自定登录案列吧!

自动登陆案列分析

开发平台:win10 64位

开发语言:Java

开发工具:Eclipse Oxygen版(2018 3月发布) 服务器: tomcat 7.0 , jdk1.8 数据库:Mysql 5.5

相关工具包:

c3p0-0.9.1.2.jar(c3p0连接池jar包)commons-dbutils-1.4.jar(简化数据处理jar包,可以自己封装)jstl.jar(jstl jar包)mysql-connector-java-5.1.39-bin.jar(mysql驱动)standard.jar(jstl jar包)


1.准备数据

  
  create database autologin;
      use autologin;
      create table user(
          id int primary key auto_increment,
              username varchar(20),
              password varchar(20),
              birthday date,
              email varchar(60)
          );
          
      insert into user values(null,'Tom','123456','1990-10-18','[email protected]');
      insert into user values(null,'Jack','123456','1921-07-01','[email protected]');
      insert into user values(null,'Bob','123456','1990-02-22','[email protected]');

前端页面 login.jsp

  
  <%@page import="com.utils.CookieUtil"%>
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>登录页面</title>
  </head>
  <body>
      <%--如果用户已登录,直接掉转到首页 --%>
      <c:if test="${not empty user }">
          <jsp:forward page="/index.jsp"></jsp:forward>
      </c:if>
      <%--如果用户未登录就显示下面的页面 --%>
      <form action="${pageContext.request.contextPath }/login" method="post">
          用户名<input type="text" name="username"><br>
          密码<input type="password" name="pwd"><br>
          自动登录<input type="checkbox" name="auto" value="on"><br>
          <input type="submit" value="登录">
      </form>
  </body>
  </html>

index.jsp

  
  <%@page import="com.bean.User"%>
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>首页</title>
  </head>
  <body>
   
      <%--判断是否已登录,如果已登录则显示欢迎XXX登录  注销   购物车 
          如果未登录,则显示  注册   登录
          
          怎么判断是否已登录?只要登录成功,就会将user对象存放到session中,所以判断session中是否有user就可以知道是否已登录
      --%>
      <c:if test="${not empty user }">
          <h1>欢迎你回来${user.username }!</h1>
          <a href="${pageContext.request.contextPath }/logout">注销</a>
          <a href="${pageContext.request.contextPath }/car.jsp">购物车</a>
      </c:if>
      
      <c:if test="${empty user }">
          <a href="${pageContext.request.contextPath }/register.jsp">注册</a>
          <a href="${pageContext.request.contextPath }/login.jsp">登录</a>
      </c:if>
      
  </body>
  </html>

car.jsp

  
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Insert title here</title>
  </head>
  <body>
      <c:if test="${empty user}">
          <jsp:forward page="/login.jsp"></jsp:forward>
      </c:if>
      <c:if test="${not empty user}">
      <h1>${user.username }欢迎来到我的购物车</h1>
      </c:if>
  </body>
  </html>

register.jsp

  
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>注册页面</title>
  </head>
  <body>
      <h1>欢迎加入我们!</h1>
  </body>
  </html>

服务端代码

LoginServlet.java

  package com.servlet;
  ​
  import java.io.IOException;
  import java.io.PrintWriter;
  ​
  import javax.servlet.ServletContext;
  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 javax.servlet.http.HttpSession;
  ​
  import com.bean.User;
  import com.service.UserService;
   
  import com.utils.CookieUtil;
  ​
  /**
   * 处理用户登录的Servlet
   */
  public class LoginServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
   
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("text/html;charset=utf-8");
          String username = request.getParameter("username");
          String password = request.getParameter("pwd");
      
          String auto = request.getParameter("auto");
          HttpSession session = request.getSession();
          //调用业务层方法登录
          UserService service=new UserService();
          User user=service.doLogin(username,password);
          
           System.out.println(user);
          
          if (user!=null) {
              
              //当用户选择自动登陆后,我们怎样才能实现用户自动登陆成功呢?首先将用户登录成功的用户名和密码存入cookie并发送到客户端
              Cookie cookie = CookieUtil.createCookie("info",username+"#"+password,7*24*60*60,request.getContextPath());
              //判断用户是否选择了自动登陆
              if (!"on".equalsIgnoreCase(auto)) {
                  //如果用户没有选择自动登陆,则需要把cookie清空
                  cookie.setMaxAge(0);
              }
              //把cookie发送到客服端
              response.addCookie(cookie);
               
              //登录成功,把user存入session中
              session.setAttribute("user",user);
              response.sendRedirect(request.getContextPath()+"/index.jsp");
          }else {
              
              response.sendRedirect(request.getContextPath()+"/login.jsp");
          }
      
      }
  ​
       
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doGet(request, response);
      }
  ​
  }

UserService.java

  
  package com.service;
  ​
  import java.sql.SQLException;
  import java.util.List;
  ​
  import com.bean.User;
  import com.dao.UserDao;
  ​
  public class UserService {
  ​
      public User doLogin(String username, String password) {
          UserDao dao = new UserDao();
          User user=null;
          try {
              user = dao.doLogin(username, password);
          } catch (SQLException e) {
              e.printStackTrace();
          }
          return user;
      }
  ​
  ​
  }

UserDao.java

  
  package com.dao;
  ​
  import java.sql.SQLException;
  import org.apache.commons.dbutils.QueryRunner;
  import org.apache.commons.dbutils.handlers.BeanHandler;
  import com.bean.User;
  import com.utils.C3P0Utils;
  ​
  public class UserDao {
  ​
      public User doLogin(String username, String password) throws SQLException {
          QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
          String sql = "select * from user where username=? and password=?";
       
          User user = runner.query(sql, new BeanHandler<>(User.class), username, password);
  ​
          return user;
      }
  ​
  }

AutoLoginFilter.java

  
  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.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.HttpSession;
  ​
  import com.bean.User;
  import com.service.UserService;
  import com.utils.CookieUtil;
  ​
  /**
   * 如果进入这个过滤器之前已经登录成功,直接放行,怎么判断有没有登录成功,就看Session中是否有user对象
   */
  public class AutoLoginFilter implements Filter {
  ​
      public void destroy() {
  ​
      }
  ​
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
              throws IOException, ServletException {
          // 1.判断是否已登录
          // 1.1将request对象强转成HttpServletRequest类型
          HttpServletRequest rqs = (HttpServletRequest) request;
          // 1.2获取session对象
          HttpSession session = rqs.getSession();
          // 1.3获取session中存放的user
          User user = (User) session.getAttribute("user");
          // 1.4判断user是否为null
          if (user == null) {
              // 未登录
              // 判断是否需要自动登录----->就看cookie中是否有"info"
              String info = CookieUtil.getCookieValue(rqs, "info");
              if (info != null) {
                  // 需要自动登录,如果不需要自动登录同样也放行
                  // 取出用户名和密码
                  String username = info.split("#")[0];
                  String password = info.split("#")[1];
  ​
                  // 调用业务层方法登录
                  UserService service = new UserService();
                  user = service.doLogin(username, password);
  ​
                  // 很重要的一步,将user存放到session中
                  session.setAttribute("user", user);
              }
          }
  ​
          chain.doFilter(request, response);
      }
  ​
      public void init(FilterConfig fConfig) throws ServletException {
      }
  ​
  }

LogoutServlet.java

  
  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 javax.servlet.http.HttpSession;
  ​
  import com.utils.CookieUtil;
  ​
  /**
   * 处理注销功能servlet
   */
  public class LogoutServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
  ​
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          //注销其实就是将用户从session中移出
          HttpSession session = request.getSession();
          //立即销毁Session,并且清楚客服端的cookie
          session.invalidate();
          Cookie cookie = CookieUtil.createCookie("info","hello", 0, request.getContextPath());
          response.addCookie(cookie);
          //跳转到登录页面
          response.sendRedirect(request.getContextPath()+"/login.jsp");
      }
  ​
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          doGet(request, response);
      }
  ​
  }

工具类

CookieUtil

  
  package com.utils;
  ​
  import javax.servlet.http.Cookie;
  import javax.servlet.http.HttpServletRequest;
  ​
  public class CookieUtil {
      /**
       * 创建并配置Cookie
       * @param name  cookie的name
       * @param value  cookie的value
       * @param time  有效期,秒
       * @param path  有效范围
       * @return
       */
      public static Cookie createCookie(String name,String value,int time,String path){
          Cookie cookie = new Cookie(name, value);
          //Cookie的一些其他设置,可以设置最大有效期,可以设置有效范围(在哪里能够获取到该Cookie信息)
          //设置有效期
          cookie.setMaxAge(time);
          //设置有效范围
          cookie.setPath(path);//只能在CookieDemo02这个Servlet中获取该Cookie的信息
          return cookie;
      }
      
      /**
       * 获取Cookie里面的值
       */
      public static String getCookieValue(HttpServletRequest request,String cookieName){
          Cookie[] cookies = request.getCookies();
          String value = null;
          if (cookies != null) {
              for (Cookie cookie : cookies) {
                  if (cookieName.equals(cookie.getName())) {
                      //确实是咱们要获取的那个名为username的cookie对象
                      value = cookie.getValue();
                  }
              }
          }
          return value;
      }
  }

C3P0Utils.java

  
  package com.utils;
  ​
  import java.sql.Connection;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  ​
  import javax.sql.DataSource;
  ​
  import com.mchange.v2.c3p0.ComboPooledDataSource;
  ​
  public class C3P0Utils {
  /**
   * c3p0连接池工具类
   */
      
      private static ComboPooledDataSource dataSource;
      
      static {
          dataSource=new ComboPooledDataSource();
      }
      
      public static DataSource getDataSource() {
          
          return dataSource;
      }
      
      public static Connection getConnection() {
          Connection con=null;
          try {
               con= dataSource.getConnection();
          } catch (SQLException e) {
               System.out.println(e);
               
               throw new RuntimeException("数据库链接异常,请联系技术人员");
          }
          return con;
      }
      
      public static void close(ResultSet resultSet,PreparedStatement ps,Connection con) {
          
          if (resultSet!=null) {
              try {
                  resultSet.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
          
          if (ps!=null) {
              try {
                  ps.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
          
          if (con!=null) {
              try {
                  con.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
      }
  }

数据库连接池配置文件

c3p0-config.xml

  
  <?xml version="1.0" encoding="UTF-8"?>
  <c3p0-config>
      <default-config>
          <property name="initialPoolSize">10</property>
          <property name="user">root</property>
          <property name="password">root</property>
          <property name="jdbcUrl">jdbc:mysql://localhost:3306/autologin?characterEncoding=utf8</property>
          <property name="driverClass">com.mysql.jdbc.Driver</property>
      </default-config> 
  </c3p0-config>

使用过滤器(Filter)实现用户自动登录

应用场景:现在大部分网站都支持一段时间类用户自动登陆功能,移动端APP应用几乎都需要自动登陆,试想一下如果你每天打开微信或者QQ等APP时每次都需要手动输入用户名密码然后在登录,内心早已是一万匹草泥马.所以说自动登录功能对于提高用户体验时非常重要的.

那么下面我们就来自己实现一个简单的用户自定登录案列吧!

自动登陆案列分析

开发平台:win10 64位

开发语言:Java

开发工具:Eclipse Oxygen版(2018 3月发布) 服务器: tomcat 7.0 , jdk1.8 数据库:Mysql 5.5

相关工具包:

c3p0-0.9.1.2.jar(c3p0连接池jar包)commons-dbutils-1.4.jar(简化数据处理jar包,可以自己封装)jstl.jar(jstl jar包)mysql-connector-java-5.1.39-bin.jar(mysql驱动)standard.jar(jstl jar包)


1.准备数据

  
  create database autologin;
      use autologin;
      create table user(
          id int primary key auto_increment,
              username varchar(20),
              password varchar(20),
              birthday date,
              email varchar(60)
          );
          
      insert into user values(null,'Tom','123456','1990-10-18','[email protected]');
      insert into user values(null,'Jack','123456','1921-07-01','[email protected]');
      insert into user values(null,'Bob','123456','1990-02-22','[email protected]');

前端页面 login.jsp

  
  <%@page import="com.utils.CookieUtil"%>
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>登录页面</title>
  </head>
  <body>
      <%--如果用户已登录,直接掉转到首页 --%>
      <c:if test="${not empty user }">
          <jsp:forward page="/index.jsp"></jsp:forward>
      </c:if>
      <%--如果用户未登录就显示下面的页面 --%>
      <form action="${pageContext.request.contextPath }/login" method="post">
          用户名<input type="text" name="username"><br>
          密码<input type="password" name="pwd"><br>
          自动登录<input type="checkbox" name="auto" value="on"><br>
          <input type="submit" value="登录">
      </form>
  </body>
  </html>

index.jsp

  
  <%@page import="com.bean.User"%>
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>首页</title>
  </head>
  <body>
   
      <%--判断是否已登录,如果已登录则显示欢迎XXX登录  注销   购物车 
          如果未登录,则显示  注册   登录
          
          怎么判断是否已登录?只要登录成功,就会将user对象存放到session中,所以判断session中是否有user就可以知道是否已登录
      --%>
      <c:if test="${not empty user }">
          <h1>欢迎你回来${user.username }!</h1>
          <a href="${pageContext.request.contextPath }/logout">注销</a>
          <a href="${pageContext.request.contextPath }/car.jsp">购物车</a>
      </c:if>
      
      <c:if test="${empty user }">
          <a href="${pageContext.request.contextPath }/register.jsp">注册</a>
          <a href="${pageContext.request.contextPath }/login.jsp">登录</a>
      </c:if>
      
  </body>
  </html>

car.jsp

  
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Insert title here</title>
  </head>
  <body>
      <c:if test="${empty user}">
          <jsp:forward page="/login.jsp"></jsp:forward>
      </c:if>
      <c:if test="${not empty user}">
      <h1>${user.username }欢迎来到我的购物车</h1>
      </c:if>
  </body>
  </html>

register.jsp

  
  <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>注册页面</title>
  </head>
  <body>
      <h1>欢迎加入我们!</h1>
  </body>
  </html>

服务端代码

LoginServlet.java

  package com.servlet;
  ​
  import java.io.IOException;
  import java.io.PrintWriter;
  ​
  import javax.servlet.ServletContext;
  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 javax.servlet.http.HttpSession;
  ​
  import com.bean.User;
  import com.service.UserService;
   
  import com.utils.CookieUtil;
  ​
  /**
   * 处理用户登录的Servlet
   */
  public class LoginServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
   
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("text/html;charset=utf-8");
          String username = request.getParameter("username");
          String password = request.getParameter("pwd");
      
          String auto = request.getParameter("auto");
          HttpSession session = request.getSession();
          //调用业务层方法登录
          UserService service=new UserService();
          User user=service.doLogin(username,password);
          
           System.out.println(user);
          
          if (user!=null) {
              
              //当用户选择自动登陆后,我们怎样才能实现用户自动登陆成功呢?首先将用户登录成功的用户名和密码存入cookie并发送到客户端
              Cookie cookie = CookieUtil.createCookie("info",username+"#"+password,7*24*60*60,request.getContextPath());
              //判断用户是否选择了自动登陆
              if (!"on".equalsIgnoreCase(auto)) {
                  //如果用户没有选择自动登陆,则需要把cookie清空
                  cookie.setMaxAge(0);
              }
              //把cookie发送到客服端
              response.addCookie(cookie);
               
              //登录成功,把user存入session中
              session.setAttribute("user",user);
              response.sendRedirect(request.getContextPath()+"/index.jsp");
          }else {
              
              response.sendRedirect(request.getContextPath()+"/login.jsp");
          }
      
      }
  ​
       
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doGet(request, response);
      }
  ​
  }

UserService.java

  
  package com.service;
  ​
  import java.sql.SQLException;
  import java.util.List;
  ​
  import com.bean.User;
  import com.dao.UserDao;
  ​
  public class UserService {
  ​
      public User doLogin(String username, String password) {
          UserDao dao = new UserDao();
          User user=null;
          try {
              user = dao.doLogin(username, password);
          } catch (SQLException e) {
              e.printStackTrace();
          }
          return user;
      }
  ​
  ​
  }

UserDao.java

  
  package com.dao;
  ​
  import java.sql.SQLException;
  import org.apache.commons.dbutils.QueryRunner;
  import org.apache.commons.dbutils.handlers.BeanHandler;
  import com.bean.User;
  import com.utils.C3P0Utils;
  ​
  public class UserDao {
  ​
      public User doLogin(String username, String password) throws SQLException {
          QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
          String sql = "select * from user where username=? and password=?";
       
          User user = runner.query(sql, new BeanHandler<>(User.class), username, password);
  ​
          return user;
      }
  ​
  }

AutoLoginFilter.java

  
  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.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import javax.servlet.http.HttpSession;
  ​
  import com.bean.User;
  import com.service.UserService;
  import com.utils.CookieUtil;
  ​
  /**
   * 如果进入这个过滤器之前已经登录成功,直接放行,怎么判断有没有登录成功,就看Session中是否有user对象
   */
  public class AutoLoginFilter implements Filter {
  ​
      public void destroy() {
  ​
      }
  ​
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
              throws IOException, ServletException {
          // 1.判断是否已登录
          // 1.1将request对象强转成HttpServletRequest类型
          HttpServletRequest rqs = (HttpServletRequest) request;
          // 1.2获取session对象
          HttpSession session = rqs.getSession();
          // 1.3获取session中存放的user
          User user = (User) session.getAttribute("user");
          // 1.4判断user是否为null
          if (user == null) {
              // 未登录
              // 判断是否需要自动登录----->就看cookie中是否有"info"
              String info = CookieUtil.getCookieValue(rqs, "info");
              if (info != null) {
                  // 需要自动登录,如果不需要自动登录同样也放行
                  // 取出用户名和密码
                  String username = info.split("#")[0];
                  String password = info.split("#")[1];
  ​
                  // 调用业务层方法登录
                  UserService service = new UserService();
                  user = service.doLogin(username, password);
  ​
                  // 很重要的一步,将user存放到session中
                  session.setAttribute("user", user);
              }
          }
  ​
          chain.doFilter(request, response);
      }
  ​
      public void init(FilterConfig fConfig) throws ServletException {
      }
  ​
  }

LogoutServlet.java

  
  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 javax.servlet.http.HttpSession;
  ​
  import com.utils.CookieUtil;
  ​
  /**
   * 处理注销功能servlet
   */
  public class LogoutServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
  ​
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          //注销其实就是将用户从session中移出
          HttpSession session = request.getSession();
          //立即销毁Session,并且清楚客服端的cookie
          session.invalidate();
          Cookie cookie = CookieUtil.createCookie("info","hello", 0, request.getContextPath());
          response.addCookie(cookie);
          //跳转到登录页面
          response.sendRedirect(request.getContextPath()+"/login.jsp");
      }
  ​
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          doGet(request, response);
      }
  ​
  }

工具类

CookieUtil

  
  package com.utils;
  ​
  import javax.servlet.http.Cookie;
  import javax.servlet.http.HttpServletRequest;
  ​
  public class CookieUtil {
      /**
       * 创建并配置Cookie
       * @param name  cookie的name
       * @param value  cookie的value
       * @param time  有效期,秒
       * @param path  有效范围
       * @return
       */
      public static Cookie createCookie(String name,String value,int time,String path){
          Cookie cookie = new Cookie(name, value);
          //Cookie的一些其他设置,可以设置最大有效期,可以设置有效范围(在哪里能够获取到该Cookie信息)
          //设置有效期
          cookie.setMaxAge(time);
          //设置有效范围
          cookie.setPath(path);//只能在CookieDemo02这个Servlet中获取该Cookie的信息
          return cookie;
      }
      
      /**
       * 获取Cookie里面的值
       */
      public static String getCookieValue(HttpServletRequest request,String cookieName){
          Cookie[] cookies = request.getCookies();
          String value = null;
          if (cookies != null) {
              for (Cookie cookie : cookies) {
                  if (cookieName.equals(cookie.getName())) {
                      //确实是咱们要获取的那个名为username的cookie对象
                      value = cookie.getValue();
                  }
              }
          }
          return value;
      }
  }

C3P0Utils.java

  
  package com.utils;
  ​
  import java.sql.Connection;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  ​
  import javax.sql.DataSource;
  ​
  import com.mchange.v2.c3p0.ComboPooledDataSource;
  ​
  public class C3P0Utils {
  /**
   * c3p0连接池工具类
   */
      
      private static ComboPooledDataSource dataSource;
      
      static {
          dataSource=new ComboPooledDataSource();
      }
      
      public static DataSource getDataSource() {
          
          return dataSource;
      }
      
      public static Connection getConnection() {
          Connection con=null;
          try {
               con= dataSource.getConnection();
          } catch (SQLException e) {
               System.out.println(e);
               
               throw new RuntimeException("数据库链接异常,请联系技术人员");
          }
          return con;
      }
      
      public static void close(ResultSet resultSet,PreparedStatement ps,Connection con) {
          
          if (resultSet!=null) {
              try {
                  resultSet.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
          
          if (ps!=null) {
              try {
                  ps.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
          
          if (con!=null) {
              try {
                  con.close();
              } catch (Exception e) {
                  System.out.println(e);
              }
          }
      }
  }

数据库连接池配置文件

c3p0-config.xml

  
  <?xml version="1.0" encoding="UTF-8"?>
  <c3p0-config>
      <default-config>
          <property name="initialPoolSize">10</property>
          <property name="user">root</property>
          <property name="password">root</property>
          <property name="jdbcUrl">jdbc:mysql://localhost:3306/autologin?characterEncoding=utf8</property>
          <property name="driverClass">com.mysql.jdbc.Driver</property>
      </default-config> 
  </c3p0-config>

相关阅读

用c/c++实现strncpy函数

strncpy函数介绍 1:strncpy是 C语言的库函数之一,来自 C语言标准库,定义于 string.h,char *strncpy(char *dest, const char *src, i

NMS(非极大值抑制)实现

先看张图: NMS算法思路来源于:https://chenzomi12.github.io/2016/12/14/YOLO-nms/ 算法流程: 把置信度最高的一个boundingbox(bbo

console统一接口实现

Console是外部发送的统一接口,ConsoleDev是具体实现的设备的代码,以下是结构

FFT算法(Java实现)

FFT导论 转载自FFT导论 FFT是离散傅立叶变换的快速算法,可以将一个信号变换到频域。 有些信号在时域上是很难看出什么特征的,但是

设置response的Content-Disposition属性,实现文件下载

我们在开发web系统时有时会有以下需求:希望某类或者某已知MIME 类型的文件(比如:*.gif;*.txt;*.htm)能够在访问时弹出“文件下载”对

分享到:

栏目导航

推荐阅读

热门阅读