过滤器是JavaEE中Servlet规范的一个组件,通过Filter技术,可以实现用户访问某个资源前,对访问的请求和响应进行拦截
拦截器(Interceptor)类似于Servlet中的过滤器,主要用于拦截客户请求并做出相应的处理。
过滤器在实现上基于函数回调,可以对几乎所有的请求进行过滤,但是缺点是一个过滤器实例只能在容器初始化时调用一次。使用过滤器的目的是用来做一些过滤操作,获取我们想要的数据。比如,在过滤器中修改字符编码,在过滤器中修改HttpServletRequest的一些参数。包括:过滤低俗文字,危险字符等。
拦截器是基于java的反射机制的
调用顺序:Filter>Interceptor>Aspect>Controller
当Controller抛出异常时,处理顺序是由内到外的。因此,经常定义一个@ControllerAdvice去统一处理控制器抛出的异常。一旦异常被@ControllerAdvice处理了,则调用拦截器的afterCompletion方法的参数Exception ex就为空了
1.过滤器只能在容器初始化时被调用一次,在action的生命周期中,而拦截器可以多次被调用。
2.过滤器可以对几乎所有的请求起作用,拦截器只能对action请求起作用。
3.过滤器不能访问action上下文、值栈里的对象,而拦截器可以访问。
4.过滤器依赖于servlet容器,而拦截器不依赖于servlet容器。
5.过滤器是基于函数回调,而拦截器是基于java的反射机制的。
6.过滤器不能获取IOC容器中的各个bean,而拦截器可以,这点很重要,在拦截器里注入一个service,可以调用业务逻辑。
package com.example.springbootmaven.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName="filter01",urlPatterns={"/*"})
@Component
@Order(1)
public class ThreadNameFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("start");
System.out.println(servletRequest.getClass());
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print("msg:"+request.getRequestURI());
System.out.println("end");
}
}
注意:
@WebFilter表明此类为过滤器,filterName为过滤器名称,urlPatterns为过滤路径
@Order为过滤器过滤顺序,数字越小,越先被过滤
@Component声明为bean,被容器扫描加载
package com.example.springbootmaven.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ThreadNameFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("start");
System.out.println(servletRequest.getClass());
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print("msg:"+request.getRequestURI());
System.out.println("end");
}
}
package com.example.springbootmaven.config;
import com.example.springbootmaven.filter.ThreadNameFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*/
@Configuration
public class BaseFilterConfig {
/**
* @返回值 org.springframework.boot.web.servlet.FilterRegistrationBean
*/
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new ThreadNameFilter());
registration.addUrlPatterns("/getName");
registration.setName("thread");
registration.setOrder(Integer.MIN_VALUE);
return registration;
}
}
注意:这种方式每声明一个过滤器,就要在配置类中创建一个 FilterRegistrationBean,以配置其名称、路径、顺序等
package com.kaishengit.config;
import com.kaishengit.entity.Account;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginInterceptor extends HandlerInterceptorAdapter {
//请求拦截
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Account account = (Account)session.getAttribute("account");
//未登录,跳转登录页
if (account==null){
String redirectPath = "/login";
response.sendRedirect(redirectPath);
return false;
}
return true;
}
//响应拦截
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
//视图渲染完成之后拦截
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
}
}
package com.kaishengit.config;
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 CustomerWebMvcConfigurer implements WebMvcConfigurer {
/*
* 设置拦截器需要拦截的路径
* mvc路径拦截
* 静态资源不拦截
* */
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/static/**");
}
}