Struts2学习笔记:DMI,多个配置文件,默认Action,后缀

动态方法调用有三种方法:

1.同一Action多次映射,每个action标签的method对应要调用的方法。

当要调用的方法多了就会增加struts.xml文件的复杂性。

2.struts.DynamicMethodInvocation=true (struts.properties文件)

或<constant name="struts.enableDynamicMethodInvocation" value=true></constant(struts.xml文件)

struts.properties文件优先级更高

因为常量可以在下面多个配置文件中进行定义,所以我们需要了解struts2加载常量的搜索顺序: 
struts-default.xml 
struts-plugin.xml 
struts.xml 
struts.properties 
web.xml 

如果在在多个文件中配置了同一个常量,则后一个文件中配置的常量值会覆盖前面文件中配置的常量值。

这个顺序是在多个文件中配置了同一个常量的前提下,比如struts.action.extension这个常量在struts.xml中有而struts.properties没有,那么struts.xml仍会覆盖默认的值aciton,,

3.通配符(官方推荐的方法)

案例:

<action name="*_*" class="action.{1}Action" method="{2}">
    <result name="success">/{2}_{1}.jsp</result>
</action>

访问http://127.0.0.1:8080/Ch12/User_add.action

调用action.UserAction.add(),若业务处理返回success,会跳转到add_User.jsp

指定多个配置文件:


我们不可能将所有的内容写在一个struts.xml文件中,特别是在比较大的应用中更是如此,为便于管理,就可以根据功能的不同写在不同的.xml文件中,然后将这些.xml文件包含在struts.xml文件中。

1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE struts PUBLIC
3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4     "http://struts.apache.org/dtds/struts-2.0.dtd">
5 <struts>
6     <include file="hello.xml"></include>
7     <constant name="struts.i18n.encoding" value="UTF-8"></constant>
8 </struts>

第7行指定了编码,防止多个xml文件的编码格式不同导致乱码。

hello.xml的内容是实际要配置的action。

默认Action:

通常用于显示404页面

1 <package name="testStruts" extends="struts-default" namespace="/aaa">
2     <action name="notFound">
3         <result>/404.jsp</result>
4     </action>
5 </package> 

如果action标签没有指定class属性,默认会不经业务逻辑直接跳转到result。

注意:如果action的name用了通配符,首先会去和通配符\匹配,如果没有才会寻找默认的Action

Action后缀:

StrutsPrepareAndExecuteFilter是Struts2框架的核心控制器,它负责拦截由<url-pattern>/*</url-pattern>指定的所有用户请求,当用户请求到达时,该Filter会过滤用户的请求。默认情况下,如果用户请求的路径不带后缀或者后缀以.action结尾,这时请求将被转入Struts 2框架处理,否则Struts 2框架将略过该请求的处理。

* 根据配置文件:struts2-core-x.x.x.jar包下的org.apache.struts2/default.properties文件定义的常量决定
    struts.action.extension=action,,

* 默认处理的后缀是可以通过常量”struts.action.extension“进行修改的,如下面配置Struts 2只处理以.do为后缀的请求路径:

<struts>

    <constant name="struts.action.extension" value="do"/>

</struts>

* 如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。如:

    <constant name="struts.action.extension" value="do,go"/>

也可在struts.properties文件中配置

也可在web.xml中配置

<filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      <init-param>
          <param-name>struts.action.extension</param-value>
          <param-value>do,action,,</param-value>
      </init-param>
  </filter>

参考:https://www.cnblogs.com/pwc1996/p/4839162.html


另外,result的name属性区分大小写,默认是success。如果多个result的name相同(包含多个未指定的情况),那么将跳转到最后一个result的页面

猜你喜欢

转载自www.cnblogs.com/wincent98/p/10040755.html
今日推荐