JavaWeb---通过ServletConfig获取Servlet的初始化参数
package com.zyz; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Enumeration; /** * Created by Administrator on 16-9-29. */ public class ConfigServlet extends HttpServlet { private ServletConfig config;//此成员变量用来接收ServletConfig对象 /** * 当Servlet配置了初始化参数后,web容器在创建Servlet实例对象时, * 会自动将这些初始化参数封装在ServletConfig对象中,并在调用Servlet的 * init方法时,将ServletConfig对象传给Servlet。进而,程序通过ServletConfig * 就可以得到初始化参数信息 * @param config */ @Override public void init(ServletConfig config){ this.config=config; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Content-Type","text/html;charset=utf8"); resp.getWriter().write("从web.xml中获取初始化参数<hr>"); Enumeration<String> paraNames=config.getInitParameterNames(); /** * getInitParameterNames得到的是是枚举类型Enumeration * */ while (paraNames.hasMoreElements()){ String paraName=paraNames.nextElement(); String paraValue=config.getInitParameter(paraName); resp.getWriter().print(paraName+":"+paraValue+"<br>"); } } }