JavaEE struts2 Action的结果配置

来源:互联网 发布:杜蕾斯震动棒 知乎 编辑:程序博客网 时间:2024/05/20 05:59

Action不会返回实际的物理页面,而是返回一个“逻辑页面”,Filter负责将此“逻辑页面”映射到物理页面,这个映射规则就是通过struts.xml文件中的result元素定义的。

result的类型

实际上在struts.xml文件中配置result元素时,可以为其指定一个type属性,也就是说,result也是有类型的。result具有如下类型:
- chain:Action链式处理的结果类型;
- dispatcher:将JSP页面作为视图的结果类型;
- freemarker:将FreeMarker模板作为视图的结果类型;
- velocity:将Velocity模板作为视图的结果类型;
- xslt:与XML/XSLT整合的结果类型;
- httpheader:控制特殊的HTTP行为的结果类型;
- stream:向浏览器返回一个InputStream的结果类型(一般用于文件下载);
- plainText:显示某个页面的原始代码的结果类型;
- redirect:直接跳转到其他URL的结果类型;
- redirectAction:直接跳转到其他Action的结果类型。

result的默认类型是dispatcher,用于显示JSP页面。

plainText结果类型

plainText类型的结果直接显示一个页面的原始代码。在struts.xml文件中的配置如下:

<result name="plainText" type="plainText">  <param name="location">/result.jsp</param>  <param name="charSet">GBK</param></result>

result元素的name属性指定“逻辑页面”,type属性指定结果类型;”location”子元素指定物理页面,”charSet”指定输出页面时所用的字符集。

dispatcher结果类型

dispatcher类型是默认的结果类型,这种类型的结果将显示JSP物理页面。它在struts.xml文件中的配置如下:

<result name="dispatcher" type="dispatcher">  <param name="location">/result.jsp</param>  <param name="parse">true</param></result>

这里的”parse”子元素指定是否允许在”location”子元素中使用表达式,默认为”true”,所以上述配置可以简写成:

<result name="dispatcher">/result.jsp</result>

因为Action默认返回的“逻辑页面”为”success”,如果result的name属性为”success”,则可以更为简洁地写成:

<result>/result.jsp</result>

redirect结果类型

redirect类型的结果将重定向到另一个URL,重定向的意思是抛弃原来所有的请求参数,重新发送一个新的请求给目的URL;而转发(dispatcher类型的结果)是将原来的请求转发到目的JSP页面。

其在struts.xml文件中的配置如下:

<result name="redirect" type="redirect">  <param name="location">/result.jsp</param>  <param name="parse">true</param></result>

redirectAction结果类型

redirectAction类型的结果和redirect类型的结果不同,redirect是重定向到一个URL,而redirectAction是重定向到一个Action,其他完全相同。在struts.xml文件中的配置如下:

<result name="redirectAction" type="redirectAction">  <param name="actionName">redirect</param>  <param name="namespace">/zzw</param></result>

这里的”actionName”子元素指定目的Action的名字(即action元素的”name”属性),”namespace”子元素指定目的Action的名空间(即package元素的”namespace”属性)。

使用PreResultListener

PreResultListener是一个监听器接口,它可以在Action完成逻辑处理后,在转入实际的物理页面前被回调。

PreResultListener监听器可以注册给Action或Filter,如果注册给Filter,则此Filter所有影响的Action都可以回调此接口。

使用该监听器的方法如下:

ActionContext.getContext().getActionInvocation().addPreResultListener(new PreResultListener() {    @Override    public void beforeResult(ActionInvocation invocation, String resultCode) {        // ...    }});

测试程序

关于上述内容的测试程序已上传到github:
https://github.com/jzyhywxz/StrutsResult

0 0
原创粉丝点击