Struts2!!Result_DynamicResult

动态result总结

 

action代码

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";

    }

}

struts.XML的配置

<struts> <constant name="struts.devMode" value="true" /> <package name="user" namespace="/user" extends="struts-default"> <action name="user" class="com.bjsxt.struts2.user.action.UserAction"> <result>${r}</result> </action> </package> </struts>

struts.xml中的${r}是配置struts.xml的OGNL表达式,这个是最简单的例子。

类似的运用譬如:你需要判断用户的级别,此用户是管理员还是普通用户,然后跳到对应的action,例子如下:

action的代码:

public class DynamicAction extends ActionSupport {

    

    private  String  username ; 

    private  String  nextAction;

    

    @Override

    public String execute() throws Exception {

        // TODO Auto-generated method stub

        if(username.equals("admin")){

            nextAction = "admin" ; 

        }else if(username.equals("user")){

            nextAction = "user";

        }else{

            nextAction = ERROR;

        }

        

        return  SUCCESS;

    }



    public String getUsername() {

        return username;

    }



    public void setUsername(String username) {

        this.username = username;

    }



    public String getNextAction() {

        return nextAction;

    }



    public void setNextAction(String nextAction) {

        this.nextAction = nextAction;

    }

}

struts.xml中的配置

   

    <package name="dynaTest" namespace="/dynaTest" extends="strurs_default">

        <action name="dyna" class="action.DynamicAction">

            <result name="success"  type="chain" >${nextAction}</result>

        </action>

        

        <action name="admin">

            <result>/admin.jsp</result>

        </action>

        

        <action name="user">

            <result>/user.jsp</result>

        </action>    

    </package>

这个struts.xml中有个Result的属性type,一共有 ?个,默认的是dispatcher

这里面的chain是跳转的下一个目标为action

 

你可能感兴趣的:(struts2)