导航

关于struts.xml中result的一些设置

Posted on 2012-11-16 15:47  阿里大盗  阅读(801)  评论(0)    收藏  举报

 

  1. result类型(常用2-4种)见其它随笔。
  2. global-results(全局结果集)

使用方法:<package name="user" namespace="/user" extends="struts-default">

    <global-results>

        <result name="mainpage">/main.jsp</result>

    </global-results>

   

    <action name="index">

        <result>/index.jsp</result>

    </action>

   

        <action name="user" class="com.bjsxt.struts2.user.action.UserAction">

        <result>/user_success.jsp</result>

        <result name="error">/user_error.jsp</result>

        </action>     

    </package>

   

    <package name="admin" namespace="/admin" extends="user">

    <action name="admin" class="com.bjsxt.struts2.user.action.AdminAction">

        <result>/admin.jsp</result>

    </action>

</package>

 

可以发现:global-results是用来修饰某个result的,且每个package只有一个,目的是使同package或不同package的不同action都能使用到某个result(从而跳转到某个页面,一般可以是项目中用到的错误页面等公共页面)。

 

  1. 将Action中的属性(参数)值传递给struts.xml。

方法:public class UserAction extends ActionSupport {

    private int type;

   

    private String r;

 

    public String getR() {

       return r;

    }

 

    public void setR(String r) {

       this.r = r;

    }

 

    public int getType() {

       return type;

    }

 

    public void setType(int type) {

       this.type = type;

    }

 

    @Override

    public String execute() throws Exception {

       if(type == 1) r="/user_success.jsp";

       else if (type == 2) r="/user_error.jsp";

       return "success";

    }

 

<result>${r}</result>

 

原理:OGNL表达式可以帮助struts.xml从ValueStack中取值。

 

  1. 当result type=redirect时,如果需要传递参数,那么必须注意result在跳转的jsp中带上动态参数(见3),并且在客户端跳转的jsp页面中使用<s:property value=”#key”/>来获取参数的值,这是因为:每一次请求都拥有同一个ValueStack,因为这个请求会通过Action生成ValueStack,而客户端跳转(redirect)是第二次请求,与(dispatcher即forward)不同,那么当result以redirect方式跳转至新的jsp页面时,这里的ValueStack中是没有属性值的(因为这次的请求没有通过Action),但是可以发现在StackContext中存在parameters,所以可以获取。

方法:<result type="redirect">/user_success.jsp?t=${type}</result>

/!—type是第一次请求时传递给Action的属性,在ValueStack中存在--/

from actioncontext: <s:property value="#parameters.t"/>