• SpringBoot2 添加应用拦截器


    项目参考:详细参见:《Spring Boot 2精髓:从构建小系统到架构分布式大系统》 第三章 3.6.1节 拦截器

    MyWebMvcConfigurer

    package com.archibladwitwicke.springboot2.chapter03.configurer;
    
    import com.archibladwitwicke.springboot2.chapter03.intercept.AdminLoginIntercept;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class MyWebMvcConfigurer implements WebMvcConfigurer {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 添加一个拦截器,连接以/admin为前缀的 url路径
            registry.addInterceptor(new AdminLoginIntercept()).addPathPatterns("/admin/**");
        }
    }
    

      

    TestAdminController

    package com.archibladwitwicke.springboot2.chapter03.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping("/admin")
    public class TestAdminController {
    
        @RequestMapping("/hello")
        @ResponseBody
        public String say() {
            return "this is a admin page.";
        }
    }
    

      

    AdminLoginIntecept

    package com.archibladwitwicke.springboot2.chapter03.intercept;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class AdminLoginIntercept implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            // 如果已经登录返回true。
            // 如果没有登录没有登录,可以使用 reponse.send() 跳转页面。后面要跟return false,否则无法结束;
    
            // 为了测试,打印一句话
            System.out.println("访问了admin下url路径。");
    
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
        }
    }
    

      

  • 相关阅读:
    Referenced file contains errors (http://www.springframework.org/...解决
    Echarts的提示(Tooltip)显示额外内容
    后端&前端零碎知识点和注意问题
    RocketMQ 4.5.1 双主双从异步复制环境搭建
    个人时间管理
    Windows系统封装教程
    你要如何衡量你的人生
    如何让你爱的人爱上你
    舔狗不会永远舔你的爱答不理和高冷
    关于小孩的教育问题
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/8583874.html
Copyright © 2020-2023  润新知