Talking about the misunderstanding of @ RequestParam of required = true

  • 2021-12-11 07:22:21
  • OfStack

Misunderstandings of directory @ RequestParam (required = true). First, the conclusion parameter summary @ RequestParam (required = false int id) does not report errors

Misunderstandings of @ RequestParam (required = true)

Let's start with the conclusion

required = true is to report an error when the front end does not transmit parameters, which does not prevent the parameters from being empty.

Consider code under 1:


@GetMapping("/userInfo")
    public void userInfo(@RequestParam(required = true) Integer id) {
           ...
    }

A 400 error will be reported if the request is as follows:

http://localhost:8088/userInfo

However, you can make id empty by constructing the following request:

http://localhost:8088/userInfo?id=

Parameter summary

required=true Indicates that the front end must pass parameters. required=false Indicates that when the front end does not pass parameters, the parameters will be set to null. Therefore, if the parameter is a type int that cannot be assigned to null, an error may be reported.

When defaultValue is used, required can only be false. When the front end does not transmit parameters, the parameters will be set to defaultValue.

The @ RequestParam (required=false int id) value does not report an error

@RequestParam(required=false int id) : required=false indicates that no value can be passed, if yes


//  Notice that now is String Type of id
@RequestParam(required=false Sting id)

This kind of non-value transmission will not report errors

But if it is the int type written on the title, this


@RequestParam(required=false int id)

An error will be reported because null cannot be assigned to int.


Related articles: