Home > OS >  Spring RequestMapping doesn't split RequestParam and RequestBody
Spring RequestMapping doesn't split RequestParam and RequestBody

Time:01-26

I want to implement a POST endpoint where it is possible to accept or refuse programmatically the data sent, depending if it comes from querystring or from x-www-form-urlencoded data. I mean:

@PostMapping(value="/api/signin")
ResponseEntity<SigninResponse> signin(
     @RequestParam(value = "username", required = false) String username,
     @RequestParam(value = "password", required = false) String password,
     @RequestBody(required = false) @ModelAttribute SigninRequest sr) {
        // here if I POST a SigninRequest without queryString, aka
        // user/pass sent in x-www-form-urlencoded, both sr and 
        // username password vars are filled. The same, if I send 
        // username password on querystring, without any data 
        // on x-www-form-urlencoded, also sr is filled
     }

If I remove the "@ModelAttribute", the POST with querystring works, but the one with x-www-form-urlencoded raises an exception "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported" (why?) and returns a 415 (Unsupported Media Type).

Anyway, I'm looking for a way to understand when the POST data comes from querystring and when the data comes from x-www-form-urlencoded, to enable/disable programmatically one way vs. the other. I can eventually write two different methods (both in POST), it is not needed to use just one.

Any suggestion?

Thank you.

CodePudding user response:

Why you use @RequestBody and @ModelAttribute with your arg at the same time?

You can use @ModelAttribute(binding=false) instead of required=false.

That should help: (Spring: @ModelAttribute VS @RequestBody)

Tip: I don't think is a good practice to include password in querystring.

CodePudding user response:

By default, RequestBody doesn't support application/x-www-form-urlencoded. If you're sending data from a form, its media type will be application/x-www-form-urlencoded which is not supported by RequestBody. RequestBody supports other types such as application/json. @ModelAttribute is like telling Spring you are serializing SigninRequest from a request with application/x-www-form-urlencoded media type.

More info here: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

  • Related