简体   繁体   中英

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. 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.

However, it always logs 200 OK even when the actual response status is 400 or 405. 在此处输入图片说明

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

@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. 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. In other words, you are logging the info before the filter has performed it processing which results in status as 200

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM