TestServletConfig.java

package com.huawei.config;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class TestServletConfig
*/
public class TestServletConfig extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public TestServletConfig() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

/**
* 获取ServletConfig的几种方式
*
*/

//this.getServletConfig();
//重写Servlet中的init方法
}

@Override
public void init(ServletConfig config) throws ServletException {

//得到servlet的实例的名称
//获取的是 在web.xml文件中的servlet配置模块中的servlet-name里面的值
System.out.println(config.getServletName());

System.out.println(config.getInitParameter("username"));
System.out.println(config.getInitParameter("password"));

System.out.println("===========");
//得到所有的名字
Enumeration<?> names = config.getInitParameterNames();
//遍历
while(names.hasMoreElements()){
//
String name = names.nextElement().toString();
System.out.println(name+":"+config.getInitParameter(name));

}
}

}

 

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TestServletConfig</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>


<servlet>
<description></description>
<display-name>TestServletConfig-dis</display-name>
<servlet-name>TestServletConfig-name</servlet-name>
<servlet-class>com.cdsxt.config.TestServletConfig</servlet-class>

<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123123</param-value>
</init-param>
</servlet>


<servlet-mapping>
<servlet-name>TestServletConfig-name</servlet-name>
<url-pattern>/config</url-pattern>
</servlet-mapping>
</web-app>