javaweb:ServletContext应用(一)——获取初始化参数
利用SerlvetContext读取初始化参数
首先我们要在web.xml增加一点初始化参数用于测试
<context-param> <param-name>sctest</param-name> <param-value>this is a test message</param-value> </context-param>
然后我们需要建立一个测试类 ServletDemo001
1 package com.jms.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletContext; 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class ServletDemo001 extends HttpServlet{ 12 13 @Override 14 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 15 ServletContext context = this.getServletContext();//获取ServletContext对象 16 String test = context.getInitParameter("sctest");//获取名为sctest的初始化参数 17 resp.getWriter().print(test); 18 } 19 20 @Override 21 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 22 doGet(req, resp); 23 } 24 25 }
我们需要再次修改web.xml为新的类注册servlet
<!--注册Servlet--> <servlet> <servlet-name>demo001</servlet-name> <servlet-class>com.jms.servlet.ServletDemo001</servlet-class> </servlet> <!--Servlet的请求路径--> <servlet-mapping> <servlet-name>demo001</servlet-name> <url-pattern>/demo001</url-pattern> </servlet-mapping>
最后进行测试
没有问题
(本文仅作个人学习记录用,如有纰漏,敬请指正)