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

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

 

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

1.  在web page中设置

 当然,设置的位置在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
	
		EncodingFilter
		com.network.filter.EncodingFilter
		
			encoding
			UTF-8
		
	
	
		EncodingFilter
		/*
	
 7.  Spring mvc中,在produces属性中设置charset为utf-8
 //    查看产品详细信息
    @RequestMapping(value = "/view/{productId}", produces = "application/json; charset=utf-8")
 
 

 

 

 

你可能感兴趣的:(basic,of,java)