巧用struts2的拦截器记日志
1:Struts.xml配置
<!--定义一个拦截器-->
<package name="test" namespace="/test/ " extends="struts-default">
<!-- 终端用户记录日志拦截器 -->
<interceptors>
<interceptor name="userLogInterceptor" class="userLogInterceptor"></interceptor>
<interceptor-stack name="userLogStack">
<interceptor-ref name="userLogInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- userLogInterceptor 的调用-->
<!-- 用户 登录 -->
<action name="loginaction" class="loginaction" method="login">
<result name="success"> /main.jsp</result>
<!-- userLogInterceptor 的调用-->
<interceptor-ref name="userLogStack" />
<interceptor-ref name="token">
<param name="includeMethods">
login
</param>
</interceptor-ref>
</action>
2. userLogInterceptor的实现
1. public class UserLogInterceptor implements Interceptor
2. {
3. private static final long serialVersionUID = 8301888377710974306L;
4.
5.
6.
7. private UserLogService userLogService;
8.
9. public void setUserLogService(UserLogService userLogService)
10. {
11. this.userLogService = userLogService;
12. }
13.
14. public void destroy()
15. {
16. // TODO Auto-generated method stub
17.
18. }
19.
20. public void init()
21. {
22. // TODO Auto-generated method stub
23.
24. }
25.
26. public String intercept(ActionInvocation invocation) throws Exception
27. {
28. HttpServletRequest request = ServletActionContext.getRequest();
29. //invocation.invoke()是放行的意思,等action中的方法执行完成后,会再次返回过来,actionResultString为action中返回的值,如success
30. String actionResultString = invocation.invoke();
31.
32. // 重复提交则不记录日志
33. if ("invalid.token".equalsIgnoreCase(actionResultString))
34. {
35. return actionResultString;
36. }
37.
38. UserLogBean userLogBean = new UserLogBean();
39. userLogBean.setOperatorName(request.getParameter("userName"));
40. userLogBean.setLogType(request.getParameter("logType"));
41. userLogBean.setTargetName(request.getParameter("targetName"));
42. String logDate = Toolkit.getCurrentTime("yyyy-MM-dd HH:mm:ss");
43. userLogBean.setTime(logDate);
44. userLogBean.setResult(actionResultString);
45.
46. // 获取action值栈的中result的信息
47. ValueStack vs = (ValueStack) request.getAttribute("struts.valueStack");
48. Object resultObj = vs.findValue("result");
49. if (null == resultObj)
50. {
51. userLogBean.setDesc("");
52. }
53. else
54. {
55. userLogBean.setDesc(resultObj.toString());
56. }
57.
58. try{
59. // 日志记录到数据库中
60. userLogService.addUserLog(userLogBean);
61. }
62. catch (Exception e)
63. {
64.
65. }
66.
67. return actionResultString;
68. }
69.
70. }
71.
巧用struts2的拦截器记日志
猜你喜欢
转载自wawa129.iteye.com/blog/1276796
今日推荐
周排行