springMvc是基于servlet的web框架,其简化了web程序的开发
在阅读时不妨可以带着几个问题阅读:
1.我们通常在浏览器输入的接口怎么由DispatcherServlet调到具体的Handler的(就是我们自己开发的Controller类)
2.编写Controller的形式有哪几种?
springMvc重要组件:
之所以先说这几个组件,是因为只要了解了这几个组件后你便可以对springMvc请求流程有个大致的清晰认识了。(Handler就是我们写的Controller)
HandlerMapping
HandlerAdapter
ViewResolver
View
HandlerExceptionResolver
HandlerInterceptor
DisPatcher作为一个主流程入口,看一下DispatcherServlet结构
DispatcherServlet为了简洁,省去了很多方法跟属性
public class DispatcherServlet extends FrameworkServlet {
//定义了默认策略名字
private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";
private static final Properties defaultStrategies;
static {
//从Properties文件中加载默认策略实现
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
private List<HandlerMapping> handlerMappings;
private List<HandlerAdapter> handlerAdapters;
private List<HandlerExceptionResolver> handlerExceptionResolvers;
private List<ViewResolver> viewResolvers;
//初始化策略
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
ModelAndView mv = null;
Exception dispatchException = null;
try {
//检查是否文件上传
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);
//通过HandlerMapping 获取Handler(返回的是HandlerExecutionChain)
/**public class HandlerExecutionChain {
//HandlerExecutionChain封装了Handler(就是我们编写的Controller)跟interceptors
private final Object handler;
private HandlerInterceptor[] interceptors;
**/
HandlerExecutionChain mappedHandler = getHandler(processedRequest);
//获取的Handler是Object类型,需要通过HandlerAdapter获取Handler真实类型
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
// Process last-modified header, if supported by the handler.
//调用Handlerinterceptor PreHandle(前置拦截器),返回false则停止执行
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}
// 调用真实handler逻辑并返回ModelAndView
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
//将ModelAndView返回值DispatcherServlet后
applyDefaultViewName(processedRequest, mv);
//调用Handlerinterceptor PostHandle(后置拦截器)
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we‘re processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex