首页 > 代码库 > [Java.Web][Servlet]读取配置

[Java.Web][Servlet]读取配置

private  ServletConfig config;    
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String value = config.getInitParameter("data");
    OutputStream out = response.getOutputStream();
    out.write(value.getBytes());
}

@Override
public void init(ServletConfig config) throws ServletException {
    this.config = config;
}
String value = http://www.mamicode.com/getServletConfig().getInitParameter("data");
OutputStream out = response.getOutputStream();
out.write(value.getBytes());
OutputStream out = response.getOutputStream();
Enumeration<String> e = this.getServletConfig().getInitParameterNames();
while (e.hasMoreElements()) {   // 遍历所有
    String name = (String) e.nextElement();
    String value = this.getServletConfig().getInitParameter(name);
    out.write((name + ‘:‘ + value + "\r\n").getBytes());
}

以上代码都可以从 web.xml 中读取配置,配置在如下节点中的 <init-param></init-param> 里:

 <servlet>
   <servlet-name>ServletDemo5</servlet-name>
   <servlet-class>cn.itcast.ServletDemo5</servlet-class>    
   <init-param>
       <param-name>data</param-name>
       <param-value>x1x2x3</param-value>
   </init-param>
 </servlet>

 

[Java.Web][Servlet]读取配置