简单说下struts2@Action和@Results

来源:互联网 发布:顶尖数据恢复的注册码 编辑:程序博客网 时间:2024/06/06 10:11
package action;import org.apache.log4j.Logger;import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.Result;import org.apache.struts2.convention.annotation.Results;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;import common.Constant;import common.MySQLDatabaseBackup;@Results({@Result(name = "success",type="chain",location="findAll"),@Result(name = "login",location="/login.jsp")})public class LoginAction extends ActionSupport {//该类继承了ActionSupport类。这样就可以直接使用SUCCESS, LOGIN等变量和重写execute等方法static Logger logger = Logger.getLogger(ActionSupport.class); private static final long serialVersionUID = 1L; private String username; private String password;  public String getUsername() {  return username; } public void setUsername(String username) {  this.username = username; } public String getPassword() {  return password; } public void setPassword(String password) {  this.password = password; }@Action(value="login",results={@Result(name = "success",type="chain",location="findAll"),@Result(name = "login",location="/login.jsp")}) public String execute() throws Exception {//登录前先做备份 if (MySQLDatabaseBackup.exportDatabaseTool("localhost", "root", "123456", "e:/backupDatabase", "mydatabase.sql", "test")) { logger.info("数据库备份成功!!!");        } else {        logger.info("数据库备份失败!!!");        }  if(Constant.UserName.equals(username) && Constant.PassWord.equals(password))//如果登录的用户名=haha并且密码=hehe,就返回SUCCESS;否则,返回LOGIN  {  ActionContext.getContext().getSession().put(Constant.UserName_Session,username);  ActionContext.getContext().getSession().put(Constant.PassWord_Session,password);    BaseAction ba = new BaseAction();  return ba.findAll();  }    return LOGIN; }       public String other()throws Exception { return SUCCESS; }} 

以上是一段java代码

@Results({@Result(name = "success",type="chain",location="findAll"),@Result(name = "login",location="/login.jsp")})


类似于struts.xml 文件里的

<pre name="code" class="html">  <global-results>              <!-- 当返回login视图名时,转入/login.jsp页面 -->              <result name="success" type="chain">findAll</result>            <result name="login">/login.jsp</result>    </global-results>  




从位置可以看出 @Results 是全局的返回,类中的所有结果都可以指向它。

值得注意的是:如果 你既加了result注解 又在struts 中配置了result ,它会使用 struts.xml文件中的配置。




如果使用全局的返回结果可以简写
@Action("login")

带返回的@Action

@Action(value="login",results={@Result(name = "success",type="chain",location="findAll"),@Result(name = "login",location="/login.jsp")})


类似于
<action name="login" class="action.LoginAction" method="execute">            <result name="success" type="chain">findAll</result>            <result name="login">/login.jsp</result></action>




1 0