其他分享
首页 > 其他分享> > ServletContext应用(一)——获取初始化参数

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>

最后进行测试

 

 没有问题

 

(本文仅作个人学习记录用,如有纰漏,敬请指正)

 

标签:初始化,resp,参数,ServletContext,import,servlet,javax
来源: https://www.cnblogs.com/jmsstudy/p/16513944.html