配置 Servlet 初始化参数 - JavaWeb

web.xml 配置

使用一个或多个 元素为 Servlet 配置初始化参数

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" metadata-complete="false" version="4.0">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>net.biancheng.www.MyServlet</servlet-class>
<!-- Servlet 初始化参数 -->
<init-param>
<param-name>name</param-name>
<param-value>编程帮</param-value>
</init-param>
<!-- Servlet 初始化参数 -->
<init-param>
<param-name>URL</param-name>
<param-value>www.biancheng.net</param-value>
</init-param>
</servlet>
</web-app>

@WebServlet 配置

1
2
3
4
5
6
7
8
9
@WebServlet(urlPatterns = {"/MyServlet"}, 
initParams = {
@WebInitParam(name = "name", value = "编程帮"),
@WebInitParam(name = "URL", value = "www.biancheng.net")
}
)
public class MyServlet extends HttpServlet {
// ...
}