1,servletconfig对象:
@1,它代表当前Servlet在web.xml中的配置信息。servlet在配置初始化信息时,web容器在创建servlet对象时,会将这些初始化参数封装到servletconfig中,在调用servlet中的init方法时,会将servletconfig对象传给servlet。程序员可以通过servletconfig对象来获取初始化参数。
@2,如何获取servletconfig对象:该对像开始是在init方法里,GenericServlet中的getServletConfig方法中可以返回Config对象.
获取servlet在web.xml中配置的名称:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Myfirstservlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write("hello my name is lishuai");
//servlet在web.xml中的名称
ServletConfig config=this.getServletConfig();
String name=config.getServletName();
System.out.println(name);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
获取当前servlet中配置的初始化参数:
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;
public class Myfirstservlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletConfig config=this.getServletConfig();
//获取在servlet的web.xml的配置信息
String value=config.getInitParameter("name1");
System.out.println(value);
Enumeration e=config.getInitParameterNames();
while(e.hasMoreElements()){
String name1=(String)e.nextElement();
String value1=config.getInitParameter(name1);
System.out.println(name1+":"+value1);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
servlet中配置信息可以在<init-param>中配置。
<servlet>
<servlet-name>Myfirstservlet</servlet-name>
<servlet-class>Myfirstservlet</servlet-class>
<init-param>
<param-name>name1</param-name>
<param-value>value1</param-value>
</init-param>
<init-param>
<param-name>name2</param-name>
<param-value>value2</param-value>
</init-param>
<init-param>
<param-name>name3</param-name>
<param-value>value3</param-value>
</init-param>
</servlet> <servlet>
<servlet-name>Myfirstservlet</servlet-name>
<servlet-class>Myfirstservlet</servlet-class>
<init-param>
<param-name>name1</param-name>
<param-value>value1</param-value>
</init-param>
<init-param>
<param-name>name2</param-name>
<param-value>value2</param-value>
</init-param>
<init-param>
<param-name>name3</param-name>
<param-value>value3</param-value>
</init-param>
</servlet>