J2EE项目中使用Spring 4及.properties文件UTF-8编码问题

本文详细介绍了如何在新建的J2EE Web工程中整合Spring4,包括配置Spring环境、加载配置文件以及在Servlet中访问配置信息的过程。

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

Spring framework可以到此处下载:http://maxwoods.ctfile.com/u/758954/11098882,这里使用Spring 4。

新建一个j2ee的web工程,将压缩包中对应的jar包放到WEB工程的lib子目录中,如/WebContent/WEB-INF/lib。

修改web.xml文件,在web-app节点加入对应配置:

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
  			classpath:spring/*.xml
  	</param-value>
  </context-param>

spring为源码目录中放置 spring的配置文件的子目录。 


Spring的配置文件中,可以通过<context:property-placeholder>标记来加载.properties配置文件,并通过file-encoding属性来指定字符编码。

还可以通过org.springframework.beans.factory.config.PropertyPlaceholderConfigurer来加载属性文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-4.1.xsd">
	
   <context:property-placeholder location="classpath*:spring.properties" file-encoding="UTF-8"/>
    	
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	    <property  name="fileEncoding" value="UTF-8"/>       
        <property name="locations">
            <list>
                <value>classpath*:spring.properties</value>
            </list>
        </property>
    </bean>    
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">	     
		<property name="properties" ref="configProperties"/> 
 		 
	    	<property name="locations"> 
	    		<list>
	     			<value>classpath:spring.properties</value> 
	    		</list> 
	   		</property>
	    
	</bean> 
</beans>

在Servlet中,可以通过以下代码访问配置文件中的Properties:

ApplicationContext context= WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
Properties property=(Properties)context.getBean("configProperties");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

螃蟹就是横着走

感谢您的支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值