RESTful API的拦截方式 (过滤器Filter)拦截器(Interceptor)切片(Aspect)

优先级按排序

1 过滤器(Filter)   最先进入拦截,只能获取到response,request 
2 拦截器(Interceptor) 可以获取到执行的类名,方法名
3 切片(Aspect) 可以获取到参数

具体使用哪一个看业务需求吧.

1 过滤器(Filter)

自定义Filter

package com.imooc.web.filter;import org.springframework.stereotype.Component;import java.io.IOException;import java.util.Date;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;@Component  // 增加一个注解即可使用,不需要其他配置,会拦截所有请求public class TimeFilter implements Filter {@Overridepublic void destroy() {System.out.println("time filter destroy");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {System.out.println("time filter start");long start = new Date().getTime();chain.doFilter(request, response); // 继续执行程序,不调用doFilter 不会往下执行System.out.println("time filter 耗时:"  (new Date().getTime() - start));System.out.println("time filter finish");}@Overridepublic void init(FilterConfig arg0) throws ServletException {// 程序启动会加载System.out.println("time filter init");}}

  如果是引用第三方的Filter 使用方法:

package com.imooc.web.config;import java.util.ArrayList;import java.util.List;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.imooc.web.filter.TimeFilter;@Configurationpublic class WebConfig {@Beanpublic FilterRegistrationBean timeFilter() {// 注册第三方FilterFilterRegistrationBean registrationBean = new FilterRegistrationBean();TimeFilter timeFilter = new TimeFilter();registrationBean.setFilter(timeFilter);// 需要拦截的urlList<String> urls = new ArrayList<>();urls.add("/*");registrationBean.setUrlPatterns(urls);return registrationBean;}}

2 拦截器(Interceptor)

  2.1自定义Interceptor

package com.imooc.web.interceptor;import java.util.Date;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;@Componentpublic class TimeInterceptor implements HandlerInterceptor {// 先进入该方法@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {System.out.println("preHandle");System.out.println(((HandlerMethod)handler).getBean().getClass().getName());System.out.println(((HandlerMethod)handler).getMethod().getName());request.setAttribute("startTime", new Date().getTime());return true; // 返回true才能继续执行controller}// 如果Controller方法抛出了异常,不会进入该方法@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {System.out.println("postHandle");Long start = (Long) request.getAttribute("startTime");System.out.println("time interceptor 耗时:"  (new Date().getTime() - start));}// 不管方法是不是抛出异常 都会进入该方法@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {System.out.println("afterCompletion");Long start = (Long) request.getAttribute("startTime");System.out.println("time interceptor 耗时:"  (new Date().getTime() - start));System.out.println("ex is " ex);}}

   2.2 注入自定义的Interceptor

package com.imooc.web.config;import com.imooc.web.interceptor.TimeInterceptor;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class TimeInterceptorConfig extends WebMvcConfigurerAdapter {    // 自定义的Interceptor    @Autowired    private TimeInterceptor timeInterceptor;    // 注入spring    @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(timeInterceptor);    }}

3 切片(Aspect)

自定义切片

package com.imooc.web.aspect;import java.util.Date;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Component;@Aspect@Componentpublic class TimeAspect {   // 切入具体的方法,拦截UserController的所有方法   @Around("execution(* com.imooc.web.controller.UserController.*(..))")   public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {      System.out.println("time aspect start");      Object[] args = pjp.getArgs(); // 可以获取方法参数      for (Object arg : args) {         System.out.println("arg is " arg);      }      long start = new Date().getTime();      Object object = pjp.proceed(); // 继续往下执行Controller      System.out.println("time aspect 耗时:"  (new Date().getTime() - start));      System.out.println("time aspect end");      return object;   }}

  

来源:https://www.icode9.com/content-1-767201.html

(0)

相关推荐