如今將常見的亂碼問題分爲JSP頁面顯示中文亂碼、表單提交亂碼兩類。 javascript
1)JSP頁面中顯示中文亂碼 html
在JSP文件中使用page命令指定響應結果的MIME類型,如<%@ page language="java" contentType="text/html;charset=gb2312" %> java
2)表單提交亂碼 web
表單提交時(post和Get方法),使用request.getParameter方法獲得亂碼,這是由於tomcat處理提交的參數時默認的是iso-8859-1,表單提交get和post處理亂碼問題不一樣,下面分別說明。
(1)POST處理
對post提交的表單經過編寫一個過濾器的方法來解決,過濾器在用戶提交的數據被處理以前被調用,能夠在這裏改變參數的編碼方式,過濾器的代碼以下: tomcat
- package example.util;
-
- 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;
-
- 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,
- <strong><span style="color: #ff0000;"> FilterChain chain) throws IOException, ServletException {
-
- if (ignore || (request.getCharacterEncoding() == null)) {
- String encoding = selectEncoding(request);
- if (encoding != null) {
- request.setCharacterEncoding(encoding);
- }
- }</span>
- </strong>
- // 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);
-
- }
-
- }
文中紅色的代碼即爲處理亂碼的代碼。
web.xml文件加入過濾器 app
- <filter>
- <filter-name>Encoding</filter-name>
- <filter-class>
- example.util.SetCharacterEncodingFilter
- </filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>gbk</param-value>
- <!--gbk或者gb2312或者utf-8-->
- </init-param>
- <init-param>
- <param-name>ignore</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>Encoding</filter-name>
- <servlet-name>/*</servlet-name>
- </filter-mapping>
(2) Get方法的處理
tomcat對post和get的處理方法不同,因此過濾器不能解決get的亂碼問題,它須要在其餘地方設置。
打開<tomcat_home>\conf目錄下server.xml文件,找到對8080端口進行服務的Connector組件的設置部分,給這個組件添加一個屬性:URIEncoding="GBK"。修改後的Connector設置爲:
post
- <Connector port="8080" maxHttpHeaderSize="8192"
- maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
- enableLookups="false" redirectPort="8443" acceptCount="100"
- connectionTimeout="20000" disableUploadTimeout="true" <span style="color: #ff0000;">URIEncoding="GBK"</span> />
* 注意修改後從新啓動tomcat才能起做用。 this