Home context-param和init-param
Post
Cancel

context-param和init-param

初始化参数

web.xml里面可以定义两种参数

  1. Application范围内的参数,存放在ServletContext中,在web.xml中配置如下
    1
    2
    3
    4
    
     <context-param>
         <param-name>context/param</param-name>
         <param-value>avalible during application</param-value>
     </context-param>
    
  2. Servlet范围内的参数,只能在Servlet的init()方法中取得,在web.xml中配置如下
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
     <servlet>
         <servlet-name>MainServlet</servlet-name>
         <servlet-class>com.wes.controller.MainServlet</servlet-class>
         <init-param>
            <param-name>param1</param-name>
            <param-value>avalible in servlet init()</param-value>
         </init-param>
         <load-on-startup>0</load-on-startup>
     </servlet>
    

初始化参数获取

在Servlet中可以通过代码分别取用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.wes.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class MainServlet extends HttpServlet {

    public MainServlet() {
        super();
    }

    public void init() throws ServletException {
        System.out.println("下面的参数是存放在ServletContext中的");
        System.out.println(getServletContext().getInitParameter("context/param"));
        System.out.println("下面的参数param1是在Servlet中存放的");
        System.out.println(this.getInitParameter("param1"));
    }

}

第一种参数在Servlet里面可以通过getServletContext().getInitParameter("context/param")得到
第二种参数只能在Servlet的init()方法中通过this.getInitParameter("param1")得到

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<servlet>
    <description></description>
    <display-name>IOCServlet</display-name>
    <servlet-name>IOCServlet</servlet-name>
    <servlet-class>com.hp.servlet.IOCServlet</servlet-class>
    <init-param>
        <param-name>test</param-name>
        <param-value>123</param-value>
    </init-param>
</servlet> 

<context-param>
    <param-name>test1</param-name>
    <param-value>456</param-value>
</context-param> 
1
2
3
4
5
6
PrintWriter out = response.getWriter();
out.println("context test:" + getServletContext().getInitParameter("test"));
out.println("context test1:" + getServletContext().getInitParameter("test1"));
out.println("init test:" + this.getInitParameter("test"));
out.println("init test1:" + this.getInitParameter("test1"));
out.close();
1
2
3
4
5
# 结果
context test null
context test1 456
init test 123
init test1 null
This post is licensed under CC BY 4.0 by the author.