首先,看一个struts.xml的配置:
<package name="default" namespace="" extends="struts-default">
<action name="HelloWorld" class="junit.LoginAction" method="display">
</action>
<action name="validateTest" class="test.ValidateTest">
<result name="input">/strutsvalidate/form.jsp</result>
</action>
</package>
<package name="second" namespace="/patha/path1b" >
<action name="HelloWorld" class="junit.UserAction" method="display"></action>
</package>
namespace决定了action的访问路径,默认为”“,可以接受所有路径的action;
然后,我们普及下url常识:
action=”url” 和 action=”./url” 都表示当前路径
action=”../” 表示上级路径
接着,了解url的两个书写方式:以“/”开头与不以“/”开头
1.不以“/”开头的url
html的form的action属性会以当前html文件路径+action的url路径
localhost:8080/test/strutsvalidate目录下的form.jsp文件中有form标签如下:
<form action="strutsvalidate/NewFile.jsp" method="post">
该form提交后url为:
http://localhost:8080/test/strutsvalidate/strutsvalidate/NewFile.jsp
struts2中的form标签也一样,action属性会以当前html文件路径+url路径发送请求
localhost:8080/test/strutsvalidate目录下的form.jsp文件中有s:form标签如下:
<s:form action="strutsvalidate/NewFile.jsp" method="post">
同样该form提交后的url也为:
http://localhost:8080/test/strutsvalidate/strutsvalidate/NewFile.jsp
总结为:如果url路径不以“/”开头的话,html的form与struts的form标签都是以当前html文件路径+action属性url路径,拼接后发送请求
2.以“/”开头的的url
当html的form表单的action=”/url”(以/开头的url地址)时,其会从http://127.0.0.1:8080 + action的url,没有附加项目的上下文(context),就是tomcat安装目录下wepapps/context(具体是你工程名字)这个文件夹名字
localhost:8080/test/strutsvalidate目录下的form.jsp文件中有form标签如下:
<form action="/strutsvalidate/NewFile.jsp" method="post">
该form提交后的url为:
http://localhost:8080/strutsvalidate/NewFile.jsp
所以使用html的form标签时我们要自己在action的url中加上/项目名/文件路径
action=”/test/strutsvalidate/NewFile.jsp”
struts2的form标签就帮我们做了优化封装,他会自动为我们在htpp://127.0.0.1:8080/后面加上项目的上下文,再附加action后的url,而这也是我们开发时想要的本意
localhost:8080/test/strutsvalidate目录下的form.jsp文件中有form标签如下:
<s:form action="/strutsvalidate/NewFile.jsp" method="post">
该form提交后的url为:
http://localhost:8080/test/strutsvalidate/NewFile.jsp
最后,回到上面的struts.xml定义的两个package,如果我要访问的是namespace=”/patha/path1b“的工作空间中的HelloWorld之Action,html的form与struts2的s:form标签的访问就分别为:
<form action="/test/patha/path1b/HelloWorld.action">
与
<s:form action="/patha/path1b/HelloWorld.action">
url一定以”/“开头;