[关闭]
@HUST-SuWB 2015-02-09T14:25:41.000000Z 字数 9565 阅读 399

Struts2中 Result类型配置详解(转载)

项目实战


一个result代表了一个可能的输出。当Action类的方法执行完成时,它返回一个字符串类型的结果码,框架根据这个结果码选择对应的result,向用户输出。
在com.opensymphony.xwork2.Action接口中定义了一组标准的结果代码,可供开发人员使用,当然了只有我们的action继承ActionSupport这个类才可以使用下面的结果代码,如下所示:

  1. public interface Action
  2. {
  3. public static final String SUCCESS = success”;
  4. public static final String NONE = none”;
  5. public static final String ERROR = error”;
  6. public static final String INPUT = input”;
  7. public static final String LOGIN = login”;
  8. }

其中 Struts2应用在运行过程中若发现addFieldError()中有信息或者类型转换失败或着输入校验失败等情况,那么它会自动跳转到name为input的,然后转到INPUT所对应的页面。若JSP页面中表单是用普通编写的,发生错误而返回该页面时,则原数据将消失;若JSP页面中表单是用编写的,发生错误而返回该页面时,则原数据仍存在;若没有提供name值为input的,那么发生错误时,将直接在浏览器中提示404错误。
除了这些预定义的结果码外,开发人员也可以定义其它的结果码来满足自身应用程序的需要。
Result配置由两部分组成:一部分是result映射,另一部分是result类型。下面我们分别对这两部分进行介绍。
一、配置 result映射
在result映射的配置中,在指定实际资源的位置时,可以使用绝对路径,也可以使用相对路径。绝对路径以斜杠(/)开头,相对于当前的Web应用程序的上下文路径;
相对路径不以斜杠(/)开头,相对于当前执行的action的路径,也就是namespace指定的路径。
例如:

  1. <package name="default" extends="struts-default" namespace="/admin">
  2. <action name="login" class="com.ibm.LoginAction">
  3. <result>success.jsp</result>
  4. <result name="error">/error.jsp</result>
  5. </action>
  6. </package>

如果当前Web应用程序的上下文路径是/Shop,那么请求/Shop/admin/login.action,执行成功后,转向的页面路径为:/Shop/admin/success.jsp;执行失败后,转向的页面路径为/Shop/error.jsp。

二、result结果类型详解

Type 类型值 作用说明 对应类
chain 用来处理Action链 com.opensymphony.xwork2.ActionChainResult
dispatcher(默认值) 用来转向页面,通常处理JSP org.apache.struts2.dispatcher.ServletDispatcherResult
redirect 重定向到一个URL org.apache.struts2.dispatcher.ServletRedirectResult
redirectAction 重定向到一个 Action org.apache.struts2.dispatcher.ServletActionRedirectResult
plainText 显示源文件内容,如文件源码 org.apache.struts2.dispatcher.PlainTextResult
freemarker 处理 FreeMarker 模板 org.apache.struts2.views.freemarker.FreemarkerResult
httpheader 控制特殊 http 行为的结果类型 org.apache.struts2.dispatcher.HttpHeaderResult
stream 向浏览器发送 InputSream对象,通常用来处理文件下载,还可用于返回 AJAX 数据 org.apache.struts2.dispatcher.StreamResult
velocity 处理Velocity模板 org.apache.struts2.dispatcher.VelocityResult
xslt 处理 XML/XLST模板 org.apache.struts2.views.xslt.XSLTResult

1、dispatcher结果类型
Struts2在后台使用Servlet API的RequestDispatcher来转发请求,因此在用户的整个请求/响应过程中,目标Servlet/JSP接收到的request/response对象,与最初的Servlet/JSP相同。
Dispatcher结果类型的实现是org.apache.struts2.dispatcher.ServletDispatcherResult,该类的二个属性(property):location和parse,这两个属性可以通过struts.xml配置文件中的result元素的param子元素来设置。param元素的name属性指定结果类型实现类的属性名,param元素的内容是属性的值。例如:

  1. <result name=“success type=“dispatcher”>
  2. <param name=“location >/success.jsp</param>
  3. <param name=“parse >true</param>
  4. </result>

说明:
A、location参数用于指定action执行完毕后要转向的目标资源,parse属性是一个布尔类型的值,如果为true,则解析location参数中的OGNL表达式;如果为false,则不解析。parse属性的默认值就是true。location参数是默认的参数,在所有的Result实现类中,都定义了一个字符串类型的DEFAULT_PARAM静态常量,专门用于指定默认的参数名。 DEFAULT_PARAM常量的定义:public static final String DEFAULT_PARAM=“location”;
B、在设置location参数时,可以在参数值中使用OGNL表达式。

  1. <action name=“viewNews class=“com.ibm.ViewNewsAction
  2. <result name=“success type=“dispatcher”>
  3. <!--如果参数是中文:请参看最底部例子-->
  4. <param name=“location >/viewNews.jsp?id=${id}</param>
  5. <param name=“parse >true</param>
  6. </result>
  7. </action>

考虑到默认值的使用(dispatcher和location都是默认值),上述可以简化为:

  1. <action name=“viewNews class=“com.ibm.ViewNewsAction”>
  2. <result name=“success >viewNews.jsp?id=${id}</result>
  3. </action>

2、redirect结果类型(重定向到一个Url,也可以是Action或一个页面)
Redirect结果类型在后台使用HttpServletResponse的sendRedirect方法将请求重定向到指定的URL,它的实现类是org.apache.struts2.dispatcher.ServletRedirectResult.该类同样有二个属性(property):location和parse,在使用redirect结果类型的场景中,用户要完成一次与服务器之间的交互,浏览器需要完成两次请求,因此第一次请求中的数据在第二次请求中是不可用的,这意味在目标资源中是不能访问action实例、action错误以及错误等。
如果有某些数据需要在目标资源中访问,
i、一种方式是将数据保存到Session中,
ii、另一种方式是通过请求参数来传递数据。
示例(1)、

  1. <result name="success" type="redirect">
  2. <param name="location">foo.jsp</param>
  3. <param name="parse">false</param><!--不解析OGNL-->
  4. </result>

示例(2)、

  1. <package name="passingRequestParameters"extends="struts-default"namespace="/passingRequestParameters">
  2. <-- Passparameters (reportType, width and height),重定向到Url并且传参 ,如果参数是中文:请参看最底部例子-->
  3. <!--The redirect-action url generated will be :
  4. /genReport/generateReport.jsp?reportType=pie&width=100&height=100-->
  5. <actionname="gatherReportInfo" class="...">
  6. <resultname="showReportResult" type="redirect">
  7. <param name="location">generateReport.jsp</param>
  8. <param name="namespace">/genReport</param>
  9. <param name="reportType">pie</param>
  10. <param name="width">100</param>
  11. <param name="height">100</param>
  12. </result>
  13. </action>
  14. </package>

3、redirectAction结果类型(重定向到一个Action)
他经常用于防止表单重复提交,比方说在增加完用户之后要显示列表 redirectAction结果类型的实现类是org.apache.struts2.dispatcher.ServletActionRedirectResult,该类是ServletRedirectResult的子类,因此我们也就可以判断出redirectAction结果类型和redirect结果类型的后台工作原理是一样的,即都是利用HttpServletResponse的sendRedirect方法将请求重定向到指定的URL。
示例、

  1. <package name="public"extends="struts-default">
  2. <action name="login"class="...">
  3. <!--Redirect to another namespace 重定向到不同命名空间下的action -->
  4. <result type="redirectAction">
  5. <param name="actionName">dashboard</param>
  6. <param name="namespace">/secure</param>
  7. </result>
  8. </action>
  9. </package>
  10. <package name="secure"extends="struts-default" namespace="/secure">
  11. <-- Redirectto an action in the same namespace,重定向到同一命名空间下的action-->
  12. <action name="dashboard" class="...">
  13. <result>dashboard.jsp</result>
  14. <result name="error"type="redirectAction">error</result>
  15. </action>
  16. <action name="error" class="...">
  17. <result>error.jsp</result>
  18. </action>
  19. </package>
  20. <package name="passingRequestParameters"extends="struts-default"namespace="/passingRequestParameters">
  21. <-- Passparameters (reportType, width and height),重定向到Action并且传参,如果参数是中文:请参看最底部例子 -->
  22. <!--TheredirectAction url generated will be :
  23. /genReport/generateReport.action?reportType=pie&width=100&height=100-->
  24. <action name="gatherReportInfo" class="...">
  25. <result name="showReportResult" type="redirectAction">
  26. <param name="actionName">generateReport</param>
  27. <param name="namespace">/genReport</param>
  28. <param name="reportType">pie</param>
  29. <param name="width">100</param>
  30. <param name="height">100</param>
  31. <param name="empty"></param>
  32. <param name="supressEmptyParameters">true</param>
  33. </result>
  34. </action>
  35. </package>

4、链接类型 result:chain(从一个Action转发到另一个Action)
chain结果类型有4个属性,分别是:

  1. actionName (default) - the name of the action that will be chained to
  2. namespace - used to determine which namespace the Action is in that we're chaining. If namespace is null, this defaults to the current namespace
  3. method - used to specify another method on target action to be invoked. If null, this defaults to execute method
  4. skipActions - (optional) the list of comma separated action names for the actions that could be chained to
    示例、
  1. <package name="public"extends="struts-default">
  2. <!-- Chain creatAccount to login, using the default parameter ,链接到同一命名空间下的Action,-->
  3. <action name="createAccount" class="...">
  4. <result type="chain">login</result>
  5. </action>
  6. <actionname="login" class="...">
  7. <!--Chain to another namespace -->
  8. <result type="chain">
  9. <param name="actionName">dashboard</param>
  10. <param name="namespace">/secure</param>
  11. </result>
  12. </action>
  13. </package>
  14. <package name="secure" extends="struts-default"namespace="/secure">
  15. <actionname="dashboard" class="...">
  16. <result>dashboard.jsp</result>
  17. </action>
  18. </package>

5、HttpHeader Result:HttpHeader(用来控制特殊的Http行为)
httpheader结果类型很少使用到,它实际上是返回一个HTTP响应的头信息
示例:

  1. <result name="success"type="httpheader">
  2. <paramname="status">204</param>
  3. <paramname="headers.a">a custom header value</param>
  4. <paramname="headers.b">another custom header value</param>
  5. </result>
  6. <result name="proxyRequired"type="httpheader">
  7. <paramname="error">305</param>
  8. <paramname="errorMessage">this action must be accessed through aprozy</param>
  9. </result>

6、Stream Result(向浏览器发送InputSream对象,通常用来处理文件下载)

  1. <result name="success"type="stream">
  2. <param name="contentType">image/jpeg</param>
  3. <param name="inputName">imageStream</param>
  4. <param name="contentDisposition">attachment;filename="document.pdf"</param>
  5. <param name="bufferSize">1024</param>
  6. </result>

7、PlainText Result(显示原始文件内容,例如文件源代码)

  1. <action name="displayJspRawContent">
  2. <result type="plaintext">/myJspFile.jsp</result>
  3. </action>
  4. <action name="displayJspRawContent">
  5. <result type="plaintext">
  6. <param name="location">/myJspFile.jsp</param>
  7. <param name="charSet">UTF-8</param>
  8. </result>
  9. </action>

若仅设置type="plainText"的话,页面中显示中文时会乱码,这时就可以借助它的charSet属性以解决中文显示时的乱码问题,如果不设置charSet属性,反而去配置struts.i18n.encoding全局属性,是不能解决问题的,设置charSet属性的目的就是让JSP页面的编码与明文显示时的编码一致。
8、Velocity Result(处理Velocity模板)

  1. <result name="success"type="velocity">
  2. <paramname="location">foo.vm</param>
  3. </result>

9、XLS Result(处理XML/XLST模板)

  1. <result name="success" type="xslt">
  2. <paramname="location">foo.xslt</param>
  3. <paramname="matchingPattern">^/result/[^/*]$</param>
  4. <paramname="excludingPattern">.*(hugeCollection).*</param>
  5. </result>

10、 FreeMarkerResult (处理FreeMarker模板)

  1. <result name="success"type="freemarker">foo.ftl</result>

附、另外第三方的Result类型还包括JasperReportsPlugin,专门用来处理JasperReport类型的报表输出。

  1. <%@ tagliburi="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
  2. <%@ taglib prefix="s"uri="/struts-tags" %>
  3. <%-- Show usage; Used in Header --%>
  4. <tiles:importAttribute name="title"scope="request"/>
  5. <html>
  6. <head><title><tiles:getAsStringname="title"/></title></head>
  7. <body>
  8. <tiles:insertAttribute name="header"/>
  9. <pid="body">
  10. <tiles:insertAttributename="body"/>
  11. </p>
  12. <p>Noticethat this is a layout made in JSP</p>
  13. </body>
  14. </html>

注意!!!!.传递中文
记住永远不要在浏览器的地址栏中传递中文。在传递中文前先进行编码
A.action中

  1. public class User extends ActionSupport{
  2. private String username;
  3. public String getUsername() {
  4. return username;
  5. }
  6. public void setUsername(String username) {
  7. this.username = username;
  8. }
  9. @Override
  10. public String execute() throws Exception {
  11. // TODO Auto-generated method stub
  12. username=URLEncoder.encode("郭蕾","utf-8");//先进行编码
  13. System.out.println(username);
  14. return "redirect";
  15. }
  16. }

B.struts.xml中

  1. <action name="redirect" class="action.User">
  2. <result type="redirect" name="redirect">/redirect.jsp?username=${username}//如果要传递两个参数,中间用&amp;代替& </result>
  3. </action>

在这里使用了类似于el表达式的方式传值,${username}其中username为action中定义的
C.redirect.jsp中

  1. <body>
  2. <%String s=request.getParameter("username");
  3. s=new String(s.getBytes("iso8859-1"),"utf-8");
  4. s=URLDecoder.decode(s,"utf-8");
  5. out.println(s);%>
  6. </body>

重定向中传递中文先进行编码,在jsp页面中先接受参数,然后对其进行字节分解,然后进行解码。

原博文连接:
http://blog.sina.com.cn/s/blog_7ffb8dd501014uzw.html

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注