本文共 2710 字,大约阅读时间需要 9 分钟。
拦截器与过滤器都是AOP思想的具体实现,拦截器会比过滤器更好用一点。
另外:
过滤器:
拦截器:
1:创建interceptor拦截器
public class interceptor01 implements HandlerInterceptor /*extends HandlerInterceptorAdapter */{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(request.getRequestURI()+" "+System.currentTimeMillis()); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(request.getRequestURI()+" "+System.currentTimeMillis()); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println(request.getRequestURI()+" "+System.currentTimeMillis()); }}
2:创建controller
@RestControllerpublic class Test14 { @RequestMapping("/test14/test01") public String test01(){ System.out.println("this is controller01"); return "this is controller01"; } @RequestMapping("/test14/test02") public String test02(){ System.out.println("this is controller02"); return "this is controller02"; }}
3:创建配置类,记住需要使用@Configuration注解
package com.example.demo.config;import com.example.demo.filter.interceptor01;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configurationpublic class webmvcconfigure implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new interceptor01()).addPathPatterns("/test14/test01","/test14/test02","/form.html");/* registry.addInterceptor(new interceptor01()).addPathPatterns("/test14/*").excludePathPatterns("/test14/test02");*/ }}
转载地址:http://rolyo.baihongyu.com/