Cookies, sessions and filters are usually used in web applications. Cookies and sessions are used to save certain data. Filter filters take effect after the browser makes a request and before the background executes a specific request. The reason why these three are put together is because they are often combined, such as some login programs .
Cookies are the browser mechanism, and session is the server mechanism, but in fact, cookies are also generated by the server and are then returned to the browser, not generated by the browser itself. When a browser sends a request, it will bring the cookie together if it has a valid cookie.
All cookies are used 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 accessed it before.
The writing methods of Filter and servlet are similar. When writing related code, you need to implement the Filter interface and rewrite the related methods. Usually, the doFilter method is changed more often. If the Filter code needs to be effective after writing, it is necessary to configure certain configuration in web.xml like configuring servlets.
Here is a simple login sample code combining cookies, sessions, Servlets and Filters:
Define a user entity class to act as database data. The singleton pattern is used here to ensure that only one instance object exists:
package models; /** * User information entity class* * @author tuzongxun123 * */ public class UserModel { private String userName; private String password; // Singleton mode, ensure that there is only one user object instance public static UserModel getInstance() { UserModel user = new UserModel("zhangsan", "123456"); return user; } private UserModel(String userName, String password) { this.userName = userName; this.password = password; } public String getUserName() { return userName; } public String getPassword() { return password; } } User login to the index.jsp interface and use the jsp feature in the form action 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>
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"); // Simulate database data UserModel user = UserModel.getInstance(); String dbUserName = user.getUserName(); String dbPassword = user.getPassword(); if (dbUserName.equals(userName) && dbPassword.equals(password)) { // Both the user name and password match, prove that the login is successful, set session and 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); // Set the storage time of cookies cookie.setMaxAge(60); cookie2.setMaxAge(60); // Send cookies to the browser resp.addCookie(cookie); resp.addCookie(cookie2); // Forward request to user list req.getRequestDispatcher("/userList").forward(req, resp); } else { // Forward request to login page req.getRequestDispatcher("index.jsp").forward(req, resp); } ; } } Request to jump after logging in:
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(); //Print out user list book data in the browser 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"> <!-- Project name when accessing --> <display-name>cookieAndFilterTest</display-name> <!-- servlet configuration--> <servlet> <servlet-name>login</servlet-name> <servlet-class>servletTest.LoginServlet</servlet-class> </servlet> <servlet-mapping> <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 settings, after browsing the request, you will go here first-> <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> <!-- Default page to access by entering the project name--> <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 { // Directly release HttpServletRequest for login request and initial request HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String uri = req.getRequestURI(); if ("/cookieAndFilterTest/loginServlet".equals(uri) || "/cookieAndFilterTest/".equals(uri)) { // Release chain.doFilter(request, response); return; } // If it is not a login request, determine whether there are cookies Cookie[] cookies = req.getCookies(); if (cookies != null && cookies.length > 0) { String userName = null; String password = null; // Determine whether the user name and password in the cookie are consistent with the database. If it is consistent, release it, otherwise forward the request to the login page 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 { // Redirect to the login interface 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 all about this article, I hope it will be helpful for everyone to learn Java programming.