struts2 在 Action 或 Interceptor 中获取 web.xml 中配置的 参数 (这是我的第一篇博文,哈哈。)

时间:2021-04-30 01:42:54

最近为了改一个问题,想加一个控制开关,就在web.xml 中配置了一个 <context-param> 参数,并在 Action 或 Interceptor 中获取参数值。

1、在 web.xml 中添加配置项:

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

2、获取配置参数值的代码:

 //方式一:
Object object = ActionContext.getContext().getApplication().get("test");
if(null != object && Boolean.valueOf(object.toString()))
{
System.out.println("logging...");
} //方式二: Spring 的listener 就是从ServletContext中获取的 getInitParameter
String parameter = ServletActionContext.getServletContext().getInitParameter("test");
if(Boolean.valueOf(parameter))
{
System.out.println("duide");
//do sth...
}

个人觉得 第二种方式 更方便些。

3、闲话

在Servlet 中也可以通过 HTTPRequest 来获取 ServletContext,进而获取 application 级别的配置项: <context-param>