1. 程式人生 > >Servlet的ServletConfig物件獲取初始化引數

Servlet的ServletConfig物件獲取初始化引數

Servlet:

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


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;




public class Servlet implements javax.servlet.Servlet{


@Override
public void destroy() {
// TODO Auto-generated method stub

}


@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}


@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}


@Override
public void init(ServletConfig servletConfig) throws ServletException {
//ServletConfig 物件獲取引數化引數
String user = servletConfig.getInitParameter("user");
String pass = servletConfig.getInitParameter("pass");
System.out.println("user:"+user);
System.out.println("pass:"+pass);

//遍歷獲取引數名與引數值
Enumeration<String> names = servletConfig.getInitParameterNames();
while(names.hasMoreElements())
{
String name = names.nextElement();
String value = servletConfig.getInitParameter(name);
System.out.println(name+":"+value);
}

//獲取servlet-name
String servletName = servletConfig.getServletName();
System.out.println("servlet-name:"+servletName);
}


@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub

}

}  

Serlvet-End

web:

<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Servlet_NeiZhiDuiXiang</display-name>


<!-- 
1、ServletConfig:
-->

<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>Servlet</servlet-class>

<!-- 配置Servlet 的初始化引數, 且節點必須放在 load-on-startup 節點的前面 -->
<init-param>
<!-- 引數名 -->
<param-name>user</param-name>
<!-- 引數值 -->
<param-value>root</param-value>
</init-param>

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


<load-on-startup>1</load-on-startup>
</servlet>

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

</web-app>