写Action的三种方法
Action类似于servlet,在用户对浏览器输入url访问的时候充当控制器的角色。它在访问时产生,执行execute()之后就销毁了。
写Action是代理事务,它实现的三种方式是: (1)POJO类
(2)继承ActionSupport类
(3)实现Action接口
POJO类
public class ActionPrint { public String execute(){ System.out.println("ActionPrint execute!"); return "success"; } }
继承ActionSupport类
import com.opensymphony.xwork2.ActionSupport; public class ActionInputCheck extends ActionSupport{ private int a; private double b; private char c; private String d; public int getA() { return a; } public void setA(int a) { this.a = a; } public double getB() { return b; } public void setB(double b) { this.b = b; } public char getC() { return c; } public void setC(char c) { this.c = c; } public String getD() { return d; } public void setD(String d) { this.d = d; } public String execute(){ return SUCCESS; } public void validate(){ if(a<0) this.addActionError("d不能小于0"); } }
实现Action接口
import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ModelDriven; import Beans.User; public class MDriven implements Action,ModelDriven<User>{ private User user=new User(); public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public User getModel() { // TODO Auto-generated method stub return user; } @Override public String execute() throws Exception { ActionContext context=ActionContext.getContext(); context.getSession().put("username", user.getUsername()); return SUCCESS; } }
ModelDriven接口是让javabean的实现和Action分离,Action只用扮演好控制器的角色就好,javabean是在Model层的东东,这样比较符合MVC的设计模式。
写了Action之后相应加上struts.xml的配置
</action> <action name="InputCheck" class="StrutsFund.ActionInputCheck"> <result name="success">/output.jsp</result> </action> <action name="MDriven" class="StrutsFund.MDriven"> <result name="success">/login_success.jsp</result> </action> <action name="print" class="StrutsFund.ActionPrint"> <result name="success">/index.jsp</result> </action>
访问的时候就在网址栏中输入:http://localhost:8080/项目名/ActionName
struts.properties配置文件
该文件定义了struts2框架的大量属性。只要将该文件放在web应用的classes下,struts2框架就会自动加载。