servlet初始化参数配置方式

时间:2021-02-24 21:05:46

servlet初始化参数配置方式


1. init-param

在部署描述符中的节点下添加节点

  <servlet>
<init-param>
<param-name>name</param-name>
<param-value>servlet-value</param-value>
</init-param>
...
</servlet>

之后在对应的Servlet中即可通过获取ServletConfig对象获取初始化参数

    // 获取该Servlet的初始化参数
ServletConfig sc = this.getServletConfig();
String servletValue = sc.getInitParameter("name");

这种方式的特点:
- 只有配置了该节点的Servlet才可以获取该配置
- 每个Servlet支持一个或多个节点
- 运行机制:Servlet初始化过程中,参数将被封装到ServletConfig中

2. context-param

在部署描述符中的节点下添加节点

<webapp>
<!-- 全局配置 -->
<context-param>
<param-name>name</param-name>
<param-value>context-value</param-value>
</context-param>
<!-- /全局配置 -->
...
</webapp>

之后在每一个Servlet中都可以获取该初始化参数

    // 获取整个web应用共享的额初始化参数
ServletContext context = this.getServletContext();
String contextValue = context.getInitParameter("name");

该方式的特点:
- web应用下的每个Servlet都可以获取该配置

3. 动态配置全局变量

在Servlet中通过ServletContextset/getAttribute方法可以动态设置/获取全局变量

    // 动态保存获取全局变量
ServletContext context = this.getServletContext();
context.setAttribute("active", "activeValue");
String activeValue = (String) context.getAttribute("active");

完整代码

<!-- web.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>Archetype Created Web Application</display-name>

<!-- 全局配置 -->
<context-param>
<param-name>name</param-name>
<param-value>context-value</param-value>
</context-param>
<!-- /全局配置 -->

<!-- 测试初始配置信息Servlet -->
<servlet>
<init-param>
<param-name>name</param-name>
<param-value>servlet-value</param-value>
</init-param>
<servlet-name>InitParam</servlet-name>
<servlet-class>com.dotgua.demo1.InitParam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InitParam</servlet-name>
<url-pattern>/param_test</url-pattern>
</servlet-mapping>
<!-- /测试初始配置信息Servlet -->
</web-app>
/**
* InitParam类
*/

package com.dotgua.demo1;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InitParam extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取该Servlet的初始化参数
ServletConfig sc = this.getServletConfig();
String servletValue = sc.getInitParameter("name");

// 获取整个web应用共享的额初始化参数
ServletContext context = this.getServletContext();
String contextValue = context.getInitParameter("name");

// 动态保存获取全局变量
context.setAttribute("active", "activeValue");
String activeValue = (String) context.getAttribute("active");

PrintWriter pw = resp.getWriter();
pw.println("ServletValue = " + servletValue);
pw.println("ContextValue = " + contextValue);
pw.println("activeValue = " + activeValue);
pw.close();
}
}