arm-linux

http://armboard.taobao.com/

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
       由于各种原因,Java 应用中有关中文编码的问题总是层出不穷,即使是在 i18n 发展已久的今日,为了能够在 Java 应用中良好地使用中文,程序员们仍然要花费许多额外的力气来调试、设置以解决有关中文编码的问题。针对在 Tomcat 服务器上运行的 Spring 应用,我总结了一些相关的经验,希望能帮助其他人在处理该问题时能少走一些弯路。以下条目纯属个人在开发中摸索出来的经验,并不一定适用于所有情况。在解决中文编码的问题时,也不一定需要将以下所罗列的条目逐一设置,往往只需要结合自己开发中的实际情况修改其中若干项目即可。

1. 修改 $CATALINA_HOME/conf/server.xml。
找到 Connector 的配置,添加 URIEncoding 属性,例如:
<Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1"
           connectionTimeout
="20000"
           redirectPort
="8443" />

2. 修改 $CATALINA_HOME/bin/catalina.sh。
设置 CATALINA_OPTS 参数,如下:
JAVA_OPTS="$JAVA_OPTS "-Djavax.servlet.request.encoding=UTF-8" "-Dfile.encoding=UTF-8""

3. 修改 Web 应用中的 web.xml。
添加过滤器 CharacterEncodingFilter。如下:
<filter>
    
<filter-name>setCharacterEncoding</filter-name>
    
<filter-class>
        org.springframework.web.filter.CharacterEncodingFilter
    
</filter-class>
    
<init-param>
        
<param-name>encoding</param-name>
        
<param-value>UTF-8</param-value>
    
</init-param>
</filter>
<!-- filtered type -->
<filter-mapping>
    
<filter-name>setCharacterEncoding</filter-name>
    
<url-pattern>*.do</url-pattern>
</filter-mapping>

4. 修改 Web 应用中的 app-servlet.xml。
找到 viewResolver bean 的配置,添加 contentType 属性,如下:
<bean id="viewResolver"
    class
="org.springframework.web.servlet.view.InternalResourceViewResolver">
    
<property name="viewClass"
        value
="org.springframework.web.servlet.view.JstlView" />
    
<property name="prefix" value="/" />
    
<property name="suffix" value=".jsp" />
    
<property name="contentType">
        
<value>text/html;charset=UTF-8</value>
    
</property>
</bean>

5. 在 JSP 页面中添加如下一行。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

6. 编译 war 包时需要注意指定编译器的编码。
例如,在 maven 的 pom.xml 中找到 maven-compiler-plugin 插件一节,指定 encoding:
<plugin>
    
<artifactId>maven-compiler-plugin</artifactId>
    
<configuration>
        
<source>1.6</source>
        
<target>1.6</target>
        
<encoding>UTF-8</encoding>
    
</configuration>
</plugin>

7. 在 Controller 中覆盖 handleRequestInternal 方法,指定 response 所采用的字符编码。
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) 
throws Exception {
    response.setCharacterEncoding(
"UTF-8");
    
return super.handleRequestInternal(request, response);
}
 
转自:http://blog.csdn.net/holy_phoenix/archive/2007/10/04/1811147.aspx
posted on 2007-10-08 12:10  arm-linux  阅读(340)  评论(0编辑  收藏  举报