jsp解決亂碼終極攻略

來源:互聯網
上載者:User

    今天發現項目竟然有中文亂碼問題!? ,明明記得配置好頁面編碼和filter了,怎麼會呢?

     開啟頁面發現編碼如下:              

<%@ page language="java" import="java.util.*,pojo.*" pageEncoding="UTF-8"%>

    過濾器也正常:

       因為也考慮了AJAX的情況,所以和一般的過濾器有點區別,但是紅色部分確實被執行了.

public class Encoding implements Filter {private String charset;private String ajaxPostContentType;      public static final String AJAX_POST_CONTENT_TYPE_DEFAULT = "application/x-www-form-urlencoded";   public void destroy() {// TODO Auto-generated method stub}public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {// TODO Auto-generated method stubHttpServletRequest request = (HttpServletRequest)arg0;String requestSrc = request.getQueryString();if(requestSrc !=null){arg0.setCharacterEncoding("UTF-8");arg1.setCharacterEncoding("UTF-8");arg0.getParameter("");}else{arg0.setCharacterEncoding(charset);arg1.setCharacterEncoding("text/html;charset="+charset);}arg2.doFilter(arg0, arg1);}public void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stubcharset = arg0.getInitParameter("charset");ajaxPostContentType = arg0.getInitParameter("ajaxContent");if(ajaxPostContentType == null){ajaxPostContentType = AJAX_POST_CONTENT_TYPE_DEFAULT;}}} 

   Web.xml中配置如下:

  <filter>   <filter-name>encode</filter-name>  <filter-class>filter.Encoding</filter-class>  <init-param>  <param-name>charset</param-name>  <param-value>utf8</param-value>  </init-param>  </filter>    <filter-mapping>  <filter-name>encode</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping>

貌似該做的都做了,到底問題出在哪裡? 經過一番測試原來問題是:

<form id="trheaderform" name="trheaderform" action="lagp.do" >

仔細看了一下,沒指定提交方式,所以預設用get方式提交!改為:

<form id="trheaderform" name="trheaderform" action="lagp.do" method="post">

測試OK!

總結一下:

    1。 要保證Jsp的頁面編碼是UTF-8

    2。 配置好filter,強制編碼為UTF-8

    3。 設定Form的提交方式為POST

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.