Spring过滤器和拦截器的区别
两者的作用
过滤器:
是在javaweb中,你传入的request、response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts的action进行业务逻辑,比如过滤掉非法url(不是login.do的地址请求,如果用户没有登陆都过滤掉),或者在传入servlet或者 struts的action前统一设置字符集,或者去除掉一些非法字符.。
拦截器 :
是在面向切面编程的就是在你的service或者一个方法,前调用一个方法,或者在方法后调用一个方法比如动态代理就是拦截器的简单实现,在你调用方法前打印出字符串(或者做其它业务逻辑的操作),也可以在你调用方法后打印出字符串,甚至在你抛出异常的时候做业务逻辑的操作。
从具体实现区分
1. 过滤器是servlet的
2. 拦截器是spring aop的
细节区别
①拦截器是基于Java的反射机制的,而过滤器是基于函数回调。
②拦截器不依赖于servlet容器,过滤器依赖于servlet容器。
③拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。
④拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。
⑤在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次。
⑥拦截器可以获取IOC容器中的各个bean,而过滤器就不行,这点很重要,在拦截器里注入一个service,可以调用业务逻辑。
工作流程及顺序
应用场景
1. 对于一些不需要用到bean的request预处理和response后处理,可以过滤器,如:encoding,cors
2. 对于一些要用到用到bean,或者逻辑比较复杂,有特殊处理的,可以用拦截器
3. 不过不怕麻烦,也可以自己建AOP
代码实现
拦截器:
继承spring的HandlerInterceptorAdapter
- public class SessionInterceptor extends HandlerInterceptorAdapter {
- private static ThreadLocal
threadLocal = new ThreadLocal (); - private final Logger logger = LoggerFactory.getLogger(this.getClass());
- @Autowired
- private UserSessionService userSessionService;
- @PostConstruct
- public void init() {
- logger.info("init");
- }
- @PreDestroy
- public void destroy() {
- logger.info("destroy");
- }
- @Override
- public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
- logger.debug("SessionInterceptor.preHandle run....");
- final URLAnalysis urlAnalysis = (URLAnalysis) request.getAttribute(Constants.URL_ANALYSIS);
- final String userIdString = urlAnalysis.getParam(Constants.USERID);
- final String accessToken = urlAnalysis.getParam(Constants.ACCESSTOKEN);
- if (!StringUtils.isNotEmpty(userIdString)) {
- throw new InvalidArgumentException("userId is required");
- }
- if (!StringUtils.isNotEmpty(accessToken)) {
- throw new InvalidArgumentException("accessToken is required");
- }
- if (!NumberUtils.isNumber(userIdString)) {
- throw new InvalidArgumentException("userId[" + userIdString + "] invalid");
- }
- final boolean result = userSessionService.checkLogin(Long.valueOf(userIdString), accessToken);
- if (!result) {
- throw new InvalidUserSessionException("Invalid accessToken[" + accessToken + "]");
- }
- final UserSessionVO userSessionVO = new UserSessionVO();
- userSessionVO.setUserId(Long.valueOf(userIdString));
- userSessionVO.setAccessToken(accessToken);
- threadLocal.set(userSessionVO);
- return result;
- }
- @Override
- public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) throws Exception {
- logger.debug("SessionInterceptor.afterCompletion run....");
- final UserSessionVO userSessionVO = threadLocal.get();
- if (userSessionVO != null) {
- // renewal session
- userSessionService.renewalSessoin(userSessionVO.getUserId(), userSessionVO.getAccessToken());
- }
- threadLocal.remove();
- }
- }
过滤器:
继承java的Filter,其实现是servlet
- public class CorsFilter implements Filter {
- // private final Log logger = LogFactory.getLog(this.getClass());
- private final String allowedOrigins;
- private final String allowCredentials;
- public CorsFilter(final String allowedOrigins, final String allowCredentials) {
- this.allowedOrigins = allowedOrigins;
- this.allowCredentials = allowCredentials;
- }
- @Override
- public void init(final FilterConfig filterConfig) throws ServletException {
- }
- @Override
- public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
- final HttpServletRequest request = (HttpServletRequest) req;
- final HttpServletResponse response = (HttpServletResponse) res;
- final String method = request.getMethod();
- // this origin value could just as easily have come from a database
- response.setHeader("Access-Control-Allow-Origin", allowedOrigins);
- response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS");
- response.setHeader("Access-Control-Max-Age", "3600");
- response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
- // "Content-Type, X-Requested-With, accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers"
- response.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization," + Constants.SESSIONID + "," + Constants.CSRFTOKEN);
- if ("OPTIONS".equals(method)) {
- response.setStatus(HttpStatus.OK.value());
- } else {
- chain.doFilter(req, res);
- }
- }
- @Override
- public void destroy() {
- }
- }