Servlet之处理请求(九)

  • 时间:
  • 来源:互联网
  • 文章标签:

12.ServletConfig
Servletconfig称为Servlet配置对象;
在Servlet初始化时,会将该servlet的配置信息封装到一个servletconfig对象中。然后容器调用init(ServletConfig)将该ServletConfig对象传递给该servlet;使用该对象可以获得servlet初始化参数、servlet名称、servletcontext对象等。
servletconfig接口定义了4个方法:
String getInitParameter(String name) //根据初始化参数名返回对应的初始化参数值
Enumeration getInitParameterNames() //返回一个Enumeration对象,包含所有的初始化参数名
ServletContext getServletContext() //返回一个代表当前web应用的servletcontext对象
String getServletName()//返回servlet的名字,即web.xml中的元素值

下面的Servlet在init()中通过ServletConfig对象的getInitParamter()得到使用@WebInitParam注解指定的两个参数值;

package com.demo;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ConfigServlet
 */
@WebServlet(name="ConfigServlet",urlPatterns= {"/config.do"},
		initParams= {
				@WebInitParam(name="email",value="abc.@163.com"),
				@WebInitParam(name="telephone",value="88991234")
		}
		)
public class ConfigServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//ServletConfig config=getServletConfig();可直接调用,不需要分开写
		String email=getServletConfig().getInitParameter("email");
		String telephone=getServletConfig().getInitParameter("telephone");
		String servletName=getServletConfig().getServletName();
		
		PrintWriter out=response.getWriter();
		out.println(email+" "+telephone+" "+servletName);
	}

}

本文链接http://www.taodudu.cc/news/show-1782145.html