[英]Why is response.getStatus() returning 200 OK even when the actual response is not
I am implementing a feature that logs all the access to my API in a log file. 我正在实现一项功能,将对API的所有访问记录在一个日志文件中。 In it, I have response status code as well as some information related to each access.
在其中,我具有响应状态代码以及与每次访问相关的一些信息。 I retrieve the status code by
response.getStaus()
as shown in AppLogFilter. 我通过
response.getStaus()
检索状态代码,如AppLogFilter中所示。
However, it always logs 200 OK even when the actual response status is 400 or 405. 但是,即使实际响应状态为400或405,它始终记录200 OK。
What could I be the problem here? 我在这里可能是什么问题?
Filter Config 过滤器配置
package com.example.kasahararestapi.filter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<ApiLogFilter> filterRegistrationBean() {
FilterRegistrationBean<ApiLogFilter> registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new ApiLogFilter());
registrationBean.addUrlPatterns("/api/items/*");
return registrationBean;
}
}
ApiLogFilter ApiLogFilter
@Component
public class ApiLogFilter extends OncePerRequestFilter {
private final Logger logger = LoggerFactory.getLogger(ApiLogFilter.class);
@Override
public final void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
long startTime = System.currentTimeMillis();
long processingTime = System.currentTimeMillis() - startTime;
logger.info(
"{} {} {} {}", request.getMethod(),
request.getRequestURI(), response.getStatus(), processingTime);
filterChain.doFilter(request, response);
}
}
Change 更改
logger.info(
"{} {} {} {}", request.getMethod(),
request.getRequestURI(), response.getStatus(), processingTime);
filterChain.doFilter(request, response);
To 至
filterChain.doFilter(request, response);
logger.info(
"{} {} {} {}", request.getMethod(),
request.getRequestURI(), response.getStatus(), processingTime);
Reason: The name chain suggests that you have a sequence of filters, with each filter doing some processing and then passing on to the next in sequence, so each object has a chain member to point to the next filter in the sequence, which gets called after the filter has performed its own processing.
原因:名称链表明您有一个过滤器序列,每个过滤器都会进行一些处理,然后传递到序列中的下一个过滤器,因此每个对象都有一个链成员指向该序列中的下一个过滤器,这
gets called after the filter has performed its own processing.
The last in the sequence will then probably have null
as the chain value, or it knows on its own that it is the last one in the sequence. 这样,序列中的最后一个可能会具有
null
作为链值,或者它自己知道它是序列中的最后一个。 In other words, you are logging the info before the filter has performed it processing which results in status as 200
换句话说,您在过滤器执行处理之前记录信息,结果状态为
200
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.