相信大家在寫頁面時明明都在jsp裡面設定了

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

 

可是資料傳到server端的時候卻還是變亂碼了

當然也有可能是你eclipse沒有設定成utf-8

如果都設定了亂碼一樣產生了要怎麼辦?

 

如果你的架構有用到spring的話呢~那一切就好辦了~

只要在web裡加入這一段

<filter>
    <filter-name>SetCharacterEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>SetCharacterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

 

這樣亂碼就不見了~整個變正常了

如果架構沒有用到spring的話呢?沒關係的

直接把org.springframework.web.filter.CharacterEncodingFilter這個class的code拷貝出來


import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CharacterEncodingFilter extends OncePerRequestFilter {

    private String encoding;
    private boolean forceEncoding = false;

 
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

 
    public void setForceEncoding(boolean forceEncoding) {
        this.forceEncoding = forceEncoding;
    }


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

        if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
            request.setCharacterEncoding(this.encoding);
            if (this.forceEncoding) {
                response.setCharacterEncoding(this.encoding);
            }
        }
        filterChain.doFilter(request, response);
    }

}

 

 

假設討厭鬼將上列的code放在nerdy.encode這個package裡的CharacterEncodingFilter.java裡

而在web.xml裡只要加入

<filter>
    <filter-name>SetCharacterEncoding</filter-name>
    <filter-class>nerdy.encode.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>SetCharacterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

 

亂碼就不見了

images (3)  

arrow
arrow
    文章標籤
    encoding utf-8 亂碼
    全站熱搜
    創作者介紹
    創作者 討厭鬼 的頭像
    討厭鬼

    討厭鬼教學

    討厭鬼 發表在 痞客邦 留言(0) 人氣()