前两天自己搭建SSH过程中,当我在页面上写了一个form表单提交时,系统报了如下错误:
There is no Action mapped for namespace / and action name saveUser. - [unknown location]
当时,我一直以为是因为我页面action写的有问题,才会报这个错,仔细检查了一下页面:
<span style="color:#ff0000;"><form name="fm" action="saveUser" method="post"></span>
<table>
<tr>
<td>
用户名:
</td>
<td>
<input name="user.userName" type="text" />
</td>
<td>
昵称:
</td>
<td>
<input name="user.nickName" type="text" />
</td>
</tr>
<tr>
<td>
密码:
</td>
<td>
<input name="user.password" type="password" />
</td>
<td>
邮箱:
</td>
<td>
<input name="user.email" type="text" />
</td>
</tr>
<tr>
<td>
性别:
</td>
<td>
<input name="user.sex" type="radio" value="1" />男
<input name="user.sex" type="radio" value="0" />女
</td>
</tr>
<tr>
<td>
生日:
</td>
<td>
<input name="user.birth" type="text" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="保存" />
<input type="button" value="取消" οnclick="javascript:void(0);" />
</td>
</tr>
</table>
</form>
struts.xml文件中:
<package name="user" namespace="/" extends="struts-default">
<action name="saveUser" class="userAction" method="save">
<result name="save_user">/webJsp/success.jsp</result>
</action>
</package>
web.xml文件中:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
发现都没有问题,然后想到,因为我这个SSH是参考当时公司项目搭建的,我把struts.xml文件放在里src目录下的一个struts下的子包中,然后想到这块可能会有点问题(也是在同学的提醒下),后面我把struts.xml文件单独拿出来放在src目录下,问题解决:
但是,我想,难道就办法访问,source下面,struts包中的struts.xml文件吗?因为如果是做项目的话,一般大家的struts配置文件都是一人一个的。于是,又搜了下struts.xml路径,得到的结果是肯定可以访问的,我们只需在web.xml中配置如下信息(红色部分):
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<span style="color:#ff0000;"><init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,/source/struts/struts.xml</param-value>
</init-param></span>
</filter>
因为我的struts配置文件是放在source包下的struts子包中的,而当项目部署完以后,strus2默认加载的是web-inf下classes下的struts.xml文件,这就是为什么一开始会报“no Action mapped”错误了,当时我还以为是名字啥的写的有问题,其实根本原因是因为,struts2根本就没有加载到struts.xml配置文件,所以会报出这个错误。而我将struts配置文件放在source下时,部署完以后,struts.xml的位置是在web-inf/classes/source/struts目录下的,所以<param-value>中与之对应就可以啦!
还要注意的是如果配置了<param-name>config</param-name>参数,那么struts-defual.xml等加载文件也许要放置进来,否则将不能自动加载而报错,还有struts-plugin.xml文件,也许要放在这儿,因为struts2,2.1.6版本中,有struts-spring-plugin-2.1.6.jar(如果使用spring集成的话)有这个struts-plugin.xml文件,另外,json-plugin-0.34.jar(如过struts需要json支持)中也有这个文件。
当然,其实我们平常项目中一般都是讲struts.xml配置文件直接放在src目录下,然后其他配置文件放在同一包下,再在struts.xml文件中include这些配置文件就行了,这样struts2默认就加载了所以的配置文件。