Hello i am looking if i can handle with only one RestController method multiple params... with controllers method it could be done... but i couldnt find project with 2 like that.
@PostMapping(value ="upload")
public upload(@RequestParam MultipartFile file,@RequestParam List<String> myParams ){
some code here ....
return;
}
I am just wondering if is also a good practise... having two deferent type of objects in same controller and if its possible,,, any idea????
Simple answer: Yes, that's possible.
But as you asked for good practice, here's some context:
It is very helpful to understand how HTTP actually transports data.
If your request uses GET as request method, parameters are added to the URL as a query string. That could look like this: http://example.com/index?param1=value1¶m2=value2
In this case, Spring maps the key-value pairs from the query string to your method arguments. But this will only work for text.
If you're using POST , the data is sent inside the request body. How that is encoded depends on the media type of your data. For example, the default media type application/x-www-form-urlencoded
would encode the data to the same query string as above.
If you want to upload mixed-type form data like a file/blob along with some textual parameters, your data should be encoded with multipart/form-data
.
As long as the request body contains a key-value format, Spring Boot will still be able to distinguish and map the parameters via @RequestParam
(If the keys don't differ from your attribute names, you don't even need to assign a name to the value
attribute).
I highly recommend you to take a look at the @RequestBody
and @RequestPart
annotations as i think it often is best practice to use a model class (DTO) for the whole request body (or rather the form, semantically), especially if there are a lot of parameters to process.
You will need to specify the names of the variables.
@PostMapping(value ="upload")
public upload(
@RequestParam(value = "file") MultipartFile file,
@RequestParam(value = "myParams") List<String> myParams
){
some code here ....
return;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.