Spring MVC HandlerMapping 代码层面的执行流程
1.找到DispatcherServlet
2.找到doDispatch()方法
asynchronous:异步的
synchronous:同步的
//入参进来一个request
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
处理器执行链
HandlerExecutionChain mappedHandler = null;
多部分请求 解析器 (文件上传)
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
try {
模型(数据)和视图
ModelAndView err = null;
异常
Exception dispatchException = null;
try {
//指的是 DispatcherServlet 的实例 看看请求是不是多部分请求
<form enctype="multipart/form-data"> 表单有文件域 上传文件了
processedRequest = this.checkMultipart(request);
multipartRequestParsed = processedRequest != request;
mappedHandler = this.getHandler(processedRequest);
3. protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
handlerMappings单列集合 。Set List
Iterator var2 = this.handlerMappings.iterator();
HandlerExecutionChain handler;
if(!var2.hasNext()) return null;
每next()拿到一个HandlerMapping实例
HandlerMapping hm = (HandlerMapping)var2.next();
handler = hm.getHandler(request);
return handler;
}
4.我们知道,HandlerMapping是一个接口 ,找实现类 Ctrl+H
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
Object handler = this.getHandlerInternal(request);
if(handler == null) {
handler = this.getDefaultHandler();
}
if(handler == null) {
return null;
} else {
if(handler instanceof String) {
String handlerName = (String)handler; // /hello
handler = this.getApplicationContext().getBean(handlerName);
}
return this.getHandlerExecutionChain(handler, request);
}
}
1,添加视图解析器
在apploicationContext.xml中添加如下代码
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean>
2.解决静态资源无法展示问题的三种方法
1,在web.xml中添加
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.img</url-pattern>
</servlet-mapping>
如果是js或css只需要把.img改成即可
2.在applicationContext.xml中添加节点
<mvc:default-servlet-handler></mvc:default-servlet-handler>
3.同样在applicationContext.xml中添加一个节点
<mvc:resources mapping="/static/**" location="/static/"></mvc:resources>
3.处理器映射器
方式一:也就是默认的
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
方式二:
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<!--<property name="mappings">-->
<!--<props>-->
<!--<prop key="/xxx">second</prop>-->
<!--</props>-->
<!--</property>-->
<property name="urlMap">
<map>
<entry key="/xxx">
<value>second</value>
</entry>
</map>
</property>
</bean>
其实这也算是两种方法,但差不多,所以就不多说了