三、控制器Action
两个框架的控制器在默认情况下都是线程安全的,而且都不依赖于具体的类。EasyJWeb默认的处理器实现要求Actionn必须实现IWebAction接口,而Struts2可以不需要。如下:
EasyJWeb中的Action
public class HelloAction implements IWebAction...{
public Page execute(WebForm form, Module module) throws Exception ...{
form.addResult("msg", "您好,这是EasyJWeb的第一个程序!");
form.addResult("date", new Date());
return new Page("/hello/index.html");
}
}
public Page execute(WebForm form, Module module) throws Exception ...{
form.addResult("msg", "您好,这是EasyJWeb的第一个程序!");
form.addResult("date", new Date());
return new Page("/hello/index.html");
}
}
Struts2中的Action
public class HelloAction ...{
public Page execute() throws Exception ...{
return "success";
}
}
public Page execute() throws Exception ...{
return "success";
}
}
当然,这个祼体Action基本上没任何作为,真正的Struts2版本的HelloAction可以写成如下:
public class HelloAction implements ServletRequestAware ...{
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) ...{
this.request = request;
}
public Page execute() throws Exception ...{
request.setAttribute("msg", "您好,这是EasyJWeb的第一个程序!");
request.setAttribute ("date", new Date());
return Action.SUCCESS;
}
}
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) ...{
this.request = request;
}
public Page execute() throws Exception ...{
request.setAttribute("msg", "您好,这是EasyJWeb的第一个程序!");
request.setAttribute ("date", new Date());
return Action.SUCCESS;
}
}
另外,还需要在struts2的配置文件中增加大致如下的配置来指明这个success字符对应的文件路径:
<action name="HelloWorld" class="tutorial.HelloAction">
<result>/HelloWorld.jsp</result>
</action>
<result>/HelloWorld.jsp</result>
</action>
但实际应用中,EasyJWeb的Action大多数都直接继承AbstractPageCmdAction,因为这个基础控制器提供了很多非常强大的功能,比如按惯例查找页面、灵活页面跳转及视图切换,动态特性的命令方法。同样为了使用Struts2中的很多功能,比如拦截器、依赖注入等都需要Action实现指定的接口,更多的时候直接继承ActionSuport类。
也就是说,一个半祼或全祼的Action在实际应用中很少用到。