3.Coding Struts 2 Actions

本系列文章均为自我学习而作,禁止转载

本篇是struts2 reference的第三篇

Coding a Struts 2 Action involves several parts:

1. Mapping an action to a class
2. Mapping a result to a view
3. Writing the controller logic in the Action class

写一个Struts2 Action需要有3个步骤

1.映射一个action包的class文件

2.映射一个result对象在view中

3.写控制逻辑在struts.xml中

在之前的教程中我们学习了怎么样去映射 一个 url 比如 hello.action 给一个实际的action 比如HelloWorldAction.java(阐述了action下的execute方法)

Action Mapping
<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" method="execute">
	<result name="success">/HelloWorld.jsp</result>
</action>
以上这个mapping表明了。他接收一个hello的请求(.action已经被过滤),映射到的对象是HelloWorldAction里面的execute方法体返回一个SUCCESS

返回给actionmapping 如果接收了success就跳转到/HelloWorld.jsp那个页面上。


Struts 2 Action Classes

Action class 在mvc模式中扮演了一个控制者的角色,Action Class对用户的请求进行相应,实现业务逻辑(或者交给其他类来完成),返回一个返回值给struts告诉他用什么页面来返回给用户。

Action class 常常继承一个来自于struts2框架的,命名为ActionSupport的基类,ActionSupport这个基类实现了大部分常用的行为(action),eg:execute,input,并且实现了一部分有用的struts2的接口,当你继承他时,你可以重写或者继承他的默认继承方法。

当你测试HelloWorldAction,你会发现的是你继承了ActionSupport并且重写了他的execute方法。

在execute方法中,我们重写了他的原有方法,让他去实现我们想要在响应中做的事。


Method execute of HelloWorldAction

public String execute() throws Exception {
		
	messageStore = new MessageStore() ;
		
	helloCount++;
		
	return SUCCESS;

}
note:需要记住的是execute方法是需要throws Exception的,在后续的教程中,我们将会介绍在action如何去配置struts2来处理抛出的异常。


Processing Form Input In The Action Class

现在我们要把我们在form写入的text传送到后台action并且显示到前台的messageStore中

我们先要修改下我们的HelloWorld.jsp

加入S2标签的form,及textfield和submit

    <s:form action="hello">
    	<s:textfield name="userName" label="Your name" />
    	<br/>
    	<s:submit value="Submit" />
    </s:form>
请求依然是hello。我们要接受的参数是名为userName的参数,所以在action先要getSet方法取得他的值

	private String userName;
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
取得userName值之后,我们要做的就是把它放到前台的messageStore中了。

就是说要加入进execute方法中。

if(userName!=null){
			messageStore.setMessage(messageStore.getMessage()+" "+userName);
		}
这样就可以显示到前台了。赶快试试吧~

Summary

This tutorial introduced you to how to code the Action class so it can process user input on a form or values in a query string parameter. If the form had numerous fields, it would be cumbersome to have a set method that matches up with each form field. So in our next tutorial will cover how to integrate a model class, form fields in the view, and form processing in the Action class.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值