SpringMVC 中重要组件
DispatcherServlet : 前端控制器,接收所有请求(如果配置/不包含 jsp)
HandlerMapping: 解析请求格式的.判断希望要执行哪个具体的方法.
HandlerAdapter: 负责调用具体的方法.
ViewResovler:视图解析器.解析结果,准备跳转到具体的物理视图
运行原理图
SpringMvc是Spring的子容器,可以调用Spring组件
使用步骤
第一步:在xml中配置前端控制器DisptcherServlet
一定要配置init 不然就需要到/WEB-INF/<servlet-name>-servlet.xml找配置文件
<servlet>
<servlet-name>jqk</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet<
SpringMVC 容器
/servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jqk</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
第二步:创建springmvc.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描注解 -->
<context:component-scan
base-package="com.bjsxt.controller"></context:component-scan>
<!-- 注解驱动 -->
<!--
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandler
Mapping -->
<!--
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerA
dapter -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
</beans>
第三步:编写控制器类
这样访问服务器访问demo 他就会跳转到main.jsp 如果将jsp放在WEB-INF目录下,就需要将路径改为/WEB-INF/main.jsp
@Controller
public class DemoController {
@RequestMapping("demo")
public String demo(){
System.out.println("执行 demo");
return "main.jsp";
}
@RequestMapping("demo2")
public String demo2(){
System.out.println("demo2");
return "main1.jsp";
}
}