Filter 过滤器
web应用程组件,可以在请求到达Servlet之前对其进行访问,也可以在响应消息返回客户端之前对其进行拦截。
有方法: init、doFilter、destroy
链式调用,存在多个过滤器时,依次进行过滤,返回时倒序返回; <======类似于栈的特性
package com.insight.cloudeureka;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "LogFilter") // 拦截所有请求
public class LogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 统计方法请求到响应花费的时间
long start = System.currentTimeMillis();
chain.doFilter(request, response);
log.info("LogFilter Print Log: {} -> {}",
((HttpServletRequest) request).getRequestURI(),
System.currentTimeMillis() - start);
}
@Override
public void destroy() {
}
}
还需在启动类上加上扫描注解
@ServletComponentScan(“Filter所在的包路径”)
Intercepter 拦截器
AOP的一种实现策略,用于在某个方法或字段在被访问之前对它进行拦截,然后在其之前或者之后进行一些操作。
方法: preHandle、afterHandle、afterCompletion
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {
long start = 0L; // 非线程安全
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
start = System.currentTimeMillis();
HandlerMethod handlerMethod = (HandlerMethod)handler; // handler 就是controller
log.info("LogInterceptor: {}",((HandlerMethod) handler).getBean().getClass().getName());
log.info("LogInterceptor method name is : ", handlerMethod.getMethod().getName());
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
log.info("LogInterceptor: {} -> {}",
request.getRequestURI(),
System.currentTimeMillis() - start);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
定义完拦截器之后,需要将拦截器进行相关的配置,如下配置类:
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
@Configuration
public class WebInterceptorAdapter implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**").order(0);
}
}
|