1. 程式人生 > 其它 >SpringMVC篇(七)亂碼問題

SpringMVC篇(七)亂碼問題

技術標籤:SpringMVC篇亂碼過濾器springjava

亂碼問題

測試步驟:

1、我們可以在首頁編寫一個提交的表單

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/e/t1" method="post">
<input type="text" name="name"> <input type="submit"> </form> </body> </html>

2、後臺編寫對應的處理類

@Controller
public class Encoding {
    @RequestMapping("/e/t")
    public String test(Model model,String name){
        model.addAttribute
("msg",name); //獲取表單提交的值 return "test"; //跳轉到test頁面顯示輸入的值 } }

3、輸入中文測試,發現亂碼
在這裡插入圖片描述
亂碼問題通過過濾器解決 , 而SpringMVC給我們提供了一個過濾器 , 可以在web.xml中配置 .

修改了xml檔案需要重啟伺服器!
配置Springmvc的亂碼過濾器

<filter>
    <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

但是我們發現 , 有些極端情況下.這個過濾器對get的支援不好 .
處理方法 :

1、修改tomcat配置檔案 :設定編碼!

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

2、自定義過濾器

package com.ni.filter;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
 
/**
 * 解決get和post請求 全部亂碼的過濾器
 */
public class GenericEncodingFilter implements Filter {
 
    @Override
    public void destroy() {
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //處理response的字元編碼
        HttpServletResponse myResponse=(HttpServletResponse) response;
        myResponse.setContentType("text/html;charset=UTF-8");
 
        // 轉型為與協議相關物件
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 對request包裝增強
        HttpServletRequest myrequest = new MyRequest(httpServletRequest);
        chain.doFilter(myrequest, response);
    }
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
}
 
//自定義request物件,HttpServletRequest的包裝類
class MyRequest extends HttpServletRequestWrapper {
 
    private HttpServletRequest request;
    //是否編碼的標記
    private boolean hasEncode;
    //定義一個可以傳入HttpServletRequest物件的建構函式,以便對其進行裝飾
    public MyRequest(HttpServletRequest request) {
        super(request);// super必須寫
        this.request = request;
    }
 
    // 對需要增強方法 進行覆蓋
    @Override
    public Map getParameterMap() {
        // 先獲得請求方式
        String method = request.getMethod();
        if (method.equalsIgnoreCase("post")) {
            // post請求
            try {
                // 處理post亂碼
                request.setCharacterEncoding("utf-8");
                return request.getParameterMap();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else if (method.equalsIgnoreCase("get")) {
            // get請求
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!hasEncode) { // 確保get手動編碼邏輯只執行一次
                for (String parameterName : parameterMap.keySet()) {
                    String[] values = parameterMap.get(parameterName);
                    if (values != null) {
                        for (int i = 0; i < values.length; i++) {
                            try {
                                // 處理get亂碼
                                values[i] = new String(values[i]
                                        .getBytes("ISO-8859-1"), "utf-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                hasEncode = true;
            }
            return parameterMap;
        }
        return super.getParameterMap();
    }
 
    //取一個值
    @Override
    public String getParameter(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        if (values == null) {
            return null;
        }
        return values[0]; // 取回引數的第一個值
    }
 
    //取所有值
    @Override
    public String[] getParameterValues(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        return values;
    }
}