在編程的時候會遇到各種中文亂碼,這里進行統計以便以后查閱
1、前端頁面元素中文亂碼
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
會出現下面亂碼
頁面上的元素也就是html內的元素,是中文的會出現亂碼,而從后台獲取的中文不會出現亂碼。
解決方法:頁面上設置編碼方式為UTF-8
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
2、URL傳參、get方式傳參出現中文亂碼,如下
出現這種情況,要先確定參數在前台頁面上不是亂碼的,可以alert()一下,看參數是否亂碼
解決辦法1:
對於以get方式傳輸的數據,request默認使用ISO8859-1這個字符編碼來接收數據,客戶端以UTF-8的編碼傳輸數據到服務器端,而服務器端的request對象使用的是ISO8859-1這個字符編碼來接收數據,服務器和客戶端溝通的編碼不一致因此才會產生中文亂碼的。
解決辦法:在接收到數據后,先獲取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");
3、POST方式出現中文亂碼
原因:因為服務器和客戶端溝通的編碼不一致造成的,因此解決的辦法是:在客戶端和服務器之間設置一個統一的編碼,之后就按照此編碼進行數據的傳輸和接收。
解決方法:由於客戶端是以UTF-8字符編碼將表單數據傳輸到服務器端的,因此服務器也需要設置以UTF-8字符編碼進行接收
1、后台代碼
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");//注意要在getParameter之前設置
String id= request.getParameter("id");
}
2、如果使用的是框架的話,可以統一設置字符過濾器,這里以 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>
3、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); } }
4、使用注解@RequestBody 導致接收的中文參數亂碼,可以參考我的這篇博客(比較詳細)https://www.cnblogs.com/lwx521/p/9855891.html