In the website, the http request is stateless, that is, when user 1 connects to the server and logs in successfully, when refreshing the website and reconnecting, it still needs to log in again. Different users cannot be identified only through general information. The emergence of cookies is to solve this problem and realize the function of remembering the login status on the website, so that users can visit the website without logging in again for a period of time after successful login.
Realization idea
- Using cookies: when the user logs in successfully, the server sets cookies for the client. The value consists of user name and password. When users visit the web page for the second time, they will automatically send their cookies to the server, and the server can identify the current user through the cookie data. (the user name and password information is more important. Remember to encrypt it and the server will decrypt and identify it)
- Realized through session: session is also realized through cookies in essence. The difference is that the cookie data is saved on the client side, while the session data is saved on the server side. When the user logs in successfully, the server saves a sessionid value and sends it to the client through cookies. The effective time is set to 1 month. Then in the next month, when the client visits my website, the sessionid value will be sent to my server for verification. The server determines whether there is a sessionid and releases it directly, If it does not exist, jump to the login interface to log in again.
code implementation
Use the HandlerInterceptor interceptor to pre process the request
public class LoginHandle implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Cookie[] cookies = request.getCookies(); // Cookie record not saved if(null == cookies){ response.sendRedirect(request.getContextPath() + "/login"); return false; } String sessionid = ""; boolean isheve = false; for(Cookie cookie:cookies){ if("sessionid".equals(cookie.getName())){ sessionid = cookie.getValue(); isheve = true; break; } } // sessionid not found, please login again if(!isheve){ response.sendRedirect(request.getContextPath() + "/login"); return false; } // Data verification here // HttpSession session = request.getSession(); // User username = (User) session.getAttribute(sessionid); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { return; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { return; } }
Implement WebMvcConfigurer and override addInterceptors() method to configure interceptors
@Configuration public class LoginConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration registration = registry.addInterceptor(new LoginHandle()); registration.addPathPatterns("/hi/*"); registration.excludePathPatterns("/login"); } }
Save session and set cookies after successful login
@RequestMapping(value = "/chat", method = RequestMethod.POST) public String loginIntoChatRoom(User user, HttpServletRequest request, Model model,HttpServletResponse response){ user = userService.validateUserPassword(user.getName(), user.getPassword()); if (user == null){ return "login"; } // Login judgment logic // if(...) ... // Save session and set cookies after successful login String uuid = UUID.randomUUID().toString(); // Save login user information to session session.setAttribute(uuid,user); // Save cookie s to realize automatic login Cookie cookie_username = new Cookie("sessionid", uuid); // Set the cookie persistence time, 30 days cookie_username.setMaxAge(30 * 24 * 60 * 60); // Set to carry this cookie under the current project cookie_username.setPath(request.getContextPath()); // Send cookie s to clients response.addCookie(cookie_username); return "hi"; }