Spring MVC learning notes. Deal with submitted data and garbled code, spring MVC garbled code filter, custom garbled code filter, Tomcat configuration coding

Article catalogue

Deal with data submission and garbled code

1. Data processing

1. Processing submitted data

  1. The domain name of the submitted data is consistent with the parameter name of the processing method

Submit data: http://localhost:8080/user/t1name=jiangnan

Treatment method:

@GetMapping("/t1")
public String test1(String name, Model model){
    // 1. Receive front-end parameters
    System.out.println("Front end parameters are:"+name);
    // 2. Pass the returned result to the front end
    model.addAttribute("msg",name);
    // 3. Jump to view
    return "test";
}

Background output: front end parameter: jiangnan

Note: the front end transmits name and the Controller receives name, so no additional processing is required.

  1. The submitted domain name is inconsistent with the parameter name of the processing method

Submit data: http://localhost:8080/user/t2username=jiangnan

Treatment method:

@GetMapping("/t2")
public String test2(@RequestParam("username") String name, Model model){
    // 1. Receive front-end parameters
    System.out.println("Front end parameters are:"+name);
    // 2. Pass the returned result to the front end
    model.addAttribute("msg",name);
    // 3. Jump to view
    return "test";
}

Background output: front end parameter: jiangnan

Note: the parameter transmitted from the front end is username, and the parameter received by the Controller is name. We need to use @ RequestParam("username") String name to receive the username transmitted from the front end and bind the name in the Controller.

  1. Submitted is an object

It is required that the submitted form field and the attribute name of the object are consistent, and the parameter can use the object

  • Entity class

    public class User {
    private int id;
    private String name;
    private int sex;
    //Structure
    // get set
    // toString
    }

  • Submit data: http://localhost:8080/user/t3id=1&name=jiangnan&sex=1

Treatment method:

// The front end receives ID, name and age
@GetMapping("/t3")
public String test(User user){
    System.out.println(user);
    return "test";
}

Back end output: User(id=1, name=jiangnan, sex=1)

Note: the parameters passed by the front end correspond to the properties in the User class, so we can use the User object to receive.

If an object is used, the parameter name passed by the front end must be consistent with the object name, otherwise it is null or 0.

2. Data display to the front end

reference resources: https://blog.csdn.net/weixin_45842494/article/details/122870656

The key part of the system, plus the received data.

2. Garbled code

2.1 use spring MVC's own filter

Test steps:

  1. We can write a submission form on the home page

  2. Write the corresponding processing class in the background

    @Controller
    public class Encoding {
    @RequestMapping("/e/t")
    public String test(Model model, String name){
    System.out.println(name);
    model.addAttribute(“msg”,name); // Get the value of the form submission
    return “test”; // Jump to the test page and display the entered value
    }
    }

  3. Input Chinese and find garbled code

resolvent:

pringMVC provides us with a filter, which can be found on the web XML.
The xml file has been modified. You need to restart the server!

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

Note that here is used/*

Test again to be normal.

2.2 custom filters

First, set our tomcat code to utf-8

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

Treatment method:

package com.xxc.controller;

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;

/**
 * Filter to solve all the garbled codes of get and post requests
 */
public class GenericEncodingFilter implements Filter {
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse
            response, FilterChain chain) throws IOException, ServletException {
        //Handle the character encoding of the response
        HttpServletResponse myResponse=(HttpServletResponse) response;
        myResponse.setContentType("text/html;charset=UTF-8");
        // Transformation into agreement related objects
        HttpServletRequest httpServletRequest = (HttpServletRequest)
                request;
        // Enhanced request packaging
        HttpServletRequest myrequest = new
                MyRequest(httpServletRequest);
        chain.doFilter(myrequest, response);
    }
    @Override
    public void init(FilterConfig filterConfig) throws
            ServletException {
    }
}
    //Custom request object, wrapper class of HttpServletRequest
class MyRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    //Coded flag
    private boolean hasEncode;
    //Define a constructor that can be passed into the HttpServletRequest object to decorate it
    public MyRequest(HttpServletRequest request) {
        super(request);// super must write
        this.request = request;
    }
    // Override methods that need to be enhanced
    @Override
    public Map getParameterMap() {
        // Get request method first
        String method = request.getMethod();
        if (method.equalsIgnoreCase("post")) {
            // post request
            try {
                // Handle post garbled code
                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) { // Make sure that the get manual encoding logic runs 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 code
                                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
    @Override
    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 parameter
    }
    //Take all values
    @Override
    public String[] getParameterValues(String name) {
        Map<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        return values;
    }
}

This is written by some great gods found on the Internet. Generally, the default garbled code processing of spring MVC can be well solved!

Then on the web Configure this filter in XML!

<!--Garbled filter-->
<filter>
    <filter-name>encoding</filter-name>
    <filter-class>com.xxc.controller.GenericEncodingFilter</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>

Note: complete directory structure

Keywords: Front-end Tomcat html Interview

Added by slibob on Mon, 21 Feb 2022 13:08:55 +0200