3、使用WebWork2实现Web表示层
(1)更改Servlet控制器:ww2/WEB-INF/web.xml
<?xml version="1.0" ?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.atlassian.xwork.ext.ResolverSetupServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>webwork</servlet-name>
<servlet-class>com.opensymphony.webwork.dispatcher.ServletDispatcher</servlet-class>
</servlet>
<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>com.opensymphony.webwork.views.velocity.WebWorkVelocityServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>webwork</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<taglib>
<taglib-uri>webwork</taglib-uri>
<taglib-location>/WEB-INF/webwork.tld</taglib-location>
</taglib>
</web-app>
l 使用WebWork2的ServletDispatcher来控制所有的请求,并映射到*.action
l 为了能使用Velocity,要增加WebWorkVelocityServlet控制器,并映射到*.vm
l 为了能在JSP中使用WebWork2标记,需要定义WebWork2的标记库;并将webwork.tld拷贝到ww2/WEB-INF目录下
(2)创建控制器:SpringappAction
package web;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import bus.ProductManager;
import com.opensymphony.xwork.ActionSupport;
public class SpringappAction extends ActionSupport {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private ProductManager prodMan;
private String now;
private List products;
public String execute() throws Exception {
now = (new java.util.Date()).toString();
logger.info(“returning hello view with “ + now);
products = prodMan.getProducts();
return SUCCESS;
}
public ProductManager getProdMan() {
return prodMan;
}
public void setProdMan(ProductManager prodMan) {
this.prodMan = prodMan;
}
public String getNow() {
return now;
}
public void setNow(String now) {
this.now = now;
}
public List getProducts() {
return products;
}
public void setProducts(List products) {
this.products = products;
}
}
l 这里使用SpringappAction来实现SpringappController相同的功能
l SpringappAction扩展ActionSupport(这是Action接口的缺省实现)并重写execute()方法
l execute()方法是Action的执行逻辑单元,通过return的返回标志,显示指定的视图页面
l 有以下一些返回标志可以使用:
Ø SUCCESS:Action执行成功,显示结果视图
Ø NONE:Action执行成功,不需要显示视图
Ø ERROR:Action执行失败,显示错误视图
Ø INPUT:需要更多的输入使Action执行成功;典型的例子就是表单处理,当用户输入无效时,重新显示表单视图
Ø LOGIN:用户没有登录以致Action不能执行,显示登录视图
l WebWork2没有Spring MVC Framework的Model机制,而是使用其属性来保存Model数据,在结果视图中可以通过这些属性来获得数据