3、Actions和Results
Actions是基本执行单元,在WebWork配置中注册,用来响应特定的请求。在MVC中,Actions是控制部分。下面是在WebWork中创建Action的基本步骤:
l 创建调用Action的JSP页;
l 创建Action类;
l 创建处理Action返回结果的JSP页;
l 在xwork.xml中注册Action;
(1)Hello WebWorld的例子
l xwork.xml文件内容如下:
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-1.0.dtd">
<xwork>
<!-- Include webwork defaults (from WebWork-2.1 JAR). -->
<include file="webwork-default.xml" />
<!-- Configuration for the default package. -->
<package name="default" extends="webwork-default">
<!-- Default interceptor stack. -->
<default-interceptor-ref name="defaultStack" />
<!-- Action: Lesson 03: HelloWebWorldAction. -->
<action name="helloWebWorld" class="lesson03.HelloWebWorldAction">
<result name="success" type="dispatcher">ex01-success.jsp</result>
</action>
</package>
</xwork>
l 调用Action的页面ex01-index.jsp:
<html>
<head>
<title>WebWork Tutorial - Lesson 3 - Example 1</title>
</head>
<body>
<p>Click the button below to activate HelloWebWorldAction.</p>
<form action="helloWebWorld.action" method="post">
<p><input type="submit" value="Hello!" /></p>
</form>
</body>
</html>
当点击页面的按钮时,浏览器提交表单数据给helloWebWorld.action;既然URL匹配映射*.action,Servlet容器激活WebWork的ServletDispatcher;ServletDispatcher读取xwork.xml,查找名为helloWebWorld的Action,如果找到就创建Action类的一个新实例,调用execute()方法
l Action类:HelloWebWorldAction.java
package lesson03;
import com.opensymphony.xwork.ActionSupport;
public class HelloWebWorldAction extends ActionSupport {
String hello;
public String getHello() {
return hello;
}
public String execute() throws Exception {
hello = "Hello, WebWorld!";
return SUCCESS;
}
}
Action类继承com.opensymphony.xwork.ActionSupport,并实现execute()方法;execute()方法的返回值SUCCESS和success(<result>的name属性值)对应;ServletDispatcher查找名字相匹配的result,转移到指定的JSP页ex01-success.jsp
l 结果显示JSP页ex01-success.jsp:
<%@ taglib uri="webwork" prefix="ww" %>
<html>
<head>
<title>WebWork Tutorial - Lesson 3 - Example 1</title>
</head>
<body>
<ww:property value="hello" />
</body>
</html>
<ww:property value="hello" />在Action类中查找hello属性,调用hello属性的setter方法获得属性值(在execute()中已经设置),显示Hello, WebWorld!
(2)向Action提供数据的例子
xwork.xml:
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-1.0.dtd">
<xwork>
<!-- Include webwork defaults (from WebWork-2.1 JAR). -->
<include file="webwork-default.xml" />
<!-- Configuration for the default package. -->
<package name="default" extends="webwork-default">
<!-- Default interceptor stack. -->
<default-interceptor-ref name="defaultStack" />
<!-- Action: Lesson 03: HelloAction. -->
<action name="hello" class="lesson03.HelloAction">
<result name="error" type="dispatcher">ex02-index.jsp</result>
<result name="success" type="dispatcher">ex02-success.jsp</result>
</action>