web.xml上下文初始化参数
1、在web.xml文件中配置上下文参数
1 <!--<context-param>标签声明上下文初始化参数, --> 2 <!-- 上下文初始化的参数可以被应用程序用所有servlet共享 --> 3 <context-param> 4 <!-- 上下文参数可以像map一样使用 --> 5 <param-name>One</param-name><!-- 参数名 --> 6 <param-value>hello</param-value><!-- 参数值 --> 7 </context-param> 8 <context-param> 9 <param-name>Two</param-name> 10 <param-value>dyf</param-value> 11 </context-param>
2、在servlet中获取上下文参数
1 //@WebServlet(name="HelloServlet01",value="/Hello") 2 @WebServlet(name="HelloServlet01",urlPatterns="/Hello") 3 public class HelloServlet01 extends HttpServlet { 4 private static final long serialVersionUID = 1L; 5 6 public void doGet(HttpServletRequest request, HttpServletResponse response) 7 throws ServletException, IOException { 8 this.doPost(request, response); 9 10 } 11 12 public void doPost(HttpServletRequest request, HttpServletResponse response) 13 throws ServletException, IOException { 14 //创建一个获取上下文参数的对象 15 ServletContext context = this.getServletContext(); 16 //获取上下文初始化的参数 17 String initParameter = context.getInitParameter("One"); 18 // context.getInitParameterNames(); 19 PrintWriter writer = response.getWriter(); 20 //将参数返回到页面 21 writer.append(initParameter); 22 } 23 }