web.xml 文件配置
<?xml version="1.0" encoding="UTF-8"?>
<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" metadata-complete="true">
<context-param>
<param-name>abc</param-name>
<param-value>123123</param-value>
</context-param>
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>cn.ly.mywebproject.MyFirstServlet</servlet-class>
<init-param>
<param-name>user</param-name>
<param-value>admin</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/MyFirstServlet</url-pattern>
</servlet-mapping>
</web-app>
Servlet类 init() 中获取 web.xml中的参数
- config.getServletName() // 获取当前Servlet的名称
- config.getInitParameter() // 获取当前Servlet中配置的初始化参数
- config.getInitParameterNames() // 获取全部初始化参数名,以枚举的格式
@Override
public void init(ServletConfig config) throws ServletException {
String userString = config.getInitParameter("user");
Enumeration<String> enumeration = config.getInitParameterNames();
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
String value = config.getInitParameter(name);
System.out.println(value);
}
}
|