Struts2 <s:action>标签示例
精华
小牛编辑
157浏览
2023-03-14
Struts2 的“action”标签是用来直接从JSP页面中调用Action类。如果“executeResult”属性设置为true,则结果页的内容将直接在当前网页渲染。
这是用一个完整的例子很好地说明:
1. 动作
Action类有几个方法用来转发不同结果的结果页面。
ParamTagAction.java
package com.yiibai.common.action; import com.opensymphony.xwork2.ActionSupport; public class ActionTagAction extends ActionSupport{ public String execute() { return SUCCESS; } public String sayHello(){ return "sayHello"; } public String sayStruts2(){ return "sayStruts2"; } public String saySysOut(){ System.out.println("SysOut SysOut SysOut"); return "saySysOut"; } }
2. <s:action>标签示例
下面的JSP页面显示如何使用“action”标签。如果 executeResult=”true”,动作标签被指定方法执行且结果页面将直接显示; 否则,它只是执行的方法,结果页面不会显示出来。
action.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head><title>struts2 action标签示例<title> </head> <body> <h1>Struts2 action标签示例</h1> <ol> <li> Execute the action's result, render the page here. <s:action name="sayHelloAction" executeResult="true"/> </li> <li> Doing the same as above, but call action's sayStruts2() method. <s:action name="sayHelloAction!sayStruts2" executeResult="true"/> </li> <li> Call the action's saySysOut() method only, no result will be rendered, By defautlt, executeResult="false". <s:action name="sayHelloAction!saySysOut" /> </li> </ol> </body> </html>
sayHello.jsp
<html> <head> </head> <body> <div><div class="ads-in-post hide_if_width_less_800"> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- 728x90 - After2ndH4 --> <ins class="adsbygoogle hide_if_width_less_800" data-ad-client="ca-pub-2836379775501347" data-ad-slot="3642936086" data-ad-region="yiibairegion"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div></div><h2>Hello Hello Hello ~ from sayHello.jsp</h2> </body> </html>
sayStruts2.jsp
<html> <head> </head> <body> <h2>Struts 2 Struts 2 Struts 2 ~ from sayStruts2.jsp</h2> </body> </html>
saySysOut.jsp
<html> <head> </head> <body> <h2>SysOut SysOut SysOut ~ from saySysOut.jsp</h2> </body> </html>
3. struts.xml
声明一些结果名称来演示 ExecuteReuslt 的效果。
<?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="default" namespace="/" extends="struts-default"> <action name="actionTagAction" class="com.yiibai.common.action.ActionTagAction" > <result name="success">pages/action.jsp</result> </action> <action name="sayHelloAction" class="com.yiibai.common.action.ActionTagAction" method="sayHello"> <result name="sayHello">sayHello.jsp</result> <result name="sayStruts2">sayStruts2.jsp</result> <result name="saySysOut">saySysOut.jsp</result> </action> </package> </struts>
4. 示例
http://localhost:8080/struts2actiontag/actionTagAction.action
在浏览器中打开上面的URL,显示结果如下图:
参考
- Struts2 <s:action>标签文档
代码下载 - http://pan.baidu.com/s/1kT8NTUf