无法确定Struts2中的拦截器是否正常工作

时间:2013-11-18 12:07:58

标签: java tomcat struts2

我已按如下方式配置struts.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <action name="hello" 
            class="com.struts2examples.HelloWorldAction" 
            method="execute">
            <result name="success">/HelloWorld.jsp</result>
            <result name="error">/AccessDenied.jsp</result>
            <interceptor-ref name="params"/>
            <interceptor-ref name="timer" />
      </action>
   </package>
</struts>

它应记录执行操作的时间hello。当我在服务器上调用hello操作时,在tomcat日志中生成的日志为:

0:0:0:0:0:0:0:1 - - [18/Nov/2013:17:24:38 +0530] "GET /StrutsHelloWorld/Login.jsp HTTP/1.1" 404 1033
0:0:0:0:0:0:0:1 - - [18/Nov/2013:17:29:30 +0530] "POST /Struts2HelloWorld/hello HTTP/1.1" 200 129
0:0:0:0:0:0:0:1 - - [18/Nov/2013:17:29:41 +0530] "POST /Struts2HelloWorld/hello HTTP/1.1" 200 105
0:0:0:0:0:0:0:1 - - [18/Nov/2013:17:31:04 +0530] "POST /Struts2HelloWorld/hello HTTP/1.1" 200 105

显示拦截器日志。我正在访问 tomcat日志中的localhost_access_log.2013-11-18.txt文件。我是否访问了错误的文件?如果是那么生成的日志会在哪里?

1 个答案:

答案 0 :(得分:1)

您没有指定您正在使用的库(例如Log4j),也没有指定它的配置方式,但您应该查看日志文件,而不是tomcat文件。

来自the documentation

  

此拦截器记录时间量(以毫秒为单位)。 为了   这个拦截器工作正常,必须设置日志框架   到至少INFO级别。此拦截器依赖于Commons Logging API来报告其执行时间值

     

参数

     
      
  • logLevel(可选) - 我们应该使用什么日志级别(跟踪,调试,信息,警告,错误,致命)? - defaut 信息

  •   
  • logCategory(可选) - 如果提供,我们将使用此类别(例如com.mycompany.app)。 默认即可使用   的 com.opensymphony.xwork2.interceptor.TimerInterceptor

  •   
     

上述参数使我们能够记录所有操作执行时间   我们自己的日志文件

那就是说,你只使用两个拦截器;最好将Timer Interceptor添加到defaultStack或至少添加到basicStack(或者自定义堆栈)。将它放在堆栈之后将只记录Action的执行时间,而堆栈之前也会记录拦截器的执行时间:

仅记录操作的执行时间:

<action name="hello" class="com.struts2examples.HelloWorldAction">
    <interceptor-ref name="defaultStack"/>
    <interceptor-ref name="timer" />
    <result>/HelloWorld.jsp</result>
    <result name="error">/AccessDenied.jsp</result>
</action>

记录动作和拦截器的执行时间:

<action name="hello" class="com.struts2examples.HelloWorldAction">
    <interceptor-ref name="timer" />
    <interceptor-ref name="defaultStack"/>
    <result>/HelloWorld.jsp</result>
    <result name="error">/AccessDenied.jsp</result>
</action>

请注意,method="execute"result name="success"不是必需的,因为它们是默认值。