Struts2 常量配置

本文介绍Struts2框架中常量的作用及配置方式,包括struts.xml、struts.properties和web.xml三个文件中的配置,并解释了常量覆盖原则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Struts2规定了一些特定的对整个Struts2应用起作用的常量,通过配置这些常量的值,可以改变Struts2框架的一些默认行为。

Struts2可以在三种文件中对常量进行配置:

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

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

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,value

<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就是常量值value

struts.i18n.encoding=GBK
3. web.xml中配置常量

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

<?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...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值