servlet获取web.xml中配置的初始化参数

时间:2021-10-15 13:54:50

在web.xml中我们配置的参数如下:

<servlet>
<servlet-name>GetInitParameterServlet</servlet-name>
<servlet-class>servlet.GetInitParameterServlet</servlet-class>

<init-param>
<param-name>username</param-name>
<param-value>admin</param-value>
</init-param>

<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>GetInitParameterServlet</servlet-name>
<url-pattern>/servlet/GetInitParameterServlet</url-pattern>
</servlet-mapping>

那么在Servlet中,我们如果需要获取初始化参数,就继承以下init方法,在这里调用如下方法进行获取:

@Override
public void init() throws ServletException {
String username = this.getInitParameter("username");
String password = this.getInitParameter("password");
}