zoukankan      html  css  js  c++  java
  • struct2(四)编写Struct2 的Action

    简介:

    1.映射一个Action到一个类上面

    2.把结果返回到view展示

    3.编写Action对应的控制逻辑

     

    1. Action Mapping

    <action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" method="execute">

    <result name="success">/HelloWorld.jsp</result>

    </action>

    上面的Action,类HelloWorldAction将会返回HelloWorld.jsp到浏览器

           2. Struts 2 Action Classes

    Action类在MVC中是作为控制器,负责的是响应用户的操作,执行业务逻辑(调用其他的类做一些其他的事情),然后返回结果告诉Struct应该响应哪一个页面。

    Struct2 的Action类常常扩展自ActionSupport,这个类是有Struct2框架提供的。ActionSupport提供大多数动作的默认的实现,并且实现了Struct2 的接口。自定义的类扩展自ActionSupport,可以重装默认的实现,也可以继承它们。

    我们在显示的页面中加上:

    <s:form action="hello">

    <s:textfield name="userName" label="Your name" />

    <s:submit value="Submit" />

    </s:form>

    希望在展示的时候能够展示欢迎输入人的名称。

    我们在HelloWorldAction 加上:

    private String userName;

    public String getUserName() {

    return userName;

    }

    public void setUserName(String userName) {

    this.userName = userName;

    }

    来记录输入人的名称,并且填入欢迎的信息中。

    if (userName != null) {

    messageStore.setMessage( messageStore.getMessage() + " " + userName);

    }

    最后HelloWorldAction为:

    import org.apache.struts.helloworld.model.MessageStore;
    import com.opensymphony.xwork2.ActionSupport;
     
    public class HelloWorldAction extends ActionSupport {
     
        private static final long serialVersionUID = 1L;
     
        private MessageStore messageStore;
        
        private static int helloCount = 0;
        
        private String userName; 
    
        @Override
        public String execute() throws Exception {
             
            messageStore = new MessageStore() ;
            if(this.getUserName() != null){
                messageStore.setMessage( messageStore.getMessage() + " " + userName); 
            }
            //记录执行的次数
            helloCount++;
            return SUCCESS;
        }
     
       
        public MessageStore getMessageStore() {
            return messageStore;
        }
     
        public void setMessageStore(MessageStore messageStore) {
            this.messageStore = messageStore;
        }
     
        public int getHelloCount() {
    
            return helloCount;
    
        }
    
        public void setHelloCount(int helloCount) {
    
            HelloWorldAction.helloCount = helloCount;
    
        }
    
    
        public String getUserName() {
            return userName;
        }
    
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    }

     

    测试:http://127.0.0.1:12345/struct2test/index.action

    image

    image

    提交:

    image

  • 相关阅读:
    JS基础类型和引用类型
    ul的margin撑不开想要的距离的办法
    html中的列表
    BEM的命名规则
    意义模糊的函数签名……文档注释
    最基础,新手入门第一段代码
    Cookie的使用
    用servlet校验密码2
    用servlet进行用户名和密码校验
    登录页面
  • 原文地址:https://www.cnblogs.com/zhailzh/p/3989083.html
Copyright © 2011-2022 走看看