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
Related
I have a feign client that uses a dto to perform the request using #RequestBody. The problem is that some property does not match with the java standards, for example id_client. Is there a way to change the variable name and keep it working with the feign ?
Below there is the code of the feign client the dto used in the request body.
#FeignClient(name="sso-token", url = "http://keycloak.com.br:8180", path="/")
public interface SsoTokenQueryWebAdapter {
#PostMapping(value = "/auth/realms/real-refrigerantes/protocol/openid-connect/token", consumes = "application/x-www-form-urlencoded")
public String recuperarToken(#RequestBody RequestTokenDto dto);
}
#Data
public class RequestTokenDto {
private String username;
private String password;
private String client_id;
private String client_secret;
private String grant_type;
}
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.
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
*/
}
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.
I am developing webservice which contain some information with image , for example , develop webservice which contain user information with photo. I want this done by POST request. How can I achieve this?
I want to store only image path in database.
What changes should i make in controller to retrive image from mobile and store it in database? I am taking UserInfoTemp object as request body.
To developing webservice I am using Spring MVC 4.0.3.Release.
Here is my code please review it:
#Entity
public class UserInfoTemp
{
#Id
#GeneratedValue
#Column(name="UserId")
private Long id;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="Email")
#JsonProperty(value="email")
private String email;
#Column(name="Phone")
private String phone;
#Column(name="ProfilePicLink")
private String profilePicLink;
#Column(name="ProfilePicThumbnailLink")
private String profilePicThumbnailLink;
//getter setter
}
Controller:-
// for registering user
#RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<Object> register(#RequestBody UserInfoTemp userInfoTemp)
{
try
{
userInfoService.save(userInfoTemp);
return new ResponseEntity<Object>(userInfoTemp, HttpStatus.CREATED);
}
catch(Exception e)
{
Message message = new Message();
message.setStatus(false);
message.setMessage("User information can not be null");
return new ResponseEntity<Object>(message, HttpStatus.CREATED);
}
}