写在前面:其实在一年前,还没有开始写博客的时候就已经学过struts2了,只是当时太蠢,无法理解MVC以及struts2的一些“人性化”的设定,过了一年再反过来看struts2就很明白了。只是在struts2.5里面多了一个机制导致无法像以往一样简单的使用通配符这种方式来对action进行映射或者说是跳转吧。
我们先看2.5以前我的们配置文件是怎么写的:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<!-- name是请求的参数 -->
<!-- class是请求反应的类 -->
<!-- method是处理的方法 -->
<action name="*_*"
class="com.baofeidyz.web.action.{1}Action"
method="{2}">
<result name="login">/WEB-INF/views/login.jsp</result>
<result name="ok">/WEB-INF/views/index.jsp</result>
<result name="fail">/WEB-INF/views/login.jsp</result>
</action>
</package>
</struts>
按照struts2给我们设定的逻辑,就是使用 *
号来表示通配符,那么我们如果使用了*_*
则表示有两个通配符了。那么{1}
与 {2}
代表着两个通配符对应的占位符。
按照我给出的配置文件,当我在浏览器一段访问的URL为User_login.action
(注:我在web.xml文件拦截的是.action*),那么此时{1}
则对应了 User ,{2}
则对应了login
然而,我们发现在struts2.5中 这样做是无法执行的,但是当我们手动把第二个*
号改成 login
,同时把 {2}
改成 login
以后呢,发现又是正常的了。
其实看到这里,大家已经猜到了一些,其实就是struts2不允许你使用通配符来访问非execute方法。其实这个在之前的struts2中已经有一个叫做DMI的action映射方法中有所体现了。DMI是使用 ! 来做区分,但是这种方法呢不安全,如果有心人找到了你的逻辑,然而反复调用一些比较敏感的方法,对于你的程序而言就很危险。同理,如果这里对于method放开要求,也容易出现这种情况。
所以我们需要在struts.xml文件的action节点中添加一行代码
<allowed-methods>login</allowed-methods>
这里如果有多个方法需要使用通配符的话,直接使用逗号隔开即可。
网上看到有人说使用 * 代替这里的login,本人实测是不行的,必须要写全所有的方法(除开execute),没写入的都无法执行。
最后贴出我的整个struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<!-- name是请求的参数 -->
<!-- class是请求反应的类 -->
<!-- method是处理的方法 -->
<action name="*_*"
class="com.baofeidyz.web.action.{1}Action"
method="{2}">
<result name="login">/WEB-INF/views/login.jsp</result>
<result name="ok">/WEB-INF/views/index.jsp</result>
<result name="fail">/WEB-INF/views/login.jsp</result>
<allowed-methods>login,loginDo</allowed-methods>
</action>
</package>
</struts>