Struts2的action采用了低侵入式,不要求实现任何类,也不需要去实现任何接口,Action类完全是一个普通的POJO类,有很好的复用性。
Struts2通常直接使用Action来封装HTTP请求参数,因此我们需要为Action中的属性添加setter()和getter()方法。并添加一个execute()方法。
其次,可以实现Action接口以规范Action类开发。
最常用的还是通过继承ActionSupport类来简化Action开发。
Struts2的Action类中就可以不使用Servlet的API来实现功能,但在控制层action中想要使用Servlet的API时,第一种方法使用ServletActionContext类即可。这样的方式也叫紧耦合方式。不推荐使用。
ServletActionContext.getRequest().setAttribute("list", this.getService().findAll());
第二种使用方法使用ActionContext类对request、session、application对象进行操作。
Map request = (Map) ActionContext.getContext().get("request");
request.put("list", this.getService().findAll());
- 使用ActionContext类访问Servlet API;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String userName;
private String password;
@Override
public String execute() throws Exception {
ActionContext ac = ActionContext.getContext();
if ("zhangsan".equals(userName) && "123456".equals(password)) {
ac.put("success", "登录成功");
return Action.SUCCESS;
} else {
ac.put("error", "用户名或密码错误");
return Action.ERROR;
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2、实现xxxAware接口直接访问Servlet API
为了使struts2能够直接访问到Servlet API实例,struts2还提供了如下接口。
- ServletContextAware 实现该接口的Action,可以直接访问web应用中的ServletContext;
- ServletRequestAware 实现该接口的Action,可以直接访问用户请求的HttpServletRequest实例;
- ServletResponseAware 实现该接口的Action,可以直接访问用户请求的HttpServletResponse实例;
3、借助ServletActionContext类直接访问Servlet API
4、配置action
当我们提供了Action的实现类后,需要在struts2.xml中去配置Action。Struts2是用包来管理action的,所以action的定义是在package元素下定义的。
action充当MVC中的C(controller),当Action处理完有用的请求后,它需要将一个视图资源返回给用户,因此在配置action的时候需要建立逻辑视图与物理视图的映射。