struts2入门(1)------- HelloWorld
1)导入struts2的包:
commons-logging-1.0.4.jar
freemarker-2.3.15.jar
ognl-2.7.3.jar
struts2-core-2.1.8.1.jar
xwork-core-2.1.6.jar
commons-fileupload-1.2.1.jar(struts2.1.6以后须导入的包,不然会出现Unable to load configuration. -
bean - jar:file:/D:/java/tomcat6/webapps/HelloWord/WEB-INF/lib/struts2-core-2.1.8.1.jar!/struts-
default.xml:47:178 )
2)web.XML中添加struts2。
<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>
3)编写struts.xml文件放到src下:
<!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="struts2" extends="struts-default">
<action name="HelloWorld" class="com.HelloWorld">
<result>helloworld.jsp</result>
</action>
</package>
</struts>
4)编写com.HelloWorld类:
public class HelloWorld extends ActionSupport
{
String name ;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String execute() throws Exception
{
name = "*****************" + name;
return SUCCESS;
}
}
5)编写输入用户名的input.jsp页面:
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:form action="HelloWorld">
Name: <s:textfield name="name" />
<s:submit />
</s:form>
6)编写接收用户输入的jsp:helloworld.jsp
<s:property value="name"/>//显示出:*******************+name
注意事项:确保struts.xml的正确:放到src下。如出现There is no Action mapped for action name HelloWorld。则一般为文件配置不正确,
在struts.xml中,如果在package中定义了命名空间,如namespace="/com/action",那么在浏览器中url就必须带package的信息,如
http://localhost:8080/Struts2Demo/com/action/HelloWorld.action
如果没有定义namespace, 则http://localhost:8080/Struts2Demo/com/action/HelloWorld.action 和 http://localhost:8080/Struts2Demo/HelloWorld.action
都可以的