spring mvc 中 请求处理过程
url初始化过程:
- org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext() throws ApplicationContextException (初始化从这里开始 )
- org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers() throws BeansException (Register all handlers found in the current ApplicationContext.)
- 在这里有个方法:org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping.determineUrlsForHandlerMethods(Class<?> handlerType, boolean hasTypeLevelMapping) ReflectionUtils.doWithMethods(TestJMS.class, new ReflectionUtils.MethodCallback(){
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
System.out.println("1111:"+method.getName()+":"+method.getTypeParameters().getClass());
RequestMapping mapping = AnnotationUtils.findAnnotation(method, RequestMapping.class);
if(null != mapping){
String[] valueString =mapping.value();
for (String string : valueString) {
System.out.println("3333:"+string);
}
}
}
}, ReflectionUtils.USER_DECLARED_METHODS);
原来的url会衍生出:url, url.*, url/ 三种。
- 最后 这些url 都会被放到:Map<String, Object> handlerMap, 其中String就是上面的三种url,Object就是具体对应的处理类对象,例如:
- /salarySheet/query=com.ulpay.vasp.entrust.action.SalarySheetController@1493f589, /salarySheet/query.*=com.ulpay.vasp.entrust.action.SalarySheetController@1493f589, /salarySheet/query/=com.ulpay.vasp.entrust.action.SalarySheetController@1493f589,
接受请求时,处理过程:
- org.springframework.web.servlet.DispatcherServlet.doService(HttpServletRequest request, HttpServletResponse response) throws Exception(请求处理从这里开始)
- // Determine handler for the current request.
mappedHandler = getHandler(processedRequest);
由请求地址获取处理该请求的handler(内部方法)
- // Determine handler adapter for the current request.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
由当前的handler获取处理该请求的其他条件,如:请求参数处理
- // Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
HandlerAdapter中的handle是真正处理请求的方法,包含了请求参数的转换,序列化等过程。
总之, spring mvc处理请求时,核心主要是DispatcherServlet.doService将请求拦截,接着获取具体的mappedHandler,然后获取到HandlerAdapter ,最后HandlerAdapter将处理当前请求。也就是说,核心就是handler和HandlerAdapter。