最近为了改一个问题,想加一个控制开关,就在web.xml 中配置了一个 <context-param> 参数,并在 Action 或 Interceptor 中获取参数值。
1、在 web.xml 中添加配置项:
- <context-param>
- <param-name>test</param-name>
- <param-value>true</param-value>
</context-param>
2、获取配置参数值的代码:
- 1 //方式一:
- 2 Object object = ActionContext.getContext().getApplication().get("test");
- 3 if(null != object && Boolean.valueOf(object.toString()))
- 4 {
- 5 System.out.println("logging...");
- 6 }
- 7
- 8 //方式二: Spring 的listener 就是从ServletContext中获取的 getInitParameter
- 9 String parameter = ServletActionContext.getServletContext().getInitParameter("test");
- 10 if(Boolean.valueOf(parameter))
- 11 {
- 12 System.out.println("duide");
- 13 //do sth...
- 14 }
个人觉得 第二种方式 更方便些。
3、闲话
在Servlet 中也可以通过 HTTPRequest 来获取 ServletContext,进而获取 application 级别的配置项: <context-param>