项目参考:详细参见:《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 { } }