学习笔记01
时间:2010-06-09 来源:hkebao
学习笔记01
时间:2010-6-9
一、编写helloworld程序
配置环境定义所需要的JAR包
commons-fileupload-1.1.1
commons-io-1.0
commons-logging-1.0.4
freemarker-2.3.8
ognl-2.6.11
struts2-core-2.0.11.1
xwork-2.0.4
操作步骤:
步骤一:编写sayHello.jsp页面
<%@ taglib prefix="s" uri="/struts-tags" %>
引用标签。这个正是我想要的东东/
<s:form action="HelloWorld">
Name:<s:textfield name="name" />
<s:submit />
</s:form>
构造表单!提交到的Action为HelloWorld
步骤二:编写ActionServlet
package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute() {
name = "Hello," + name + "!";
return SUCCESS;
}
}
默认Action处理单元为execute方法。
步骤三:配置Action与XML之间的映射。定义structs.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml"/>
<package name="tutorial" extends="struts-default">
<action name="HelloWorld" class="tutorial.HelloWorld">
<result>HelloWorld.jsp</result>
</action>
</package>
</struts>
非常明确地定义了Action的信息!
步骤四:编写HelloWorld.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:property value="name"/>
因为我们的ActionServlets里面的定义的正是其属性值!
步骤五:编写web配置文件添加过滤器
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
非常简单:
Structs相当于是一个过滤器。将请求丢给它之后依据XML与ACTION之间的映射配置。丢给具体的一个ACTION进行处理请求。
请求处理完之后如何进行处理!
注意对每一个Action要编写其相应的单元测试出来!
package tutorial;
import com.opensymphony.xwork2.ActionSupport;
import junit.framework.TestCase;
public class HelloWorldTest extends TestCase {
public void testExecute() {
HelloWorld hello = new HelloWorld();
hello.setName("World");
String result = hello.execute();
assertTrue("Expected a success result!", ActionSupport.SUCCESS.equals(result));
final String msg = "Hello, World!";
assertTrue("Expected the default message!", msg.equals(hello.getName()));
}
}