Map multipart data to POJO on Spring WebFlux - java

On the frontend we have a form which send the data as multipart/form-data and we need to receive the data in the controller. Keys nameconvention is to use hyphens.
We can receive the data in the controller by using #RequestPart annotation
#PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<String> create(#RequestPart("first-name") String firstName,
#RequestPart("last-name") String lastName) {
// ...
}
But the form can contains more fields, and in this case it is not so convenient to receive data by using #RequestPart.
Is there a way to map multipart fields to a POJO on Spring WebFLux? Something like
class UserData {
private String firstName;
private String lastName;
// getters & setters
}
#PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<String> create(UserData userData) {
// ...
}

Related

How can I add multiple files with 2 fields in Springboot

My request DTO :
#Getter
#Setter
public class FileUploadRequestDTO {
private MultipartFile fileMap;
private String filetype;
private String fileNature;
}
// Controller method
#RequestMapping(path = FLAT_FILE_UPLOAD, method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<FileUploadResponseDTO> flatFileUpload(List<FileUploadRequestDTO> fileDTO){
}
**
Question:
I want to send multiple files with the following variables in the request body. How to achieve this in Postman?
**

How to read additional JSON attribute(s) which is not mapped to a #RequestBody model object in Spring boot

I have a RestController which looks like this
#RequestMapping(value = "/post", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> test(#RequestBody User user) {
System.out.println(user);
return ResponseEntity.ok(user);
}
And the User model which looks like this
class User {
#NotBlank
private String name;
private String city;
private String state;
}
I have a requirement wherein users can pass some extra additional attribute(s) in the input JSON, something like this
{
"name": "abc",
"city": "xyz",
"state": "pqr",
"zip":"765234",
"country": "india"
}
'zip' and 'country' are the additional attributes in the input JSON.
Is there any way in Spring Boot we can get these additional attributes in the Request Body ?
I know a way wherein I can use either a "Map" or "JsonNode" or "HttpEntity" as Requestbody parameter. But I don't want to use these classes as I would loose the javax.validation that can be used inside "User" model object.
Extend your User DTO with a Map<String, String> and create a setter which is annotated with #JsonAnySetter. For all unknown properties this method will be called.
class User {
private final Map<String, Object> details= new HashMap<>);
#NotBlank
private String name;
private String city;
private String state;
#JsonAnySetter
public void addDetail(String key, Object value) {
this.details.add(key, value);
}
public Map<String, Object> getDetails() { return this.details; }
}
Now you can obtain everything else through the getDetails().

How to receive json param in spring boot

I have a Json like the following.
{"person":[{"name":"asd","age":"22"},{"name":"asd","age":"22"}]}
but it could also be:
{"person":[{"name":"asd","age":"22"},{"name":"asd","age":"22"}],"city":["NewYork"],"student":"false"}
How can I receive it in a Spring Boot Controller?
You should use #RequestBody annotation.
#RequestMapping("/api/example")
public String example(#RequestBody String string) {
return string;
}
Later, add some validations and business logic.
You can generate custom class with http://www.jsonschema2pojo.org/. Once generated you can expect your custom class instead of String.
For further instructions, I find this tutorial interesting.
You can receive the json like below, Spring Boot will convert your json into model(For example "Comment" model below) which you defined.
#RequestMapping(value = "/create", method = RequestMethod.POST)
public ResultModel createComment(#RequestBody Comment comment) {...}
1) You need to difine your rest controllers. Example
#Autowired
UserService userService;
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if (users.isEmpty()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
2) Define your pojo: Example
public class User {
String name;
String age;
public User(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
}
3) Define a service
#Service
public class UserService {
public List<User> findAllUsers(){
// Those are mock data. I suggest to search for Spring-data for interaction with DB.
ArrayList<User> users = new ArrayList<>();
User user = new User("name", "5");
users.add(user);
return users;
}
}
You can follow this tutorial. If you want to just send a json message to a spring boot rest controller you can use a rest client like postman.

Convert form data to object (DTO)

I have this route in controller which accepts - application/x-www-form-urlencoded
#RequestMapping(value = "/browser", method = RequestMethod.POST, produces = {"application/xml"}, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
#ResponseBody
public ResponseEntity<String> processServerCallback(#RequestBody final MultiValueMap<String, String> formVars) {
System.out.println(formVars);
return null;
}
Now I need to convert formVars to my DTO object. How can I do that?
Say, formVars looks like this:
public class FormVars{
private String name;
private int age;
//constructors and getters and setters
}`
Then in your controller method, you need to replace #RequestBody MultiValueMap<String, String> with #RequestBody FormVars formVars

Why is Spring Data Neo4J Ignoring #JsonIgnore?

Using the following #NodeEntity
#NodeEntity
public class Person extends BasePersistenceObject {
#GraphId
Long id;
String fullName;
#Indexed(unique=true)
String email;
String passwordHash = null;
#JsonIgnore
public String getPasswordHash() {
return passwordHash;
}
...
}
I'm still seeing the passwordHash in the JSON Response from the following controller method:
#RequestMapping(value = "/login", method=RequestMethod.POST)
public #ResponseBody Person login(#RequestBody Map<String, String> credentials, HttpServletRequest request) throws AuthorizationException {
String email = credentials.get("email");
String password = credentials.get("password");
String ipAddress = request.getRemoteAddr();
return authService.authenticate(email, password, ipAddress);
}
Spring Data Neo4J has nothing to do with JSON serialization, that's the responsibility of Spring MVC and Jackson or Gson, depending on what you use. So make sure, that Jackson is used for JSON serialization, otherwise the annotation wouldn't work.

Categories

Resources