Home  >  Article  >  Java  >  SpringBoot interceptor implements login interception

SpringBoot interceptor implements login interception

(*-*)浩
(*-*)浩forward
2019-09-17 16:03:453774browse

What SpringBoot interceptor can do

can intercept URL paths and can be used for permission verification, garbled resolution, operation logging, performance monitoring, exception handling, etc. .

SpringBoot interceptor implements login interception

SpringBoot interceptor implements login interception

pom.xml:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.0.RELEASE
        
    
    com.wyj
    springboot-interceptor01
    0.0.1-SNAPSHOT
    springboot-interceptor01
    springboot拦截器

    
        1.8
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        

        
        
            org.projectlombok
            lombok
            true
        

        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
    

    
        springboot-interceptor01
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

WebMvcConfigurer: Inherit the WebMvcConfigurationSupport class, override the addInterceptors method

/**
 * 在springboot2.0.0之后,WebMvcConfigurerAdapter已经过时了
 * 会使用WebMvcConfigurer或者WebMvcConfigurationSupport替代
 *
 * @author wyj
 * @create 2019-06-01 21:48
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    /**
     * 在springboot2.0.0之前继承WebMvcConfigurerAdapter类,重写addInterceptors方法
     *
     * @param registry
     */
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        /**
//         * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行
//         */
//        registry.addInterceptor(new AuthorityInterceptor())
//                .addPathPatterns("/user/**");
//        super.addInterceptors(registry);
//    }

    /**
     * 在springboot2.0.0之后实现WebMvcConfigurer接口,重写addInterceptors方法
     *
     * @param registry
     */
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        /**
//         * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行
//         */
//        registry.addInterceptor(new AuthorityInterceptor())
//                .addPathPatterns("/user/**");
//    }

    /**
     * 在springboot2.0.0之后继承WebMvcConfigurationSupport类,重写addInterceptors方法
     *
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        /**
         * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行
         */
        registry.addInterceptor(new AuthorityInterceptor())
                .addPathPatterns("/user/**");
        super.addInterceptors(registry);
    }
}

AuthorityInterceptor: Implement the HandlerInterceptor interface, override the preHandle , postHandle, afterCompletionmethod

preHandle: called before request processing (before the Controller method is called)

postHandle: request processing Called later, but before the view is rendered (after the Controller method is called)

afterCompletion: Called after the entire request is completed, that is, executed after the DispatcherServlet renders the corresponding view (mainly used for resource processing Cleanup)

@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {

    private static final Set NOT_INTERCEPT_URI = new HashSet<>();//不拦截的URI

    static {
        NOT_INTERCEPT_URI.add("/user/login.html");
        NOT_INTERCEPT_URI.add("/user/login");
    }

    /**
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object object) throws Exception {
        String uri = request.getRequestURI();
        if (NOT_INTERCEPT_URI.contains(uri)) {
            log.info("不拦截" + uri);
            return true;
        }
        log.info("拦截" + uri);
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("user_info_in_the_session");
        if (userInfo == null) {
            throw new RuntimeException("用户未登陆");
        }
        return true;
    }

    /**
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception {
    }

    /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行
     * (主要是用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception {
    }
}

UserController:

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @RequestMapping(value = "/login.html")
    public String index() {
        return "login";
    }

    @RequestMapping(value = "/login")
    public String login(User user) {
        //查询数据库,我这里直接写死
        User dbUser = new User(1, "zhangsan", "123456", "admin");
        if (dbUser.getPassword().equals(user.getPassword())) {
            UserInfo userInfo = new UserInfo(dbUser.getId(), dbUser.getUsername(), dbUser.getRole());
            HttpSession session = getRequest().getSession();
            session.setAttribute("user_info_in_the_session", userInfo);
            return "admin";
        }
        return "login";
    }

    @RequestMapping(value = "/userInfo")
    @ResponseBody
    public String userInfo() {
        HttpSession session = getRequest().getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("user_info_in_the_session");
        return userInfo.toString();
    }

    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }
}

User:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

    private int id;
    private String username;
    private String password;
    private String role;

}

UserInfo: for Existing user information is stored in the session

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo implements Serializable {

    private int id;
    private String username; 
    private String role;

}

login.html:Just a very simple login form




    
    登陆页面

登陆:
用户名:
密 码:

admin.html:




    
    首页

The above is the detailed content of SpringBoot interceptor implements login interception. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete