============================================================================
拦截器示例:
控制器:
package org.example.controller; 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; @Controller public class HelloController { // http://localhost:8080/hello @ResponseBody @RequestMapping("/hello") public String hello() { return "Hello World!____________china"; } // http://localhost:8080/123 @ResponseBody @RequestMapping("/123") public String home123() { return "中国您好"; } // http://localhost:8080/1234 @RequestMapping(value = "/1234",method = RequestMethod.GET) @ResponseBody public String home1234() { return "中国您好_123456"; } }
定义一个拦截器:
package org.example.controller.Interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UseInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if ("b".equals(request.getParameter("a"))) { System.out.println("请求不成功"); return false; } else { System.out.println("该方法在控制器处理请求方法前执行,其返回值表示是否中断后续操作,返回 true 表示继续向下执行,返回 false 表示中断后续操作。"); //放行 return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("该方法在控制器处理请求方法调用之后、解析视图之前执行,可以通过此方法对请求域中的模型和视图做进一步修改。"); } }
注册拦截器:
package org.example.config; import org.example.controller.Interceptor.UseInterceptor; 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 MyMvcConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { System.out.println("注册拦截器"); registry.addInterceptor(new UseInterceptor()).addPathPatterns("/**") //拦截所有请求,包括静态资源文件 .excludePathPatterns("/", "/login", "/index.html", "/user/login", "/css/**", "/images/**", "/js/**", "/fonts/**"); //放行登录页,登陆操作,静态资源 } }
请求:http://localhost:8080/hello?a=b
请求:http://localhost:8080/hello?a=c
PS:
标签:web,拦截器,http,spring,boot,springframework,org,import,public From: https://www.cnblogs.com/xiaobaibailongma/p/17060812.html