SpringMVC- Chinese gibberish

Take an example of Chinese garbled characters: when submitting a form.

  1. The form

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

Copy the code
  1. Business Control class
package controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class controllerDemo02 {

    @RequestMapping("/c02/t1")
    public String test1(String name, Model model){
        System.out.println(name);
        model.addAttribute("message",name);
        return "test"; }}Copy the code
  1. Result: Garbled characters appear

The solution

Use your own filters

  1. You can define a Filter to Filter garbled characters
package Filter;

import javax.servlet.*;
import java.io.IOException;

public class EncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {}public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    public void destroy(a) {}}Copy the code
  1. Configure this filter in web.xml
    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>Filter.EncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>
Copy the code

Use the filters provided by SpringMVC

Configure directly in web.xml (fixed)

<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>
Copy the code

If the above two methods are not implemented, try the following method, written by the great God

package 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;

public class GenericEncodingFilter implements Filter {

    public void destroy(a) {}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Handle the character encoding of response
        HttpServletResponse myResponse=(HttpServletResponse) response;
        myResponse.setContentType("text/html; charset=UTF-8");

        // Transform to the object associated with the protocol
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // Enhance the request wrapper
        HttpServletRequest myrequest = new MyRequest(httpServletRequest);
        chain.doFilter(myrequest, response);
    }


    public void init(FilterConfig filterConfig) throws ServletException {}}// Custom Request object, wrapper class for HttpServletRequest
class MyRequest extends HttpServletRequestWrapper {

    private HttpServletRequest request;
    // Whether to encode the tag
    private boolean hasEncode;
    // Define a constructor that can be passed to an HttpServletRequest object to decorate it
    public MyRequest(HttpServletRequest request) {
        super(request);// super must be written
        this.request = request;
    }

    // Override the methods that need to be enhanced

    public Map getParameterMap(a) {
        // Get the request mode first
        String method = request.getMethod();
        if (method.equalsIgnoreCase("post")) {
            / / post request
            try {
                // Handle post garbled characters
                request.setCharacterEncoding("utf-8");
                return request.getParameterMap();
            } catch(UnsupportedEncodingException e) { e.printStackTrace(); }}else if (method.equalsIgnoreCase("get")) {
            / / get request
            Map<String, String[]> parameterMap = request.getParameterMap();
            if(! hasEncode) {// Ensure that the get manual encoding logic is run only once
                for (String parameterName : parameterMap.keySet()) {
                    String[] values = parameterMap.get(parameterName);
                    if(values ! =null) {
                        for (int i = 0; i < values.length; i++) {
                            try {
                                // Handle get garbled characters
                                values[i] = new String(values[i]
                                        .getBytes("ISO-8859-1"), "utf-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                hasEncode = true;
            }
            return parameterMap;
        }
        return super.getParameterMap();
    }

    // Take a value

    public String getParameter(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        if (values == null) {
            return null;
        }
        return values[0]; // Retrieve the first value of the argument
    }

    // take all values

    public String[] getParameterValues(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        returnvalues; }}Copy the code