文章目录
  1. 1. 配置文件
    1. 1.1. 具体配置
      1. 1.1.1. web.xml
      2. 1.1.2. [servlet-name]-servlet.xml

配置文件

  • web.xml :在应用程序的 WebContent/WEB-INF 目录下

  • [servlet-name]-servlet.xml :用于创建 bean 定义,重新定义在全局范围内具有相同名称的任何已定义的 bean。

具体配置

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>TestReport</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
NOTE:
  • 初始化 MyServlet DispatcherServlet 时,框架将尝试加载位于该应用程序的 WebContent/WEB-INF 目录中文件名为 [servlet-name]-servlet.xml 的应用程序内容。如上配置,加载的文件将是 MyServlet-servlet.xml。
  • 若不想使用默认文件名 [servlet-name]-servlet.xml 和默认位置 WebContent/WEB-INF,可以通过在 web.xml 文件中添加 servlet 监听器 ContextLoaderListener 自定义该文件的名称和位置,如下所示:
1
2
3
4
5
6
7
8
9
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

[servlet-name]-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.tutorialspoint" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
  • 标签将用于激活 Spring MVC 注解扫描功能,该功能允许使用注解,如 @Controller 和 @RequestMapping 等。
文章目录
  1. 1. 配置文件
    1. 1.1. 具体配置
      1. 1.1.1. web.xml
      2. 1.1.2. [servlet-name]-servlet.xml