标签:gets public out tom eee boolean tcp stack ram
为了简单,就写个统计Action 请求数量的例子:
1、首先写个 listener
1 public class TestServletContextListener implements ServletContextListener 2 { 3 4 @Override 5 public void contextDestroyed(ServletContextEvent e) 6 { 7 System.out.println("--event-- context destoryed.."); 8 e.getServletContext().log("ssseeevvv"); 9 System.out.println(e.getServletContext().getAttribute("count")); 10 11 // System.out.println(ActionContext.getContext().getApplication().get("count")); //获取不到 ActionContext 12 } 13 14 @Override 15 public void contextInitialized(ServletContextEvent evt) 16 { 17 System.out.println("--event-- context initialized.."); 18 ServletContext ctx = evt.getServletContext(); 19 20 if(null == ctx.getAttribute("count")) 21 {
22 ctx.setAttribute("count",0); //为了简单起见,我就数数了 23 //ctx.setAttribute("count", new HashMap<String,Set<String>>()); 24 } 25 } 26 27 }
2、在拦截器中获取信息,保存在 ServletContext 的 count 对象里。
1 public class TestInterceptor extends MethodFilterInterceptor 2 { 3 private static final long serialVersionUID = 1L; 4 5 @Override 6 protected String doIntercept(ActionInvocation invocation) throws Exception 7 { 8 System.out.println("-m- Enter into TestInterceptor..."); 9 countActionRequestNumber(); 10 11 invocation.invoke(); //一定要有这一句,不然请求走到这个拦截器之后就断了 12 return null; 13 } 14 15 private void countActionRequestNumber() 16 { 17 //方式二: Spring 的listener是从ServletContext中获取的 getInitParameter 18 ServletContext servletContext = ServletActionContext.getServletContext(); 19 String parameter = servletContext.getInitParameter("test"); 20 21 if(Boolean.valueOf(parameter)) 22 { 23 int count = (int)servletContext.getAttribute("count"); 24 servletContext.setAttribute("count", ++count); 25 } 26 } 27 }
3、在 web.xml 中注册监听器
1 <context-param> 2 <param-name>test</param-name> 3 <param-value>true</param-value> 4 </context-param> 5 6 <listener> 7 <listener-class>test.listener.TestServletContextListener</listener-class> 8 </listener>
4、在struts 文件中配置拦截器
1 <package name="one" extends="struts-default"> 2 3 <interceptors> 4 <interceptor name="test" class="test.interceptor.TestInterceptor"></interceptor> 5 <interceptor-stack name="selfDefaultIntcptorStack"> 6 <interceptor-ref name="test"></interceptor-ref> 7 <interceptor-ref name="defaultStack"></interceptor-ref> 8 </interceptor-stack> 9 </interceptors> 10 11 <default-interceptor-ref name="selfDefaultIntcptorStack"></default-interceptor-ref> 12 13 <action name="test1" class="test.action.TestAction" method="test1"> 14 </action> 15 <action name="test2" class="test.action.TestAction" method="test2"> 16 </action> 17 18 </package>
note: 如果是 eclipse 启动的 tomcat ,最好是使用右键 stopped 停止服务器,而不是直接点击红色按钮强制关闭。
标签:gets public out tom eee boolean tcp stack ram
原文地址:https://www.cnblogs.com/Home-Artchy/p/web_listener0.html