Demonstration of several cases of SpringMvc accepting request parameters

  • 2021-11-02 01:06:00
  • OfStack

Description:

Usually, get requests get parameters after url, while post requests get parameters in the request body. Therefore, the two will be different in the way of request.   

1. Write the accepted parameters directly in the formal parameters of the corresponding method of controller (applicable to get submission mode)


/**
     * 1. Write the parameters of the form directly in Controller In the formal parameters of the corresponding method, 
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/addUser1")
    public String addUser1(String username, String password) {
        System.out.println ("username is:" + username);
        System.out.println ("password is:" + password);
        return username + "," + password;
    }

2. Get the parameters through the url request path


/**
     * 2 , through @PathVariable Get the parameters in the path 
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/addUser4/{username}/{password}", method = RequestMethod.GET)
    public String addUser4(@PathVariable String username, @PathVariable String password) {
        System.out.println ("username is:" + username);
        System.out.println ("password is:" + password);
        return "addUser4";
    }

3. Accept the sent parameter information through the request request object (Get request mode or Post request mode can be used)


/**
     * 3 , through HttpServletRequest Receive 
     *
     * @param request
     * @return
     */
    @RequestMapping("/addUser2")
    public String addUser2(HttpServletRequest request) {
        String username = request.getParameter ("username");
        String password = request.getParameter ("password");
        System.out.println ("username is:" + username);
        System.out.println ("password is:" + password);
        return "demo/index";
    }

4. Encapsulate the JavaBean object to accept the request parameters (get and post can be used)

4.1 First, create the corresponding JavaBean in the module, and provide the corresponding get and set methods.


package com.example.demo.pojo;

import lombok.Data;

@Data
public class User1 {
    private String username;
    private String password;
}

4.2 Controller layer


/**
     * 4 , through 1 A bean To receive 
     *
     * @param user
     * @return
     */
    @RequestMapping("/addUser3")
    public String addUser3(User1 user) {
        System.out.println ("username is:" + user.getUsername ( ));
        System.out.println ("password is:" + user.getPassword ( ));
        return "/addUser3";
    }

5. Use the annotation @ RequestParam annotation to bind the request parameter to the formal parameter of the corresponding method in the Controller layer


/**
     * 5 With annotations @RequestParam Bind request parameters to method entry parameters 
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value="/addUser6",method=RequestMethod.GET)
    public String addUser6(@RequestParam("username") String username,@RequestParam("password") String password) {
        System.out.println("username is:"+username);
        System.out.println("password is:"+password);
        return "demo/index";
    }

The following describes how to send a request in json format and accept data:

1. Encapsulate the key and value values of the json request into the attributes of the entity object (usually, the parameters are placed in the request body body and obtained by the back end in application/json format)

1.1 Create 1 Entity Class


public class User2 implements Serializable {
    private static final long serialVersionUID = 1L;
    @JsonProperty(value = "id")
    private Integer id;
    @JsonProperty(value = "name")
    private String name;
    @JsonProperty(value = "age")
    private Integer age;
    @JsonProperty(value = "hobby")
    private List<String> hobby;

/**
     * Will json Requested key,value Encapsulated in entity objects. 
     * @param user
     * @return
     */
    @PostMapping("/save")
    public String saveUser(@RequestBody User2 user) {
//        list.add(user);
//        User2 user2 = new User2 (  );
//        user2.setId (user.getId ());
//        user2.setAge (user.getAge ());
//        user2.setName (user.getName ());
//        user2.setHobby (user.getHobby ());
        return "success"+user;
    }

2. Encapsulate the values of key and value requested by json into the attributes of request object (usually request parameters are placed in body, and content-type is changed to x-www-form-urlencoded)


/**
     *  Encapsulates the request parameters to the request Object. 
     * @param request
     * @return
     */
    @PostMapping("/save2")
    public User2 save(HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        Integer age = Integer.parseInt(request.getParameter("age"));
        String parameter = request.getParameter("hobby");
        List<String> stringList = new ArrayList<> (  );

        String[] split = parameter.split (",");
        for (int i = split.length - 1; i >= 0; i--) {
            stringList.add (split[i]);
        }

        User2 user2 = new User2(id, name, age, stringList);
//        list.add(user);
        return user2;
    }

3. Transform json parameters into JSONOBject objects through http protocol

3.1 Controller layer accepts JSON parameters


/**
     *  Pass http The protocol converts the parameters to jsonobject
     * @param request
     * @return
     * @throws IOException
     * @throws JSONException
     */
    @PostMapping("/save3")
    public User2 save3(HttpServletRequest request) throws IOException, JSONException {

        JSONObject jsonObject = handlerData(request);
        Integer id = jsonObject.getInteger("id");
        String name = jsonObject.getString("name");
        Integer age = jsonObject.getInteger("age");
        List<String> hobby = jsonObject.getObject("hobby", List.class);
        User2 user3 = new User2 (id, name, age, hobby);
//        list.add(user);
        return user3;
    }

3.2 Convert an Json string into an Jsonobject object by


/**
     * 2 , through @PathVariable Get the parameters in the path 
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/addUser4/{username}/{password}", method = RequestMethod.GET)
    public String addUser4(@PathVariable String username, @PathVariable String password) {
        System.out.println ("username is:" + username);
        System.out.println ("password is:" + password);
        return "addUser4";
    }
0

4. Encapsulate the request parameters in json format into key and value key-value pairs of hashmap. (The json string is strung in body, and the request format is application/json)


/**
     * 2 , through @PathVariable Get the parameters in the path 
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/addUser4/{username}/{password}", method = RequestMethod.GET)
    public String addUser4(@PathVariable String username, @PathVariable String password) {
        System.out.println ("username is:" + username);
        System.out.println ("password is:" + password);
        return "addUser4";
    }
1

This document is mainly a summary of the following two documents:

https://www.cnblogs.com/lirenhe/p/10737673.html

https://blog.csdn.net/zyxwvuuvwxyz/article/details/80352712


Related articles: