Web.xml配置文件:
<servlet>
<servlet-name>ServletDemo5</servlet-name>
<servlet-class>cn.itcast.ServletDemo5</servlet-class>
<init-param>
<param-name>data1</param-name>
<param-value>xxxxx</param-value>
</init-param>
<init-param>
<param-name>data2</param-name>
<param-value>yyyyy</param-value>
</init-param>
<init-param>
<param-name>data3</param-name>
<param-value>zzzzz</param-value>
</init-param>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/struts-config.xml</param-value>
</init-param>
</servlet>
Servlet代码:
//servletConfig对象,用于封装servlet配置信息
//在实际开发中,有一些东西不适合在servlet程序中写死,这类数据就可以通过配置方式配给servlet,例如
//servlet采用哪个码表,servlet连接哪个数据库,servlet采用哪个配置文件
public class ServletDemo5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//得到指定的参数
String value = this.getServletConfig().getInitParameter("data1");
System.out.println(value);
//得到所有的参数
Enumeration e = this.getServletConfig().getInitParameterNames();
while(e.hasMoreElements()){
String name = (String)e.nextElement();
String value1 = this.getServletConfig().getInitParameter(name);
System.out.println(name+"="+value1);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}