在編程的時候會遇到各類中文亂碼,這裏進行統計以便之後查閱html
一、前端頁面元素中文亂碼前端
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
會出現下面亂碼web
頁面上的元素也就是html內的元素,是中文的會出現亂碼,而從後臺獲取的中文不會出現亂碼。spring
解決方法:頁面上設置編碼方式爲UTF-8編程
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
二、URL傳參、get方式傳參出現中文亂碼,以下數組
出現這種狀況,要先肯定參數在前臺頁面上不是亂碼的,能夠alert()一下,看參數是否亂碼tomcat
解決辦法1:服務器
對於以get方式傳輸的數據,request默認使用ISO8859-1這個字符編碼來接收數據,客戶端以UTF-8的編碼傳輸數據到服務器端,而服務器端的request對象使用的是ISO8859-1這個字符編碼來接收數據,服務器和客戶端溝通的編碼不一致所以纔會產生中文亂碼的。app
解決辦法:在接收到數據後,先獲取request對象以ISO8859-1字符編碼接收到的原始數據的字節數組,而後經過字節數組以指定的編碼構建字符串,解決亂碼問題。框架
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id= request.getParameter("id"); id=new String(name.getBytes("ISO8859-1"), "UTF-8") ; }
解決方法2:
修改tomcat服務器的編碼方式,能夠在server.xml裏面設置
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
設置成紅字部分,可是有時也是不可用的,由於即便這裏設置的是UTF-8可是其餘地方設置成其餘編碼方式會覆蓋掉這個設置,仔細檢查各個地方的編碼。
好比Spring Boot 的application.properties配置文件裏設置成server.tomcat.uri-encoding=GBK就會覆蓋掉tomcat本身的設置,我這裏是打個比方,由於SpringBoot是內置Tomcat服務器的。
解決辦法3:中文參數進行編碼處理
?id="+encodeURI(encodeURI("中文參數"));
後臺:
String name = request.getParameter("name");
String str = URLDecoder.decode(name,"UTF-8");
三、POST方式出現中文亂碼
緣由:由於服務器和客戶端溝通的編碼不一致形成的,所以解決的辦法是:在客戶端和服務器之間設置一個統一的編碼,以後就按照此編碼進行數據的傳輸和接收。
解決方法:因爲客戶端是以UTF-8字符編碼將表單數據傳輸到服務器端的,所以服務器也須要設置以UTF-8字符編碼進行接收
一、後臺代碼
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");//注意要在getParameter以前設置
String id= request.getParameter("id");
}
二、若是使用的是框架的話,能夠統一設置字符過濾器,這裏以 SpringMVC爲例:
<filter> <description>字符集過濾器</description> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <description>字符集編碼</description> <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>
三、SpringBoot 這樣設置: 建立一個類繼承WebMvcConfigurerAdapter
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter { @Bean public HttpMessageConverter<String> responseBodyConverter() { StringHttpMessageConverter converter = new StringHttpMessageConverter( Charset.forName("UTF-8")); return converter; } @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); converters.add(responseBodyConverter()); } @Override public void configureContentNegotiation( ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } }
四、使用註解@RequestBody 致使接收的中文參數亂碼,能夠參考個人這篇博客(比較詳細)http://www.javashuo.com/article/p-rxoskkrr-bz.html