Spring的OncePerRequestFilter过滤器

SpringOncePerRequestFilter

OncePerRequestFilter顾名思义,他能够确保在一次请求只通过一次filter,而不需要重复执行

大家常识上都认为,一次请求本来就只过一次,还要OncePerRequestFilter限制一次过滤干啥。

其实实际上因为不同的web container对请求的过滤方式都不一样,比如在servlet-2.3中,Filter会过滤一切请求,包括服务器内部使用forward转发请求和<%@ include file="/index.jsp"%>的情况。

到了servlet-2.4Filter默认下只拦截外部提交的请求,forwardinclude这些内部转发都不会被过滤,但是有时候我们需要 forward的时候也用到Filter

自定义实现OncePerRequestFilter的过滤器

package com.fchan.espractice.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Order(-1000)
public class MyOnceFilter extends OncePerRequestFilter {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            filterChain.doFilter(request, response);
        }

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Map<String,Object> map = new HashMap<>();
        map.put("name","李四");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(objectMapper.writeValueAsBytes(map));
        outputStream.close();
        //重定向之后还是会进入过滤器的
        //response.sendRedirect("/testQuery");
    }
}

你可能感兴趣的:(spring,JAVA,springboot,spring,java,http)