SpringMVC执行原理
原理:
1.客户发起http请求 通过web.xml找到DispatcherServlet
2.DispatcherServlet通过配置文件springmvc-servlet.xml找到HandlerMaping(映射处理器),HandlerMaping找到Handler然后返回给DispatcherServlet
3.DispatcherServlet调用HandlerAdapter(处理器),HandlerAdapter调用具体的Controller(控制器)
4.Controller处理业务逻辑,返回ModelAndView(模型和视图)到DispatcherServlet
5.DispatcherServlet将ModelAndView传给ViewResolve(视图解析器)
6.ViewResolve解析后,将具体的View返回给DispatcherServlet
7.DispatcherServlet根据view将图形展示给用户
具体代码实现
hello.jsp
<html>
<body>
${msg}
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--1.注册 DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--管理一个springmvc的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVC中 / 和/*的区别
/ 代表匹配所有的请求,但不会去匹配jsp页面
/*代表匹配所有的请求,包括jsp页面
那么我们接下来会走一次视图解析器,而我们在视图解析器中设置了前缀和后缀
如果使用/*,那么他就会变成xxx.jsp.jsp
resources下的springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--HandlerMapping(处理器映射器)-->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"></bean>
<!--HandlerAdapter(处理器适配器)-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<!--ViewResolver(视图解析器):DispatcherServlet给它的ModeAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!--后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--Handler-->
<bean id="/hello" class="com.hongkai.controller.HelloController"></bean>
</beans>
Controller处理业务逻辑
package com.hongkai.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//第一步:实现org.springframework.web.servlet.ModelAndView下的Controller接口
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ModelAndView 模型和视图
ModelAndView mv = new ModelAndView();
//封装对象 放在ModelAndView中
mv.addObject("msg","HelloSpringMvc");
//封装要跳转的视图,放在ModelAndView中
mv.setViewName("hello");//相当于 /WEB-INF/jsp/hello.jsp
return mv;
}
}