struts2官方 中文教程 系列四:Action

先贴个本帖的地址,免得其它网站被爬去了struts2教程 官方系列四:Action  即 http://www.cnblogs.com/linghaoxinpian/p/6905521.html 

下载本章节代码

介绍

写一个struts2 Action涉及到以下几部分:

  1.映射一个action到一个指定的类

  2.映射一个result到指定视图

  3.在action中编写控制器逻辑

在先前的教程中,我们了解到如何映射一个URL到一个Action,并且指定调用的方法。

struts2 Action类通常继承ActionSupport类,这个类由struts2 framework提供。ActionSupport提供了常见的行为的默认实现(如 execute、input),也实现了一些有用的接口。当我们的Action类继承自它的话,我们可以重写默认的实现,也可以直接继承使用。在先前的章节中,我们的HelloWorldAction就重写了execute方法。

public class HelloWorldAction extends ActionSupport {
    private MessageStore messageStore;

    public String execute() {
        //每次调用helloCount++
        helloCount++;
        messageStore = new MessageStore() ;
        
        return SUCCESS;
    }

在Action类中处理表单输入

Action类最常见的职责之一是处理表单上的用户输入,在这里有一个有趣的自动填充机制。

<s:form action="hello">
    <s:textfield name="userName" label="Your name" />
    <s:submit value="Submit" />
</s:form>

请注意textfield标签的name属性的值userName。当用户单击上述表单的submit按钮时,表单字段的值将被送到Struts 2 Action类(HelloWorldAction)中。如果有一个与表单字段名值相匹配的公共设置方法,Action类可以自动接收并填充这些表单字段值。

为了演示用法,让我们在HelloWorldAction类中添加如下代码:

package action;

import com.opensymphony.xwork2.ActionSupport;

import model.MessageStore;

public class HelloWorldAction extends ActionSupport {
    private MessageStore messageStore;

    public String execute() {
        //每次调用helloCount++
        helloCount++;
        messageStore = new MessageStore() ;

      if (userName != null) {
        messageStore.setMessage( messageStore.getMessage() + " " + userName);
      }

return SUCCESS;
    }

    public MessageStore getMessageStore() {
        return messageStore;
    }
    //添加一个static int变量
    private static int helloCount = 0;
    
    public int getHelloCount() {
        return helloCount;
    }
    
    //自动填充
    private String userName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

运行:

struts2官方 中文教程 系列四:Action

struts2官方 中文教程 系列四:Action

 由于查询字符串参数是用户名,Struts将该参数的值传递给HelloWorldActionsetUserName方法。

本教程向您介绍了如何编写Action类,以便它可以处理表单中用户输入的值。如果表单有多个字段,那么要有多个与表单字段匹配的set方法是很麻烦的。因此,我们的下一篇教程将介绍如何集成一个模型类将之简化。