Struts 2標簽庫里的debug標簽以及Struts 2提供的Debugging攔截器大大簡化了Web應用程序的調試工作,Profiling攔截器可以分析應用程序中的性能瓶頸。
使用debug標簽獲取調試信息
debug標簽的用途是顯示ValueStack棧和其他對象的內容,它非常易用,只需要在需要調試的頁面插入如下語句:
示例:
index.jsp
<body>
<s:debug></s:debug>
</body>
在瀏覽器中輸入:http://localhost:8081/DebugAndProfiling/index.jsp,獲得如下頁面:

點擊"[Debug]",會獲得如下界面

可以看到獲取了各種棧對象和ContextMap里的對象。這些信息可以幫助我們快速排查Web應用程序里的潛在隱患。
使用Debugging攔截器獲取調試信息
Debugging攔截器是默認攔截器棧defaultStack的一員,若引用了默認攔截器棧,則不需要特意去引用。使用該攔截器可以使我們查看ValueStack和其他一些對象內容。觸發這個攔截器的方法是在用來觸發某個動作的URL地址欄里添加debug=xml或者debug=console參數。
debug=xml參數將會導致產生一個XML文件,它包含ValueStack和其他一些對象的值:
示例:
input.jsp
<body>
<s:form action="debug.action?debug=xml">
<s:textfield name="username" label="Enter your name"></s:textfield>
<s:submit value="submit"></s:submit>
</s:form>
</body>
struts.xml
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="debugAndProfilingPackage" extends="struts-default">
<action name="debug" class="struts2.action.DebugAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
struts.devMode的默認值為false,需要將其修改為true,才可以使該功能生效。
動作類:
public class DebugAction extends ActionSupport {
private static final long serialVersionUID = -1345567815879866335L;
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String execute()
{
return SUCCESS;
}
}
index.jsp
<body>
<s:property value="username"/>,Welcome
</body>
在瀏覽器中輸入:http://localhost:8081/DebugAndProfiling/input.jsp,獲得如下頁面:

點擊"submit"按鈕,查看結果:

可以看到,ValueStack和其他對象的信息。debug=console的設置與xml一致,只是好像IE不支持console選項。
使用Profiling攔截器分析應用程序的性能
Struts 2自帶的性能分析功能可以幫助我們找出應用程序里的瓶頸。該功能是由com.opensymphony.xwork2.util.profiling.UtilTimerStack類提供的支持,讓Struts 2可以跟蹤記錄它的過濾器調度程序、每一個攔截器、每個動作和每個結果的執行用時情況。Profiling攔截器可以幫助我們激活性能分析功能。
激活Profiling攔截器與激活Debugging攔截器相似,也是在某個動作的URL地址里加上profiling=true或profiling=yes請求參數。還必須將struts.devMode屬性設置為true才能使用這個功能,否則設置不會生效。
示例:
修改上面例子的struts.xml文件
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="debugAndProfilingPackage" extends="struts-default">
<action name="debug" class="struts2.action.DebugAction">
<interceptor-ref name="profiling"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
因為profiling攔截器不屬于defaultStack攔截器棧,需要特別引用,還需要注意Profiling攔截器所處的的位置,決定了它分析性能的范圍。
修改input.jsp
<body>
<s:form action="debug.action?profiling=true">
<s:textfield name="username" label="Enter your name"></s:textfield>
<s:submit value="submit"></s:submit>
</s:form>
</body>
其他不用修改,在瀏覽器輸入: http://localhost:8081/DebugAndProfiling/input.jsp,獲得如下頁面:

點擊"submit"按鈕,查看結果:

該結果是在我的IDE(MyEclipse9.0)的控制臺頁面獲取的.可以看到我們設置的Profiling攔截器生效了,它打印出了每一個流程所花費的時間。每一行代表一個活動。每行最左邊的數字是截止到即將觸發這個活動時已經耗用的時間。