Spring的OncePerRequestFilter
原文链接:https://blog.csdn.net/weixin_43944305/article/details/119923969
Spring
的OncePerRequestFilter
OncePerRequestFilter
顾名思义,他能够确保在一次请求只通过一次filter
,而不需要重复执行
大家常识上都认为,一次请求本来就只过一次,还要OncePerRequestFilter
限制一次过滤干啥。
其实实际上因为不同的web container
对请求的过滤方式都不一样,比如在servlet-2.3
中,Filter
会过滤一切请求,包括服务器内部使用forward
转发请求和<%@ include file="/index.jsp"%>
的情况。
到了servlet-2.4
中Filter
默认下只拦截外部提交的请求,forward
和include
这些内部转发都不会被过滤,但是有时候我们需要 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");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44