spring設置字符編碼過濾器


一、在web.xml中的配置

    <!-- characterEncodingFilter字符編碼過濾器 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <!--要使用的字符集,一般我們使用UTF-8(保險起見UTF-8最好)-->
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <!--是否強制設置request的編碼為encoding,默認false,不建議更改-->
            <param-name>forceRequestEncoding</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <!--是否強制設置response的編碼為encoding,建議設置為true,下面有關於這個參數的解釋-->
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--這里不能留空或者直接寫 ' / ' ,否者不起作用-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

二、CharacterEncodingFilter過濾器類淺析

打開該類源碼,可以看到該類有三個類屬性

private String encoding; //要使用的字符集,一般我們使用UTF-8(保險起見UTF-8最好)
private boolean forceRequestEncoding = false; //是否強制設置request的編碼為encoding
private boolean forceResponseEncoding = false; //是否強制設置response的編碼為encoding

主要方法只有一個,也就是下面這個,代碼邏輯很簡單,入注釋所解釋

 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String encoding = getEncoding();
        if (encoding != null) { //如果設置了encoding的值,則根據情況設置request和response的編碼
            //若設置request強制編碼或request本身就沒有設置編碼
            //則設置編碼為encoding表示的值
            if (isForceRequestEncoding() || request.getCharacterEncoding() == null) { 
                request.setCharacterEncoding(encoding);
            }
            //若設置response強制編碼,則設置編碼為encoding表示的值
            if (isForceResponseEncoding()) { //請注意這行代碼,下面有額外提醒
                response.setCharacterEncoding(encoding);
            }
        }
        filterChain.doFilter(request, response);
    }
# 額外提醒
if (isForceResponseEncoding()) { response.setCharacterEncoding(encoding); }

是在

filterChain.doFilter(request, response);
之前執行的,這也就是說這段代碼的作用是設置response的默認編碼方式,在之后的代碼里是可以根據需求設置為其他編碼的,即這里設置的編碼可能不是最終的編碼

對於get請求中文參數出現亂碼解決方法有兩個:

修改tomcat配置文件添加編碼與工程編碼一致,如下:

<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

另外一種方法對參數進行重新編碼:

String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")

 

ISO8859-1是tomcat默認編碼,需要將tomcat編碼后的內容按utf-8編碼

三、可以自定義攔截器(在web.xml中配置)
 <filter>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <filter-class>com.itwang.filter.SetCharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
      </init-param>
  </filter>
  <filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
public class SetCharacterEncodingFilter implements Filter {

    private FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest  request;
        HttpServletResponse response;
        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException("non-HTTP request or response");
        }
        
        String encoding = filterConfig.getInitParameter("encoding");
        if(encoding==null){
            encoding = "UTF-8";
        }
        
        //POST:
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset="+encoding);
        chain.doFilter(request, response);
    }

    public void destroy() {

    }

}

 


參考:https://blog.csdn.net/lianjunzongsiling/article/details/77926370


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM