SpringBoot + Thymeleaf - upload MultipartFile in form - spring

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?

Related

How to post an Image and JSON object with single request to back end Spring Boot

I want to send image and JSON data to my back end in Spring Boot.
This is my method:
#PostMapping
public void uploadFile(#ModelAttribute FileUploadDto fileUploadDto) {
My FileUploadDto model:
public class FileUploadDto {
private MultipartFile file;
private CategoryModel category;
My CategoryModel model:
#Entity
#Table(name = "Category")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class CategoryModel {
#Id
#Column(name = "id")
//#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String category_name;
private String category_description;
private String image_path;
#JsonIgnore
#OneToMany( mappedBy = "category")
private Set<ProductModel> category;
I do not understand where I'm wrong.
My postman request:
Your payload has to be raw and in json form. Something like this would help Spring boot to convert your payload into a object of an example class:
public class Foo{
public String foo;
public String foo1;
//Getters setters
}
And the request handling method:
#PostMapping
public void uploadFile(#RequestBody Foo foo)
It is also recommended to parse the payload into some a temporary class and then convert objects of the temporary class into the Entity class and vice versa. Take a look at: https://struberg.wordpress.com/2012/01/08/jpa-enhancement-done-right/ for more information
Also, if you want to upload file per REST I also recommend you to take a look at the following documentation: https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/
Best luck.

Response Entity not getting mapped for custom objects inside a class

I am hitting an API and getting the response using resttemplate.exchange object and i am mapping the response to a parameterized object .All the variables inside the response class are getting mapped to the response entity object but not the Attribute class variables inside the parameterized object.
ResponseEntity<ArrayList<Response>> responseEntity =
restTemplate.exchange(
builder.toUriString(),
HttpMethod.GET,
new HttpEntity<>(headers),
new ParameterizedTypeReference<ArrayList<Response>>()
{});
#Getter
#Setter
public class Response {
private String number;
private String id;
private String name;
#JsonProperty("attributes")
private ArrayList<Attributes> attributes ;
}
#Getter
#Setter
#JsonIgnoreProperties(ignoreUnknown=true)
public class Attributes {
private String value;
private String name;
}

Spring 4.1.7 validate request body

I know this issue has been around there in other post, but after applying the fiux suggested was not working.
I am using spring 4.1.7 version, i want to validate the RequestBody from post rest call. For doing this i tried following set of codes, but it was not working as i expected.
My Request body pojo classes.
ParentPojo.class
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Builder
#ToString
#Validated
public class ParentPojo<T> implements Serializable{
#NotNull
private String cNumber;
#NotNull
private String statusCode;
#NotNull T child;
}
ChildPojo.class
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Builder
#ToString
#Validated
public class ChildPojo{
#NotNull
private String name;
#NotNull
private String address;
#NotNull
private String pin;
}
Controller:
Adding only methods
#Autowired
#Qualifier("validator")
private Validator validator;
#InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
#RequestMapping(produces = { "application/json", "application/xml" }, consumes ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = { RequestMethod.POST })
#ResponseStatus(HttpStatus.CREATED)
public Messageresponse<ChildPojo> create(#NotNull(groups = {ParentPojo.class, ChildPojo.class})
#Valid #Validated({ParentPojo.class, ChildPojo.class}) #RequestBody final ParentPojo<ChildPojo> ParentPojo, BindingResult bindingResult) {
System.out.println("new version 8="+bindingResult.hasErrors());
validator.validate(ParentPojo, bindingResult);
if(bindingResult.hasErrors()) {
System.out.println("Non formated form stuff.");
}
return service.create(ParentPojo);
}
#RequestMapping(value = "/{create}", produces = { "application/json", "application/xml" }, consumes ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}, method = { RequestMethod.POST })
#ResponseStatus(HttpStatus.CREATED)
public Messageresponse<ChildPojo> create1(#NotNull #Valid #RequestBody final ParentPojo<ChildPojo> ParentPojo, BindingResult bindingResult) {
System.out.println("new version 8="+bindingResult.hasErrors());
validator.validate(ParentPojo, bindingResult);
if(bindingResult.hasErrors()) {
System.out.println("Non formated form stuff.");
}
return service.create(ParentPojo);
}
application context xml:
<mvc:annotation-driven validator="validator">
</mvc:annotation-driven>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
jar file tried:
hibernate-validator-4.3.0.Final
hibernate-validator-4.1.0.Final
hibernate-validator-4.0.2.GA
validation-api-1.1.0.Final
spring-context-4.1.7.RELEASE
But nothing was working with all the above combination for the request below:
in below request "pin" is missed and the controller method #Valid #RequestBody expected to handle this request as Bad Request. instead it is accepting the request body and processing further.
{
"cNumber" : "ff",
"statusCode" : "ddd",
"child" : {
"name" : "ll",
"address" : "ll"
}
Look at this question Here
You need to decorate the child pojo as #Valid
public class ParentPojo<T> implements Serializable{
#NotNull
private String cNumber;
#NotNull
private String statusCode;
#Valid
#NotNull
T child;
}

Spring boot url configure with data and multipartfile

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.

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
*/
}

Resources