Java中文乱码问题的解决方案

在WebService调用中,经常会发生中文乱码问题,除了服务器的配置(如tomcat的server.xml中设置)

<Connector port="8080" protocol="HTTP/1.1"
	       URIEncoding="UTF-8"
               connectionTimeout="20000"
               redirectPort="8443" />

 

还有一些影响中文乱码的因素。

1.  在web page中设置

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

 当然,设置的位置在head。

2.  如果使用js,可以使用js的encodeURI编码

data:{id:id,name:encodeURI(name)}

 在程序中再使用Decoder.decode来解码

String name = URIDecoder.decoder(name);

3.  使用jquery时,如果是post方法,使用cotent-type

contentType:"application/x-www-form-urlencoded; charset=utf-8"

     get方法则在程序中使用

String dist = new String(source.getBytes("ISO-8859-1"), "UTF-8");

4.   设置response

response.setContentType("text/json");
response.setCharacterEncoding("UTF-8");

5.  字符集转码

String str = new String(sourceStr.getBytes("ISO-8859-1"), "UTF-8");
6.   在APP中增加字符集 filter
public class EncodingFilter extends HttpServlet implements Filter {

	private static final long serialVersionUID = 5505580234404567333L;
	private String encoding = "UTF-8";

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		request.setCharacterEncoding(encoding);
		filterChain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.encoding = filterConfig.getInitParameter("encoding");
	}

	public EncodingFilter() {
		super();
	}

	public void destroy() {
		this.encoding = null;
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
 web.xml
	<filter>
		<filter-name>EncodingFilter</filter-name>
		<filter-class>com.network.filter.EncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>EncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
 7.  Spring mvc中,在produces属性中设置charset为utf-8
 //    查看产品详细信息
    @RequestMapping(value = "/view/{productId}", produces = "application/json; charset=utf-8")
 
 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值