今天真是弄了好久,这样简单的例子,却一直在报404错误。搞得头都大了,其间还受一个帖子的影响,该帖子煞有其事的说tomcat6.0不支持struts2,看了心都拔凉拔凉的,幸亏没有信。其实报错,还是因为配置文件有错误,或者配置文件放错位置或者导入的包不对。
遇到问题时,应该多找找自己的原因。
首先,当然是需要导入struts2的jar包,我用的是struts2.2.1,需要的包如下:
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
freemarker-2.3.16.jar
javassist-3.7.ga.jar
ognl-3.0.jar
struts2-core-2.2.1.jar
xwork-core-2.2.1.jar
总共是7个包,这七个jar包,其实有个简单的办法可以获得。如果下了struts的完整包,app中的struts2-blank-2.2.1.war被解压后,她所使用的jar包就是这七个包。
然后,第一步就是写web.xml,web.xml如下:
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
第二步就是写struts,struts.xml和源代码(即action代码)放在一起:
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" namespace="/" extends="struts-default">
<action name="helloworld" class="helloworld">
<result name="success">hello.jsp</result>
</action>
</package>
<!-- Add packages here -->
</struts>
第三步,写action代码:
String message;
String name;
public String getMessage()
{
return this.message;
}
public void setName(String n)
{
this.name=n;
}
public String getName()
{
return this.name;
}
public String execute()
{
message=name+",hello!";
return SUCCESS;
}
}
第四步,就是写name.jsp和hello.jsp