In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how springboot uses interceptors to determine whether to log in or not. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Two steps for springboot interceptor to determine whether to log in to implement interceptor
Custom interceptor implements HandlerInterceptor interface
Create a configuration class that inherits the WebMvcConfigurerAdapter class and overrides the addInterceptors method
Code:
1. The custom interceptor @ Componentpublic class AdminLoginInterceptor implements HandlerInterceptor {/ / is called before the request is processed. Only if true is returned will the request @ Override public boolean preHandle (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {/ / get session HttpSession session = httpServletRequest.getSession (true); / / get the object Object admin = session.getAttribute ("admin") / / determine whether the object exists if {return true;} else {/ / if it does not exist, jump to the login page httpServletResponse.sendRedirect (httpServletRequest.getContextPath () + "/ login/adminLogin"); return false }} / / execute @ Override public void postHandle (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {} / / after request processing, execute @ Override public void afterCompletion (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {} 2 before view rendering, custom configuration class inherits WebMvcConfigurerAdapter@SpringBootConfigurationpublic class AdminLoginAdapter extends WebMvcConfigurerAdapter {@ Autowired AdminLoginInterceptor adminLoginInterceptor @ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (adminLoginInterceptor) .addPathPatterns ("/ admin/**") .excludePathPatterns ("/ login/**"); super.addInterceptors (registry);}} springboot add interceptor to determine whether to log in 1, create interceptor package com.example.demo.interceptor;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView Import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * < brief description of the function of one sentence >
* < interceptor > * @ author, Zh2Guo * @ create 2018-11-22 * @ since 1.0.0 * / public class LoginInterceptor implements HandlerInterceptor {private Logger logger = LoggerFactory.getLogger (LoginInterceptor.class); / / before the request is processed, the request @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {logger.info ("[interceptor] initiates login status interception") will be executed only if true is returned. / / get session HttpSession session = request.getSession (); logger.info ("[interceptor] sessionID:" + session.getId ()); / / get user information Object userInfo = session.getAttribute ("userInfo") / / determine whether the user is logged in to if (userInfo! = null) {logger.info ("[interceptor] user has logged in, username, password:" + session.getAttribute ("userInfo")); return true;} else {/ / there is no jump to login page response.sendRedirect (request.getContextPath () + "/") / / Jump to the home page to log in to logger.info ("[interceptor] the user did not log in, but jumped to:" + request.getContextPath () + "/"); return false }} / / after performing @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} / / request processing after view rendering, @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}} 2, inherit WebMvcConfigureAdapter class
Override its addInterceptors interface and register a custom interceptor
@ Configuration annotations must be available
Package com.example.demo.interceptor;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/** * < brief description of the function of one sentence >
* < Custom configuration class > * * @ author, Zh2Guo * @ create 2018-11-22 * @ since 1.0.0 * / @ Configurationpublic class LoginConfig implements WebMvcConfigurer {/ * * this method is used to register interceptors * multiple interceptors can be registered Multiple interceptors form a chain of interceptors * / @ Override public void addInterceptors (InterceptorRegistry registry) {/ / addPathPatterns add path / / excludePathPatterns exclude path registry.addInterceptor (new LoginInterceptor ()) .addPat hPatterns ("/ sys/*") / / intercept url// .origindePathPatterns ("") under the sys path } 3, LoginController/** * Copyright (C), 2017-2018, XXX Limited * FileName: LoginController * Author:, Zh2Guo * Date: 2018-11-22 11:10 * Description: login * History: * * author name revision time version number description * / package com.example.demo.controller Import com.example.demo.dao.UserDAO;import com.example.demo.pojo.User;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpServletRequest;/** * < brief description of the function of one sentence >
* < login > * * @ author, Zh2Guo * @ create 2018-11-22 * @ since 1.0.0 * / @ Controllerpublic class LoginController {/ / log private Logger logger = LoggerFactory.getLogger (LoginController.class); @ Autowired private UserDAO userDAO / / start service auto jump login / / @ RequestMapping (value = {"/", "/ login"}) @ RequestMapping (value = "/") public String login () {return "login" } / / Login @ RequestMapping (value = "/ loginCheck", method = RequestMethod.POST) @ ResponseBody public String loginCheck (HttpServletRequest request) {/ / get login information String userName = request.getParameter ("userName"); String password = request.getParameter ("password"); / / encapsulated into an object User user = new User (); user.setUserName (userName) User.setPassword (password); / / verify user information User info = userDAO.checkUser (user); if (info! = null) {request.getSession () .setAttribute ("userInfo", userName + "-" + password); logger.info ("login successful, user name: + userName +" password: "+ password); return" success " } else {logger.info ("login failed, username:" + userName + "password:" + password); return "fail";} 4. If you fail to log in, you will automatically jump to the login page.
This is how the springboot shared by the editor uses the interceptor to determine whether you are logged in. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.