Action是什么
在Struts2中,一个Action类代表一次请求或调用,每个请求的动作都对应于一个相应的Action类,一个Action类是一个独立的工作单元。也就是,用户的每次请求,都会转到一个相应的Action类里面,由这个Action类来进行处理,因此一个Action类代表了用户的一次请求或调用。简单来说,Action就是用来处理一次用户请求的对象。
Action能干什么
public class HelloWorldAction implements Action { private String account; private String password; public String execute() throws Exception { System.out.println("用户输入的参数为===" + "account=" + account + ",password=" + password); return "toWelcome"; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
根据上面的Action实现,在Struts2里面,Action充当着MVC中模型的角色,也就是Action既封装了业务数据,又要处理业务功能。在实际的JavaEE开发中,逻辑部分会放到逻辑层去实现,这就变成Action只是去调用逻辑层来进行业务逻辑的处理,并不是真的在Action里面去实现业务逻辑的处理。上面Action的属性和属性对应的getter/setter方法,就是用来接收用户请求的数据,并把这些数据封装在Action中,在后续处理中可以访问这些数据。上面Action的实现中的execute方法的实现,你会发现execute方法里面实现的功能,正是前面学习的MVC的控制器部分的功能。从另外一个角度说,Struts2的Action也充当着MVC中控制器的角色。