Home > OS >  For multipart request, how to use using @ModelAttribute and Hashmap together?
For multipart request, how to use using @ModelAttribute and Hashmap together?

Time:08-10

First of all, thank you in advance for your support.

My problem;

First I am successfully getting my specific parameters in Employer. However, I also have a constantly changing parameter list in request. I want to get them with Map too.

My dto:

public class Employee {
    private String name;
    private MultipartFile document;
}
@RequestMapping(path = "/employee", method = POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public Mono<Employee> saveEmployee(@ModelAttribute Employee employee, Map<String,Object> otherValues) {
System.out.println(otherValues.get("key1").toString());
return employeeService.save(employee);
}

I attached a request example aslo.

NOTE: I used @RequestParam, @RequestPart before Map<String,Object> otherValues like this;

 @RequestParam Map<String,Object> otherValues
 @RequestPart Map<String,Object> otherValues

But I still couldn't get the rest of the data.

enter image description here

CodePudding user response:

When you want to get values from form data, you can create a model like a DTO, with field of both entity (employee) and additional data (otherValues). Because @ModelAttribute can bind data to only one named model attribute

CodePudding user response:

@RequestMapping(path = "/employee", method = POST, consumes ={MediaType.MULTIPART_FORM_DATA_VALUE })
public Mono<Employee> saveEmployee(
@ModelAttribute Employee employee, 
@RequestParam Map<Object,Object> otherValues,
@RequestParam("file") MultipartFile file) {
System.out.println(otherValues.get("key1").toString());
return employeeService.save(employee);
}

Main trick is to use Object for key and value;

@RequestParam Map<Object,Object> otherValues
  • Related