0%

tomcat之web配置文件

Web 应用部署核心:web.xml 配置文件详解

web.xml 是 Java Web 应用的核心部署描述文件,用于定义应用的初始化参数、Servlet 映射、过滤器、安全约束等配置。它分为两个层级:Tomcat 全局默认配置(conf/web.xml)和应用自定义配置(WEB-INF/web.xml),后者会覆盖前者的同名配置。本文将系统解析 web.xml 的核心配置项及用法。

配置文件结构概览

web.xml 的配置项按功能可分为以下类别,本文将逐一详解:

  1. ServletContext 初始化参数
  2. 会话配置(Session)
  3. Servlet 声明与映射
  4. 生命周期监听器(Listener)
  5. 过滤器(Filter)定义与映射
  6. MIME 类型映射
  7. 欢迎文件列表
  8. 错误页面配置
  9. 本地化与编码映射
  10. 安全配置
  11. JNDI 资源配置

核心配置项详解

1. ServletContext 初始化参数

通过 <context-param> 定义全局参数,所有 Servlet 和过滤器可通过 ServletContext.getInitParameter() 获取。适用于存储应用级常量(如版本号、配置路径)。

配置示例

1
2
3
4
5
6
7
8
<context-param>
<param-name>app.version</param-name>
<param-value>1.0.0</param-value>
</context-param>
<context-param>
<param-name>api.endpoint</param-name>
<param-value>https://api.example.com</param-value>
</context-param>

获取方式

1
2
// 在 Servlet 中
String version = getServletContext().getInitParameter("app.version");

2. 会话配置(<session-config>

用于配置 HTTP 会话的全局属性,包括超时时间、Cookie 策略、会话追踪模式等。

配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<session-config>
<!-- 会话超时时间(分钟),默认 30 分钟 -->
<session-timeout>60</session-timeout>

<!-- Cookie 配置(仅当追踪模式为 COOKIE 时生效) -->
<cookie-config>
<name>MY_SESSION_ID</name> <!-- 自定义会话 Cookie 名称,默认 JSESSIONID -->
<domain>.example.com</domain> <!-- Cookie 生效域名 -->
<path>/myapp</path> <!-- Cookie 生效路径 -->
<http-only>true</http-only> <!-- 禁止 JS 访问,防止 XSS 攻击 -->
<secure>true</secure> <!-- 仅 HTTPS 传输 -->
<max-age>3600</max-age> <!-- Cookie 有效期(秒) -->
</cookie-config>

<!-- 会话追踪模式(COOKIE/URL/SSL),可多选 -->
<tracking-mode>COOKIE</tracking-mode>
</session-config>

会话追踪模式说明

  • COOKIE:通过 Cookie 传递会话 ID(默认,推荐)。
  • URL:通过 URL 重写(;jsessionid=xxx)传递,适用于禁用 Cookie 的场景。
  • SSL:通过 SSL 会话标识追踪,适用于 HTTPS 环境。

3. Servlet 声明与映射

Servlet 是处理请求的核心组件,需通过 <servlet> 声明并通过 <servlet-mapping> 绑定 URL 路径。

配置示例

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
<!-- 声明 Servlet -->
<servlet>
<servlet-name>UserServlet</servlet-name> <!-- 唯一标识 -->
<servlet-class>com.example.UserServlet</servlet-class> <!-- 全类名 -->

<!-- Servlet 初始化参数(仅当前 Servlet 可见) -->
<init-param>
<param-name>pageSize</param-name>
<param-value>10</param-value>
</init-param>

<!-- 启动优先级:数值越小越先加载(>=0 时应用启动时加载) -->
<load-on-startup>1</load-on-startup>

<!-- 文件上传配置(适用于处理 multipart/form-data 请求) -->
<multipart-config>
<max-file-size>10485760</max-file-size> <!-- 单个文件最大 10MB -->
<max-request-size>52428800</max-request-size> <!-- 请求总大小最大 50MB -->
<file-size-threshold>4096</file-size-threshold> <!-- 超过 4KB 写入磁盘 -->
</multipart-config>
</servlet>

<!-- 映射 URL 路径 -->
<servlet-mapping>
<servlet-name>UserServlet</servlet-name> <!-- 关联声明的 Servlet -->
<url-pattern>/user/*</url-pattern> <!-- 匹配以 /user 开头的路径 -->
<url-pattern>/api/user</url-pattern> <!-- 精确匹配 -->
</servlet-mapping>

URL 模式规则

  • 精确匹配:如 /login 仅匹配 http://domain/login
  • 路径匹配:如 /user/* 匹配 http://domain/user/123http://domain/user/profile
  • 扩展名匹配:如 *.do 匹配 http://domain/action/login.do
  • 根路径:/ 匹配所有未被其他模式匹配的请求(默认 Servlet)。

4. 生命周期监听器(<listener>

监听器用于监控 Web 应用的生命周期事件(如启动、关闭)或请求 / 会话事件(如会话创建、属性变更)。需实现 ServletContextListenerHttpSessionListener 等接口。

配置示例

1
2
3
4
5
6
7
8
9
<!-- 应用启动/关闭监听器 -->
<listener>
<listener-class>com.example.AppStartupListener</listener-class>
</listener>

<!-- 会话监听器 -->
<listener>
<listener-class>com.example.SessionListener</listener-class>
</listener>

执行顺序

  • 启动时按配置顺序执行 contextInitialized()
  • 关闭时按相反顺序执行 contextDestroyed()

5. 过滤器(Filter)定义与映射

过滤器用于对请求 / 响应进行预处理(如编码转换、权限校验、日志记录),可链式调用。

配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- 定义过滤器 -->
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.example.AuthFilter</filter-class>
<!-- 过滤器初始化参数 -->
<init-param>
<param-name>excludePaths</param-name>
<param-value>/login,/register</param-value>
</init-param>
</filter>

<!-- 映射过滤器 -->
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern> <!-- 对所有请求生效 -->
<dispatcher>REQUEST</dispatcher> <!-- 拦截直接请求 -->
<dispatcher>FORWARD</dispatcher> <!-- 拦截转发请求 -->
</filter-mapping>

dispatcher 取值

  • REQUEST:默认,拦截直接请求。
  • FORWARD:拦截通过 RequestDispatcher.forward() 的请求。
  • INCLUDE:拦截通过 RequestDispatcher.include() 的请求。
  • ERROR:拦截错误页面跳转的请求。

6. MIME 类型映射(<mime-mapping>

定义文件扩展名与 MIME 类型的映射,用于浏览器正确解析资源(如 JS、CSS、图片)。

配置示例

1
2
3
4
5
6
7
8
9
10
11
12
<mime-mapping>
<extension>json</extension>
<mime-type>application/json</mime-type>
</mime-mapping>
<mime-mapping>
<extension>svg</extension>
<mime-type>image/svg+xml</mime-type>
</mime-mapping>
<mime-mapping>
<extension>pdf</extension>
<mime-type>application/pdf</mime-type>
</mime-mapping>

7. 欢迎文件列表(<welcome-file-list>

定义访问目录时默认返回的文件(如 index.html),按配置顺序匹配。

配置示例

1
2
3
4
5
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
</welcome-file-list>

访问 http://domain/myapp/ 时,会依次查找 index.htmlindex.jsp 等。

8. 错误页面配置(<error-page>

指定特定错误码或异常类型对应的自定义页面,提升用户体验。

配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- 按错误码配置 -->
<error-page>
<error-code>404</error-code>
<location>/error/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>

<!-- 按异常类型配置 -->
<error-page>
<exception-type>java.lang.NullPointerException</exception-type>
<location>/error/npe.html</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/error/servlet-error.html</location>
</error-page>

9. 本地化与编码映射(<locale-encoding-mapping-list>

定义 Locale(语言 / 地区)与字符编码的映射,用于自动设置响应编码。

配置示例

1
2
3
4
5
6
7
8
9
10
<locale-encoding-mapping-list>
<locale-encoding-mapping>
<locale>zh</locale> <!-- 中文 -->
<encoding>UTF-8</encoding>
</locale-encoding-mapping>
<locale-encoding-mapping>
<locale>en</locale> <!-- 英文 -->
<encoding>ISO-8859-1</encoding>
</locale-encoding-mapping>
</locale-encoding-mapping-list>

10. 安全配置

通过 <security-constraint><login-config> 等配置 Web 应用的访问控制,包括资源权限、认证方式等。

配置示例

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
31
32
33
<!-- 1. 定义安全约束(哪些资源需要保护) -->
<security-constraint>
<web-resource-collection>
<web-resource-name>AdminPages</web-resource-name>
<url-pattern>/admin/*</url-pattern> <!-- 保护 /admin 路径下的资源 -->
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>

<!-- 允许访问的角色 -->
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>

<!-- 传输安全(NONE/INTEGRAL/CONFIDENTIAL) -->
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee> <!-- 要求 HTTPS -->
</user-data-constraint>
</security-constraint>

<!-- 2. 声明安全角色 -->
<security-role>
<role-name>admin</role-name>
</security-role>

<!-- 3. 配置认证方式 -->
<login-config>
<auth-method>FORM</auth-method> <!-- 表单认证 -->
<form-login-config>
<form-login-page>/login.html</form-login-page> <!-- 登录页面 -->
<form-error-page>/login-error.html</form-error-page> <!-- 登录失败页面 -->
</form-login-config>
</login-config>

认证方式(auth-method

  • BASIC:基础认证(明文传输,简单但不安全)。
  • DIGEST:摘要认证(加密传输密码)。
  • FORM:表单认证(自定义登录页面,推荐)。
  • CLIENT-CERT:客户端证书认证(基于 HTTPS 客户端证书)。

11. JNDI 资源配置

通过 <resource-ref> 引用 JNDI 资源(如数据源),实现资源与应用解耦。

配置示例

1
2
3
4
5
6
<resource-ref>
<description>MySQL 数据源</description>
<res-ref-name>jdbc/myDB</res-ref-name> <!-- JNDI 名称 -->
<res-type>javax.sql.DataSource</res-type> <!-- 资源类型 -->
<res-auth>Container</res-auth> <!-- 容器管理认证 -->
</resource-ref>

使用方式

1
2
3
4
// 在 Servlet 中获取数据源
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myDB");
Connection conn = ds.getConnection();

配置优先级与覆盖规则

  1. 全局配置 vs 应用配置
    Tomcat 全局 conf/web.xml 定义默认行为(如 JSP Servlet、默认 MIME 类型),应用的 WEB-INF/web.xml 可覆盖同名配置(如自定义欢迎文件)。
  2. Servlet 3.0+ 注解与 XML 配置
    注解(如 @WebServlet@WebFilter)可替代 XML 配置,若两者同时存在,XML 配置优先级更高(可覆盖注解属性)。

欢迎关注我的其它发布渠道

表情 | 预览
快来做第一个评论的人吧~
Powered By Valine
v1.3.10