锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
聽聽聽 <filter-name>Set Character Encoding</filter-name>
聽聽聽 <filter-class>com.util.filters.SetCharacterEncodingFilter</filter-class>
聽聽聽 <init-param>
聽聽聽聽聽 <param-name>encoding</param-name>
聽聽聽聽聽 <param-value>UTF-8</param-value>
聽聽聽 </init-param>
聽 </filter>
聽 <filter-mapping>
聽聽聽 <filter-name>Set Character Encoding</filter-name>
聽聽聽 <url-pattern>/*</url-pattern>
聽 </filter-mapping>
SetCharacterEncodingFilter:
package com.util.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SetCharacterEncodingFilter
聽聽聽 implements Filter {
聽 protected String encoding = null;
聽 protected FilterConfig filterConfig = null;
聽 protected boolean ignore = true;
聽 public void destroy() {
聽聽聽 this.encoding = null;
聽聽聽 this.filterConfig = null;
聽 }
聽 public void doFilter(ServletRequest request, ServletResponse response,
聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽聽 FilterChain chain) throws IOException, ServletException {
聽聽聽 // Conditionally select and set the character encoding to be used
聽聽 request.setCharacterEncoding("GBK");
聽聽聽 // Pass control on to the next filter
聽聽聽 chain.doFilter(request, response);
聽 }
聽 public void init(FilterConfig filterConfig) throws ServletException {
聽聽聽 this.filterConfig = filterConfig;
聽聽聽 this.encoding = filterConfig.getInitParameter("encoding");
聽聽聽 String value = filterConfig.getInitParameter("ignore");
聽聽聽 if (value == null) {
聽聽聽聽聽 this.ignore = true;
聽聽聽 }
聽聽聽 else if (value.equalsIgnoreCase("true")) {
聽聽聽聽聽 this.ignore = true;
聽聽聽 }
聽聽聽 else if (value.equalsIgnoreCase("yes")) {
聽聽聽聽聽 this.ignore = true;
聽聽聽 }
聽聽聽 else {
聽聽聽聽聽 this.ignore = false;
聽聽聽 }
聽 }
聽 protected String selectEncoding(ServletRequest request) {
聽聽聽 return (this.encoding);
聽 }
}
2錛庤В鍐矴ET鏂瑰紡鍑虹幇涔辯爜鐨勬柟妗?/p>
tomcat鐨剆erver.xml涓?
<Connector connectionTimeout="20000" maxSpareThreads="75" maxThreads="150" minSpareThreads="25" port="8080" redirectPort="8443" uRIEncoding="UTF-8" useBodyEncodingForURI="true">
</Connector>
娉ㄦ剰鍏朵腑鐨剈seBodyEncodingForURI="true"榪欏彞鏄槸瑙e喅闂鐨勫叧閿紝浣嗙己鐪佹儏鍐典笅娌℃湁錛岃嚜宸卞姞榪涘幓銆?
鐒跺悗鍐嶇敤Filter鏂規瑙e喅 瑙e喅GET鐨勯棶棰?/p>
3.涔辯爜瀛楃杞崲銆
銆銆byte[] bytes = str.getBytes("ISO8859-1");
聽聽聽 String dept=new String(bytes);
AJAX
鍦ㄧ敤XMLHttpRequest鍙戦佽姹傛椂濡傜敤post鏂瑰紡浼犻佹暟鎹?瀹規槗鍑虹幇涓枃涔辯爜闂!
鍦ˋjax涓?榛樿鐨勭紪鐮佹柟寮忔槸UTF-8,鎵浠ュ湪鏈嶅姟鍣ㄧ鐢╮equest.setCharacterEncoding("UTF-8");(瀵逛簬java璦,鍏跺畠璇█鍙兘綾諱技鏂規硶)璁劇疆緙栫爜鍗沖彲瑙e喅澶ч儴浠界殑緙栫爜闂!
聽瀵逛簬鏈嶅姟鍣ㄧ榪斿洖鐨刋ML鏂囦歡鍦ㄧ敤responseXML璇誨彇鏃朵篃瑕佹敞鎰忕紪鐮侀棶棰?
浠ヤ笅鏄紜殑澶勭悊鏂規硶錛?/p>
response.setCharacterEncoding("UTF-8");-----(1)
PrintWriter out=response.getWriter();------(2)
out.println("榪斿洖鍐呭");
濡備笂鎵紺?濡傛灉1銆?鐨勫厛鍚庨『搴忓彂鐢熷彉鍖栧氨浼氫駭鐢熶貢鐮侊紒