Struts2 常量配置

Struts2规定了一些特定的对整个Struts2应用起做用的常量,经过配置这些常量的值,能够改变Struts2框架的一些默认行为。

Struts2能够在三种文件中对常量进行配置:html

  • struts.xml
  • struts.properties
  • web.xml

在不一样配置文件中配置相同常量,会出现覆盖的状况:后一个覆盖前一个配置文件中的常量值。例如,在struts.xml中配置一个常量I,在web.xml中也配置一样的常量I,则web.xml中的常量I会覆盖struts.xml中的常量I。java

struts中的部分常量

属性 说明
struts.locale 默认是en\_US,中文环境下为zh\_CN
struts.i18n.encoding 指定默认编码集,默认值UTF-8
struts.action.extension 指定须要Struts2处理的请求后缀,默认值是action,,
struts.devMode 指定Struts2是否使用开发模式,默认值false,开发时常设为true
struts.custom.i18n.resources 指定struts2所须要的国际化资源文件,用英文逗号隔开

1. struts.xml中配置常量

使用<constant>标签配置,属性有name,valueweb

<struts>
    
    <constant name="struts.i18n.encoding" value="UTF-8"></constant>
    
    <constant name="struts.action.extension" value="action,,"></constant>
    
    <constant name="struts.devMode" value="true"></constant>
    ...省略
</struts>

2. struts.properties中配置常量

该文件包含了系列的键值对key=value的形式,每一个key就是一个Struts2常量名name,对应的value就是常量值valueapache

struts.i18n.encoding=GBK

3. web.xml中配置常量

在配置Struts2的核心Filter时,经过<init-param>子元素配置常量,其中<param-name>元素指明常量名name,<param-value>元素指明常量值value。app

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>struts2_4</display-name>
  
  <filter>
      <filter-name>struts2</filter-name>
      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      <init-param>
          <param-name>struts.i18n.encoding</param-name>
          <param-value>GBK</param-value>
      </init-param>
      <init-param>
          <param-name>struts.devMode</param-name>
          <param-value>true</param-value>
      </init-param>
  </filter>
  <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.xml中配置常量,而不是在struts.properties和web.xml中配置。之因此保留struts.properties文件定义Struts2属性的方式,主要是为了保持与WebWork的向后兼容性。在实际开发中不推荐在web.xml中配置常量,由于这种配置会增长web.xml文件的内容量,下降可读性。

End...框架

相关文章
相关标签/搜索