在web.xml文件中配置:
ServletDemo7.java:
结果:
data=XXXXXX
data1=YYYYYY
data2=ZZZZZZ
<init-param> <param-name>data</param-name> <param-value>XXXXX</param-value> </init-param> <init-param> <param-name>data1</param-name> <param-value>YYYYY</param-value> </init-param> <init-param> <param-name>data2</param-name> <param-value>ZZZZZ</param-value> </init-param>
ServletDemo7.java:
package cn.edu; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //获取Web应用的初始化参数 public class ServletDemo7 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //单个输出全局初始化参数 String num=this.getServletContext().getInitParameter("data"); System.out.println(num); //输出多个全局初始化参数 Enumeration e = this.getServletContext().getInitParameterNames(); while(e.hasMoreElements()){ String name=(String)e.nextElement(); String value1=this.getServletConfig().getInitParameter(name); System.out.println(name+" = "+value1); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
结果:
data=XXXXXX
data1=YYYYYY
data2=ZZZZZZ