Java WEB應用中文亂碼處理總結

來源:互聯網
上載者:User

標籤:中文亂碼   編碼   tomcat   字元集設定   get與post亂碼處理   

處理伺服器亂碼的四種方式
1.jsp編碼設定錯誤導致亂碼在JSP檔案中使用page命令指定響應結果的MIME類型,如<%@ page language="java" contentType="text/html;charset=utf-8" %>
2.在接受request參數時進行,response響應時設定編碼格式request.setCharacterEncoding( "UTF-8" )response.setCharacterEncoding( "UTF-8")
3.使用String設定字元集的方式處理亂碼indexString = java.net.URLDecoder.decode(indexString , "UTF-8");indexString =  new String(indexString.getBytes("UTF-8"), "UTF-8");
4.使用自訂過濾器
package com.cdu.yige.filter;
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.http.HttpServletRequest;

public class EncodingFilter implements Filter {
     private String charset = "UTF-8";
     @Override
     public void destroy() {}
     @Override
     public void doFilter(ServletRequest request, ServletResponse response,
               FilterChain chain) throws IOException, ServletException {
          HttpServletRequest req = (HttpServletRequest) request;
          if(req.getMethod().equalsIgnoreCase("GET")) {
               if(!(req instanceof GetRequest)) {
                    req = new GetRequest(req, charset);//處理get請求編碼
               }
          } else {
               req.setCharacterEncoding(charset);//處理post請求編碼
          }
          chain.doFilter(req, response);
     }

     @Override
     public void init(FilterConfig fConfig) throws ServletException {
          String charset = fConfig.getInitParameter("charset");
          if(charset != null && !charset.isEmpty()) {
               this.charset = charset;
          }
     }
} 對get方式的過濾package com.cdu.yige.filter;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* 對GET請求參數加以處理!
* @author lucien
*
*/
public class GetRequest extends HttpServletRequestWrapper {
     private HttpServletRequest request;
     private String charset;
     
     public GetRequest(HttpServletRequest request, String charset) {
          super(request);
          this.request = request;
          this.charset = charset;
     }

     @Override
     public String getParameter(String name) {
          // 擷取參數
          String value = request.getParameter(name);
          if(value == null) return null;//如果為null,直接返回null
          try {
               // 對參數進行編碼處理後返回
               return new String(value.getBytes("ISO-8859-1"), charset);
          } catch (UnsupportedEncodingException e) {
               throw new RuntimeException(e);
          }
     }
     
     @SuppressWarnings({ "unchecked", "rawtypes" })
     @Override
     public Map getParameterMap() {
          Map<String,String[]> map = request.getParameterMap();
          if(map == null) return map;
          // 遍曆map,對每個值進行編碼處理
          for(String key : map.keySet()) {
               String[] values = map.get(key);
               for(int i = 0; i < values.length; i++) {
                    try {
                         values[i] = new String(values[i].getBytes("ISO-8859-1"), charset);
                    } catch (UnsupportedEncodingException e) {
                         throw new RuntimeException(e);
                    }
               }
          }
          // 處理後返回
          return map;
     }
     @Override
     public String[] getParameterValues(String name) {
          String[] values = super.getParameterValues(name);
          for(int i = 0; i < values.length; i++) {
               try {
                    values[i] = new String(values[i].getBytes("ISO-8859-1"), charset);
               } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
               }
          }
          return values;
     }
}
過濾器web.xml檔案配置      < filter>            <filter-name >EncodingFilter </filter-name >           <filter-class >com.cdu.yige.filter.EncodingFilter </filter-class >      </filter >      <filter-mapping >            <filter-name >EncodingFilter </filter-name >            <url-pattern >/* </url-pattern >      </filter-mapping >
5.修改tomcat伺服器server.xml的字元集配置,對get方式和post方式的亂碼終極處理。  <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
    URIEncoding="UTF-8"
    useBodyEncodingForURI="true"
    redirectPort="8443" />
6.get請求方式和post請求方式產生的亂碼處理方式略有不同,請自行百度參看。其他方法參看:http://wenku.baidu.com/view/f27afc4bfe4733687e21aa6c.html http://blog.csdn.net/pcxbest/article/details/24418303 http://my.oschina.net/u/267081/blog/137383 http://huifeideyu.blog.51cto.com/6764601/1176432 http://blog.163.com/shuangyuehuixin%40126/blog/static/16276137420113242322311/ http://www.iteye.com/topic/251743 

Java WEB應用中文亂碼處理總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.