SpringMVC
SpringMVC
创建项目
-
创建
Java Enterprice
修改为如下 ( maven
)项目 -
添加
pom.xml
依赖 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<dependencies>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
</dependencies>
-
需求
需求: 用户发起一个请求,
spring-mvc
接受请求, 显示请求的处理结果
-
Servlet
的实现方式 jsp
—>·发起请求 servelt
—->处理请求 jsp
显示处理后的结果
-
spring-mvc
web(Java Enterprice)
web(spring-webmvc )
springmvc
DispatcherServlet
DispatcherServlet
是一个 servlet
对象 DispatcherServlet
叫做前端控制器 DispatcherServlet
的作用 - 在
servlet
的 init()
方法中, 创建 springmvc
中的容器对象 - 作为
servlet
,接受请求
- 在
jsp | html
,发起请求代替之前的 servlet
)- 在类的上面加入
@Controller
注解 - 在类中定义方法,
方法的上面加入 @RequestMapping
注解,方法是处理请求的, 相当于 servlet
的 doget | doPost
jsp | html
spring-mvc
spring
- 声明组件扫描器,
指定 @Controller
注解所在的包名 - 声明视图解析器对象
-
位置
spring-mvc
核心对象 -
本质是一个
sevlet
核心对象的本质 -
访问
spring-mvc
1
2
3
4
5
6
7
8
9<!-- 声明中央调度器 -->
<servlet>
<servlet-name>coderitl</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>coderitl</servlet-name>
<url-pattern>/coder-itl</url-pattern>
</servlet-mapping>访问 mvc
地址后, 报错, 文件没找到, 找的目标文件为 coderitl-servlet.xml
-
错误的原因
在
Servlet
的 init()
方法中, 创建 spring-mvc
使用的容器对象 WebApplicationContext
-
WebApplicationContext ctx = new ClassPathXmlApplicationContext(配置文件)
而配置文件的默认路径为:/WEB-INF/<servlet-name>-servlet.xml
-
解决方案
-
在默认路径下创建对应匹配规则的配置文件
( 不灵活
) -
自定义配置文件路径
读取过程分析
-
-
web.xml
配置内容 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<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">
<!-- 声明中央调度器 -->
<servlet>
<!-- WebApplicationContext ctx = new ClassPathXmlApplicationContext(配置文件) -->
<servlet-name>coderitl</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</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>coderitl</servlet-name>
<!--
url-pattern 作用: 把一些请求交给指定的 servlet 处理,使用中央调度器 (DispatcherServlet)
1. 使用扩展名方式 格式: *.xxx, xxx 是自定义的扩展名
例如: *.do *.action *.mvc 不能使用 *.mvc
2. 使用 /xxx
-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>