Spring boot url configure with data and multipartfile - spring-boot

I have this controller file with the following code
#PostMapping(path = "/addDefaultTemplate")
void addDefaultTemplate(#Valid #ModelAttribute AddDefaultTemplate defaultTemplate) throws Exception {
//Logic
}
And i have this AddDefaultTemplate java file
#Data
public class AddDefaultTemplate {
#NotBlank
String name;
#NotNull
String category;
#NotNull
String type;
#NotNull
MultipartFile[] file;
}
When i comment the multipartfile configuration in the above class, the url is working fine. If i add the multipartfile in the above class url throws 400 error. Why, what's the reason?
This is the request data.

Related

SpringBoot + Thymeleaf - upload MultipartFile in form

I've done the following Thymeleaf form which takes some fields and a .pdf CV file
Form: link
There is the controller:
#Controller
#RequestMapping("/interview")
public class InterviewController {
#PostMapping(path = "/create", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public #ResponseBody ResponseEntity<Object> createInterview(#RequestBody #ModelAttribute CreateInterviewTO createInterviewTO) {
ErrorRTO errorRTO = checkErrorsInsertInterview.validate(createInterviewTO);
//...Other
}
}
And at the end, DTO class:
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class CreateInterviewTO {
private String site;
private String candidateName;
private String candidateSurname;
private Date candidateBirth;
private String mail;
private String eduQualification;
private String candidateType;
private String interviewType;
private String enterpriseId;
private MultipartFile curriculum;
}
When I send the request, I receive the following error:
w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
UPDATE: when I sent request, curriculum DTO attribute is null.
Anyone has a solution?

Spring MVC Based Rest Services Validations for request body

I have Rest Controller in my application which has the code snippet like below:-
#RestController
#RequestMapping("/api/v1/user")
public class UserRestControllerV1 {
#PostMapping("")
public Response registerUser(#RequestBody #Valid final Request<UserDto> request,
final HttpServletRequest httpServletRequest,
BindingResult result){
Response response = new Response(request);
if(result.hasErrors()){
response.setData(new String("Error"));
}else {
response.setData(new String("Test"));
}
return response;
}
The Request Class:-
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Request<T> {
#JsonProperty(value = "co-relation-id")
private String coRelationID;
#NotNull(message = "The request body should be present")
private T data;
/*
..... various other fields
Getters / Setters
*/
}
The UserDto Class :-
public class UserDto {
#NotNull(message = "The username should not be null")
private String username;
#NotNull(message = "The password should not be null")
#JsonIgnore
private String password;
/*
..... various other fields
Getters / Setters
*/
}
Issue : I am having issues with my validations here. The field private T data in the request class gets validated but the fields inside T - in the case UserDto are not getting validated.
So I need to know the approach or code snippet to achieve this.
I have tried configuring the hibernate validator bean in the configuration but it is of no help in the scenario
#Valid constraint will instruct the Bean Validator to delve to the type of its applied property and validate all constraints found there.
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Request<T> {
#JsonProperty(value = "co-relation-id")
private String coRelationID;
//#NotNull(message = "The request body should be present")
#Valid
private T data;
/*
..... various other fields
Getters / Setters
*/
}

How to create REST endpoint service consume multipart using Spring 4.x?

I am trying to create a REST service that consumes the "multipart/form-data" with text and attachment objects. For files i can use "org.springframework.web.multipart.MultipartFile", but how do i specify the service method for Text objects?
Below is the expected client call to service.
create Rest endpoint by using this way
public void sendEmail(#RequestParam String to,#RequestParam String from,#RequestParam String cc,#RequestParam String body, #RequestParam(required = false)MultipartFile[] file){
}
or
create pojo class for strings
public class Email{
private String from;
private String to;
private String cc;
private String body;
// getters and setters
}
//email should be json string
public void sendEmail(#RequestParam String email,#RequestParam(required = false) MultipartFile[] file){
ObjectMapper mapper=new ObjectMapper();
Email email_pojo=mapper.readValue(email,Email.class);
}
Just create the controller as specified below:
#RequestMapping(value = "/uploadFiles", headers = ("content-type=multipart/*"), method = RequestMethod.POST)
public AppDTO uploadFile(UploadFiles uploadFiles, HttpServletRequest request) {
Now create a pojo class for what ever things you need to submit along with a multipartfile member where the file will bind to. refer below code for pojo
class UploadFiles
{
private String cc;
private String to;
private String from;
private MultipartFile attachment;
//create getters and setters
}
MultipartFile here used is provided by spring
import org.springframework.web.multipart.MultipartFile;
If you have more than one attachment you can use MultipartFile[] in POJO

Spring Request Mapping post vs put, same method, same logic, but

I have a 2 method:
first one create product:
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> create(#Validated ProductDTO productDTO){
productService.addProduct(productDTO);
return new ResponseEntity<>("Maxsulot ro'yhatga qo'shildi", HttpStatus.OK);
}
another one update product:
#RequestMapping(method = RequestMethod.PUT)
public ResponseEntity<?> update(#Validated ProductDTO productDTO){
productService.update(productDTO);
return new ResponseEntity<>("Maxsulot ma'lumotlari yangilandi", HttpStatus.OK);
}
Now, I am surprized that, if I sent same data post method works fine(screen1), but put(screen2) method return validation error.
screen1(post)
screen2(put)
What the problem is?
MyDTO class:
public class ProductDTO {
private Long id;
private MultipartFile file;
#NotNull
#Size(min = 2, max = 50)
private String productName;
#NotNull
private Long productPrice;
private String productInfo;
#NotNull
private Long categoryId;
private String unitOfMeasurement;
// getters and setters
}
I can see you have #Validated that should validate your request body according to JSR-303.
Seems like it is not consistent when you POST and PUT. It validates/not validating and return an error because your body does not match the validation rules you placed on ProductDTO.
In all the docs I saw you should do something like #Valid #RequestBody instead of just putting #Validated.
Try to change it to the above and see if it now work more consistently.

Multipart file and number of form parameters are not converting as ModelAttribute in Rest controller (Spring 4)

I am using Chrome postman client for rest calls, here I am sending 15 form parameters like fname, last name.. so on, and also two files as file type.
I am submitting my request POST method, body type is form data selected and content type header is empty.
In the server side, I am consume this as method
#RequestMapping(value = "/create"
method = RequestMethod.POST,
consumes = {"multipart/form-data"},
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public ResponseEntity<ResponseTO> create( #ModelAttribute RequestTO updateTripRequestTO, HttpServletRequest request);
public class RequestTO implements Serializable {
private UUID id private Date createdate;
private String createdby;
private String updatedby;
private Date updateddate;
private String visibility;
private String name;
private MultipartFile tripimage;
public class RequestTO implements Serializable {
private UUID id private Date createdate;
private String createdby;
private String updatedby;
private Date updateddate;
private String visibility;
private String name;
private MultipartFile tripimage;
( and Set and get Methods)
When I debug the TO, its giving comma separated values in TO.
If I give fname is "Test", lname "Ltest" in the postman, when I debug the TO its coming fname as "Test,Test" and lname as "Ltest,Ltest " for all form fields. Can some suggest me why like this and any solution please.

Resources