Home  >  Article  >  Java  >  Cookie, session and java filter are combined to implement the login program

Cookie, session and java filter are combined to implement the login program

高洛峰
高洛峰Original
2017-01-18 14:20:051415browse

Cookies, sessions and filters are usually used in web applications. Cookies and sessions are used to save certain data. Filters occur after the browser sends a request and before a specific request is executed in the background. effect. The reason why these three are put together is because many times they are used together, such as some login programs.

Cookie is a browser mechanism, and session is a server mechanism, but in fact cookies are also generated by the server, and then returned to the browser, not generated by the browser itself. When the browser sends a request, if it has a valid cookie, it will bring this cookie with it.

The reason why cookies are used is because the http protocol is originally a stateless protocol, which means that through the http protocol itself, the server cannot determine whether the browser has visited before.

Filter and servlet are written similarly. When writing relevant code, you need to implement the Filter interface and rewrite the relevant methods. Usually the doFilter method is the one that changes more. If the Filter code needs to be effective after it is written, it needs to be configured in web.xml just like servlet configuration.

The following is a simple login example code that combines cookie, session, Servlet and Filter:

Define a user entity class to act as database data. Singleton mode is used here to ensure that only one exists. Instance object:

package models; 
  
/** 
 * 用户信息实体类 
 * 
 * @author tuzongxun123 
 * 
 */
public class UserModel { 
  private String userName; 
  private String password; 
  
  // 单例模式,保证只有一个用户对象实例 
  public static UserModel getInstance() { 
    UserModel user = new UserModel("zhangsan", "123456"); 
    return user; 
  
  } 
  
  private UserModel(String userName, String pasword) { 
    this.userName = userName; 
    this.password = pasword; 
  } 
  
  public String getUserName() { 
    return userName; 
  } 
  
  public String getPassword() { 
    return password; 
  } 
  
}

The user logs in and enters the index.jsp interface, and uses the jsp feature in the action of the form form to obtain the project path:

<%@ page language="java" import="java.util.*" 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>cookieAndFilterTest</title> 
</head> 
<body> 
   <form action="<%=request.getContextPath() %>/loginServlet" method="post"> 
    userName:<input type="text" name="userName" /></br> 
    password:<input type="password" name="password" /></br> 
    <input type="submit" value="login"/> 
   </form> 
</body> 
</html>

The corresponding background servlet:

package servletTest; 
  
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 models.UserModel; 
  
public class LoginServlet extends HttpServlet { 
  
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    this.doPost(req, resp); 
  } 
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    String userName = req.getParameter("userName"); 
    String password = req.getParameter("password"); 
    // 模拟数据库数据 
    UserModel user = UserModel.getInstance(); 
    String dbUserName = user.getUserName(); 
    String dbPassword = user.getPassword(); 
    if (dbUserName.equals(userName) && dbPassword.equals(password)) { 
      // 用户名和密码都匹配,证明登陆成功,设置session和cookie 
      HttpSession session = req.getSession(); 
      session.setAttribute("userName", userName); 
      session.setAttribute("password", password); 
      Cookie cookie = new Cookie("userName", userName); 
      Cookie cookie2 = new Cookie("password", password); 
      // 设置cookie的存储时长 
      cookie.setMaxAge(60); 
      cookie2.setMaxAge(60); 
      // 把cookie发送给浏览器 
      resp.addCookie(cookie); 
      resp.addCookie(cookie2); 
      // 转发请求到用户列表 
      req.getRequestDispatcher("/userList").forward(req, resp); 
    } else { 
      // 转发请求到登陆页面 
      req.getRequestDispatcher("index.jsp").forward(req, resp); 
    } 
    ; 
  
  } 
  
}

Request to jump after logging in above:

package servletTest; 
  
import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import models.UserModel; 
  
public class UserListServlet extends HttpServlet { 
  
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    this.doPost(req, resp); 
  } 
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    UserModel user = UserModel.getInstance(); 
    //在浏览器中打印出用户列表书数据 
    resp.getWriter().write( 
        "userName:" + user.getUserName() + "," + "password:"
            + user.getPassword()); 
  
  } 
  
}

Project web.xml configuration:

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  id="WebApp_ID" version="2.5">   
  
 <!-- 访问时的项目名称 -->
 <display-name>cookieAndFilterTest</display-name> 
 <!-- servlet配置 -->
 <servlet> 
   <servlet-name>login</servlet-name> 
   <servlet-class>servletTest.LoginServlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
   <servlet-name>login</servlet-name> 
   <url-pattern>/loginServlet</url-pattern> 
 </servlet-mapping> 
  
 <servlet> 
   <servlet-name>userList</servlet-name> 
   <servlet-class>servletTest.UserListServlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
   <servlet-name>userList</servlet-name> 
   <url-pattern>/userList</url-pattern> 
 </servlet-mapping> 
  
 <!-- 过滤器设置,浏览其发送请求后首先会走这里 -->
 <filter> 
   <filter-name>loginFilter</filter-name> 
   <filter-class>filterTest.FilterTest</filter-class> 
 </filter> 
 <filter-mapping> 
   <filter-name>loginFilter</filter-name> 
   <url-pattern>/*</url-pattern> 
 </filter-mapping> 
  
 <!-- 输入项目名访问的默认页面 -->
 <welcome-file-list> 
  <welcome-file>index.jsp</welcome-file> 
 </welcome-file-list> 
</web-app>

java filter code:

package filterTest; 
  
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 models.UserModel; 
  
public class FilterTest 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; 
    String uri = req.getRequestURI(); 
    if ("/cookieAndFilterTest/loginServlet".equals(uri) 
        || "/cookieAndFilterTest/".equals(uri)) { 
      // 放行 
      chain.doFilter(request, response); 
      return; 
    } 
  
    // 不是登陆请求的话,判断是否有cookie 
    Cookie[] cookies = req.getCookies(); 
    if (cookies != null && cookies.length > 0) { 
      String userName = null; 
      String password = null; 
      // 判断cookie中的用户名和密码是否和数据库中的一致,如果一致则放行,否则转发请求到登陆页面 
      for (Cookie cookie : cookies) { 
        if ("userName".equals(cookie.getName())) { 
          userName = cookie.getValue(); 
        } 
        if ("password".equals(cookie.getName())) { 
          password = cookie.getValue(); 
        } 
      } 
      UserModel user = UserModel.getInstance(); 
      if (user.getUserName().equals(userName) 
          && user.getPassword().equals(password)) { 
        chain.doFilter(request, response); 
        return; 
      } else { 
        // 重定向到登陆界面 
        req.getRequestDispatcher("/index.jsp").forward(req, resp); 
        return; 
      } 
    } else { 
      req.getRequestDispatcher("/index.jsp").forward(req, resp); 
      return; 
    } 
  } 
  
  @Override
  public void init(FilterConfig arg0) throws ServletException { 
  
  } 
  
}

The above is the entire content of this article, I hope It will be helpful for everyone to learn java programming.

For more articles related to the combination of cookie, session and java filters to implement the login program, please pay attention to the PHP Chinese website!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn