有句名言,叫做10000小时成为某一个领域的专家。姑且不辩论这句话是否正确,让我们到达10000小时的时候再回头来看吧。
Hour 32
Struts2 Action
1 将action 映射到 action class
2 将action class 返回的结果 映射到一个 view
3 写action class 的控制逻辑
所以这里关键点是action class
Action Class
public class HelloWorldAction extends ActionSupport { private static final long serialVersionUID = 1L; private static int helloCount = 0; public int getHelloCount() { return helloCount; } public void setHelloCount(int helloCount) { HelloWorldAction.helloCount = helloCount; } private MessageStore messageStore; public String execute() throws Exception { messageStore = new MessageStore(); helloCount++; return SUCCESS; }
这里一般直接继承ActionSupport 基类。
然后override 默认的execute 方法。
注意这里可能会抛出Exception 的异常,关于异常将在后面讲解。
只要在Action Class 里增加符合约定的属性和字段,Struts2 将自动赋值到该属性。
package org.apache.struts.helloworld.action; import org.apache.struts.helloworld.model.MessageStore; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { private static final long serialVersionUID = 1L; private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } private static int helloCount = 0; public int getHelloCount() { return helloCount; } public void setHelloCount(int helloCount) { HelloWorldAction.helloCount = helloCount; } private MessageStore messageStore; public String execute() throws Exception { messageStore = new MessageStore(); helloCount++; if (userName != null) { messageStore.setMessage(messageStore.getMessage() + " " + userName); } return SUCCESS; } public MessageStore getMessageStore() { return messageStore; } public void setMessageStore(MessageStore messageStore) { this.messageStore = messageStore; } }
随着方法和属性的增多,这个顺序有点乱。
eclipse 有各种字段,方法,自动分类排序功能么?
这个小时就暂时到这里为止,明天继续。
综合以上这些部分,解决我们这个weather 项目应该不成问题了。
不过不得不说,这个问题写得挺nice 的,适合我这样的初学者。
http://struts.apache.org/release/2.1.x/docs/processing-forms.html