“This is the 29th day of my participation in the August Gwen Challenge.

1. Receive parameters as attributes

@Controller
@RequestMapping("/user")
public class UserController {
    @GetMapping("/t1")
    public String test1(@RequestParam("username") String name, Model model){
        //1. Receive front-end parameters
        System.out.println("Parameter is"+name);
        //2. Pass the returned result to the front end
        model.addAttribute("msg",name);
        //3. View jump
        return "hello"; }}Copy the code

Front-end submitted domain is: http://localhost:8080/user? name=wanli

@requestParam () = @requestParam (“username”);

Could we submit the front domain can only be as follows: http://localhost:8080/user? username=wanli

2. Receive parameters as objects

Entity class User

package com.cheng.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private int age;
}
Copy the code
    @GetMapping("/t2")
    public String test2(User user,Model model){
        System.out.println(user); //User(id=1, name=null, age=3)
        model.addAttribute("msg",user);        
        return "hello";
    }
Copy the code

Submit data: http://localhost:8080/s2/user/t2? username=wanli&id=1&age=3

The parameter name passed by the front end must be the same as the object name, otherwise null is received.

3. Data echo

3.1. Through ModelAndView

public class ControllerTest1 implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       // Returns a model view object
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg"."ControllerTest1");
       mv.setViewName("test");
       returnmv; }}Copy the code

3.2. Through ModelMap

@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
   // Encapsulate the data to be displayed in the view
   // req.setattribute ("name",name);
   model.addAttribute("name",name);
   System.out.println(name);
   return "hello";
}
Copy the code

3.3. Through the Model

@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
   // Encapsulate the data to be displayed in the view
   // req.setattribute ("name",name);
   model.addAttribute("msg",name);
   System.out.println(name);
   return "test";
}
Copy the code

Differences between the three echo modes:

  • Model has only a few methods suitable for storing data, simplifying the operation and understanding of Model objects for beginners;
  • ModelMap inherits LinkedMap. In addition to implementing some of its own methods, ModelMap also inherits LinkedMap methods and features;
  • ModelAndView can store data at the same time, can set the returned logical view, control the jump of the display layer.

4, deal with the problem of garbled code

Use SpringMVC filters

<! -- Configure garble filtering for 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>
Copy the code

If the above configuration does not solve the gargle problem, set the code apache-tomcat-9.0.41\conf\server.xml in the Tomcat configuration file

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

Ultimate garble solution: Custom filters, generic, but remember to register in web.xml

package com.cheng.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;

/** * Filter to resolve all garbled get and POST requests */
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
    <filter>
        <filter-name>GenericEncodingFilter</filter-name>
        <filter-class>com.cheng.filter.GenericEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>GenericEncodingFilter</filter-name>
        <url-pattern>/ *</url-pattern>
    </filter-mapping>
Copy the code