0%

Servlet上下文对象

2017年9月7日 上午8:58

上下文对象的作用:

获取web.xml的 标签中的值,标签的作用域是所有的servlet类文件,这点与一个具体servlet类对应的标签下的标签,作用域是不同的,可以将标签的值理解成一个全局变量

获取方法:

  1. 继承HttpServlet的类中:在service()方法中使用getServletContext()方法来获得
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /*
    * 接收所有请求的方法
    */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    //servlet 四大作用域对象之一。他是servlet上下文对象
    ServletContext application = getServletContext();
    //getInitParameter(java.lang.String name)
    String value = application.getInitParameter("param-name");
    System.out.println(value);

    }
    1. 实现Servlet接口的类中:通过ServletConfig对象的getServletContext()方法来获得上下文对象
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      /*
      * servlet 初始化方法
      * servlet生命周期方法之一
      */
      @Override
      public void init(ServletConfig arg0) throws ServletException {
      System.out.println("init 222 ...");
      String value = arg0.getServletContext().getInitParameter("param-name");
      System.out.println(" 222 ... "+value);
      }

在web.xml中的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<context-param>
<param-name>param-name</param-name>
<param-value>param-value</param-value>
</context-param>

.....

</web-app>