首页 > 代码库 > ServletConfig对象和它在开发中的应用场

ServletConfig对象和它在开发中的应用场

package cn.itcast;import java.io.IOException;import java.io.PrintWriter;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;//servletConfig对象:用于封装servlet的配置信息//在实际开发,有一些东西不适合在servlet中写死,这类数据就可以通过配置方式给servlet,例如//servlet采用哪个码表、servlet连接哪个库,servlet哪个配置文件public class ServletDemo extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        // 得到指定的        String value = http://www.mamicode.com/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 {    }}
View Code
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    <display-name></display-name>    <servlet>        <servlet-name>ServletDemo</servlet-name>        <servlet-class>cn.itcast.ServletDemo</servlet-class>        <init-param>            <param-name>data1</param-name>            <param-value>xxxxxx</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>dddddd</param-value>        </init-param>        <init-param>            <param-name>data4</param-name>            <param-value>aaaaaa</param-value>        </init-param>    </servlet>    <servlet-mapping>        <servlet-name>ServletDemo</servlet-name>        <url-pattern>/servlet/ServletDemo</url-pattern>    </servlet-mapping>    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list></web-app>
View Code