ServletConfig

在Servlet容器初始化时,Servlet容器将ServletConfig传递给Servlet的init方法 。 ServletConfig封装可以通过@WebServlet 或者不熟描述符传给一个Servlet的配置信息。以这种方式传递的每一条信息都称为初始参数。

为了从一个Servlet内部获取某个初始参数的值,应该在由Servlet容器传递给Servlet容器的getinitParameter方法,获取getinitParameter 方法的签名如下:

servletConfig.getInitParameter(NAME)

servletConfig.getInitParameterName( )

除了getInitParameter 和 getInitParameterName之外,还有另一个方法有用:getServletContext。利用这个方法可以从Servlet内部获取ServletContext。

下面举例:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

public class ServletConfigDemo implements Servlet{
	private transient ServletConfig servletConfig;
	public ServletConfig getServletConfig() {
		return servletConfig;
	}
	public void init(ServletConfig config) throws ServletException {
		this.servletConfig = config;
		System.out.println("***init***");
	}
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		ServletConfig servletConfig = getServletConfig();
		String admin = servletConfig.getInitParameter("admin");
		String email = servletConfig.getInitParameter("email");
		ServletContext context = servletConfig.getServletContext();
		res.setContentType("text/html");
		PrintWriter writer = res.getWriter();
		writer.print(""+"Admin:"+admin+"
Email:"+email+"
ServletContext:"+context+""); } public String getServletInfo() { return "ServletConfig demo"; } public void destroy() { // TODO Auto-generated method stub } }
下面是Web.XML 文件的配置


  	ServletConfig
  	servlet.ServletConfigDemo
  	
  		admin
  		zhangsan
  	
  	
  		email
  		[email protected]
  	
  
  
  	ServletConfig
  	/config
  



你可能感兴趣的:(WEB,Servlet)