springmvc 獲取當前請求的 原生request/response

炸雞店老闆發表於2017-11-01

看springmvc 方法入參解析器是如何獲取的

// mvc原始request入參 方法引數解析
public class ServletWebArgumentResolverAdapter extends AbstractWebArgumentResolverAdapter {
    
    @Override
    protected NativeWebRequest getWebRequest() {
        // 核心,當前請求執行緒ThreadLocal
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            // 獲取對應的request response session等
            return new ServletWebRequest(servletRequestAttributes.getRequest());
        }
        return null;
    }
}

關鍵類:RequestContextHolder


構造當前請求執行緒的RequestAttributes, 參考:

org.springframework.web.servlet.FrameworkServlet#processRequest
org.springframework.web.servlet.FrameworkServlet#initContextHolders

然後熟悉的doDispatch。

相關文章