avatarMalvin Lok

Summary

The provided web content outlines eight distinct methods for Spring Boot to receive parameters from HTTP requests.

Abstract

The article on the undefined website presents a concise guide to handling HTTP request parameters in Spring Boot applications. It covers a range of techniques, from using formal parameters and entity classes to more complex structures like arrays, sets, and maps. The article also discusses the use of annotations such as @RequestParam, @PathVariable, and @RequestBody to facilitate parameter retrieval. Additionally, it touches on the direct use of HttpServletRequest and the handling of JSON format parameters through the @RequestBody annotation. Each method is illustrated with code examples, providing developers with a clear understanding of how to implement these parameter-receiving strategies in their Spring Boot controllers.

Opinions

  • The author suggests that formal parameters are best suited for scenarios with a limited number of parameters.
  • When dealing with entity parameters, the @RequestParam annotation should not be used with Get requests, as it is not supported for receiving parameters from entity classes.
  • Utilizing HttpServletRequest is presented as a flexible way to retrieve parameters without specifying their names in the method signature.
  • The @PathVariable annotation is recommended for extracting data from the URI path, which can be particularly useful for RESTful services.
  • For handling multiple values with the same parameter name, array parameters are a straightforward solution.
  • Set parameters are introduced as a way to handle an undefined number of parameters of the same type, providing a collection that excludes duplicates.
  • The @RequestBody annotation is highlighted as the preferred method for receiving JSON format parameters sent from the front end.
  • The use of a Map is suggested for receiving parameters either as query parameters using @RequestParam or as a JSON body using @RequestBody, offering a dynamic key-value pair structure.
  • The article concludes with a note of anticipation for future encounters, indicating the author's intention to continue sharing knowledge on the subject.

8 Ways Spring Boot Receives Parameters

Photo by Boitumelo on Unsplash

This is a summary of how Spring Boot can receive parameters from HTTP requests.

How that will become one of your library stories.

1 . Formal Parameters

This approach is generally suitable for cases with fewer parameters.

@Slf4j
@RestController
@RequestMapping("/profile")
public class ProfileController {

    @GetMapping("/detail")
    public String getDetail(String uid) {
        log.info("uid:{}", uid);
       return "ok";
    }

}

if the parameter is labeled with @RequestParam, indicating that this parameter needs to be passed, otherwise an error will be reported.

@Slf4j
@RestController
@RequestMapping("/profile")
public class ProfileController {

    @GetMapping("/detail")
    public String getDetail(@RequestParam String uid) {
        log.info("uid:{}", uid);
       return "ok";
    }

}

2. Entity Parameters

@Slf4j
@RestController
@RequestMapping("/profile")
public class ProfileController {

    @GetMapping("/detail")
    public String getDetail(Profile profile) {
        log.info("profile:{}", profile);
       return "ok";
    }

}

The RequestParam annotation cannot be used when a Get request receives a parameter from an entity class, as it is not supported to get the parameter in this way.

3. Via HttpServletRequest

@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @GetMapping("/detail")
    public String getDetail(HttpServletRequest request) {
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        log.info("name:{}", name);
        log.info("sex:{}", sex);
       return "ok";
    }

}

4. Via the @PathVariable annotation

@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @GetMapping("/detail/{name}/{sex}")
    public String getDetail(@PathVariable String name, @PathVariable String sex) {
        log.info("name:{}", name);
        log.info("sex:{}", sex);
       return "ok";
    }
}

5. Array Parameters

@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @GetMapping("/detail")
    public String getDetail(String[] names) {
        Arrays.asList(names).forEach(name->{
            System.out.println(name);
        });
       return "ok";
    }

}

6. Set Parameters

@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @GetMapping("/detail")
    public String getDetail(@RequestParam List<String> names) {
        names.forEach(name->{
            System.out.println(name);
        });
       return "ok";
    }

}

7. Via the @RequestBody annotation

The RequestBody annotation is used to receive json format parameters in the body passed from the frontend.

@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @PostMapping("/save")
    public String getDetail(@RequestBody Profile profile) {
      log.info("name:{}", profile.getName());
      log.info("phone:{}", profile.getPhone());
       return "ok";
    }

}

8. Via Map

1. Pass the parameter as param, the RequestParam annotation receives the parameter.

@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @PostMapping("/save")
    public String getDetail(@RequestParam Map<String,Object> map) {
        System.out.println(map);
        System.out.println(map.get("name"));
       return "ok";
    }

}

2. Pass the parameter in body JSON format and receive it in RequestBody annotation.

@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @PostMapping("/save")
    public String getDetail(@RequestBody Map<String,Object> map) {
        System.out.println(map);
        System.out.println(map.get("name"));
       return "ok";
    }

}

See you next time! Thanks for reading.

Java
Spring
Spring Boot
Development
Code Newbie
Recommended from ReadMedium