POST doesn't send data - rest

I'm using Angularjs and spring mvc 3. I have in my controller class:
#Controller
#RequestMapping(value = "/elprocesses")
public class ELProcessController {
...
#RequestMapping(value = "/elprocess", method = RequestMethod.POST)
public #ResponseBody void save(#RequestBody final Entity01 entity01,
#RequestBody final Entity02 entity02
) {
...
}
ELProcessController.js :
$scope.saveForm = function(selectedname01) {
$http.post('elprocesses/elprocess', {entity01:selectedname01, entity02:selectedname02});
...
}
it doesn't enter in my spring controller method, but when I send only one data with $http.post('elprocesses/elprocess', selectedname01);
and changing my controller class with:
#RequestMapping(value = "/elprocess", method = RequestMethod.POST)
public #ResponseBody void save(#RequestBody final Entity01 entity01)
this works fine,
What am I doing wrong to send entity01 and entity02?

In your javascript, is selectedname02 defined anywhere?
If it is, then open up your network tab and you'll see whether or not it's sending data. The POST request has the header Content-Type: application/json by default though so make sure you're trying to get json data and not form encoded data or something. I'm not familiar with spring mvc at all so check their docs.

Related

Multipart Request bind Form(#ModelAttribute) in Spring Boot Rest API

In Spring Boot2 REST, can a Multipart Request be bound to a Form?
After executing the code below, the Multipart variable of Form is null.
Form Class:
public class UploadFrom implements Serializable {
#Data
private MultipartFile uploadFile;
}
Rest Controller:
#RestController
public class UploadController {
#PostMapping("/upload")
public void uploadFile(#ModelAttribute UploadForm form){
System.out.println(form.getUploadFile()); // --> null!!
}
}
You can do it in a different way, by using two RequestPart(MultiPart) one for UploadForm and second for File. Like this :
#PostMapping("/upload")
public void uploadFile(#RequestPart("form") UploadForm form,
#RequestPart("file") MultipartFile file,){
System.out.println(file);
}

Spring Rest API, receiving one or list of object using same URL

I want to insert one or list of object using same URL :
#RequestMapping(value = "/subject", method = RequestMethod.POST)
public #ResponseBody void addSubject(#ModelAttricbute Subject subject){
... // Inserting a subject
}
#RequestMapping(value = "/subject", method = RequestMethod.POST)
public #ResponseBody void addSubject(#RequestBody Subject[] subject){
... // Inserting all the subject in the array
}
I want to be able to do those 2 things without changing the URL of Request.
Thanks in advance

Unable to test the REST API developed with Spring Boot

I am trying to test the REST API created with Spring Boot. Following is the signature of the method:
#RequestMapping(consumes = "multipart/form-data", method = RequestMethod.POST)
public Response<String> upload(#RequestBody CsvUploadModel form) {
Following is the details of Model Object:
private char separator;
private char quoteCharacter;
private String metricName;
private String groupName;
private MultipartFile file;
//getters and setters
I have tried accessing this service using 1. chrome Postman and 2. Simple http POST form. Every time I am getting the error: 415 : Unsupported media type.
EDIT:
Following is the bean configuration for multi part bean:
/**
* Allow file uploads
*
* #return
*/
#Bean
public MultipartConfigElement multipartConfigElement() {
MultiPartConfigFactory factory = new MultiPartConfigFactory();
factory.setMaxFileSize("500MB");
factory.setMaxRequestSize("500MB");
return factory.createMultipartConfig();
}
/**
* Get the multipart resolver
*
* #return
*/
#Bean
public MultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
I tried changing #RequestBody to #RequestParam but it didn't work. Following is the request preview of postman.
POST /dev/wizard/upload HTTP/1.1
Host: localhost:10022
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="metricName"
test
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="separator"
,
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Am I missing anything obvious?
Thanks
#RequestBody CsvUploadModel form
This requires a HttpMessageConverter to be present that can read request payloads of the type multipart/form-data. Unfortunately Spring currently does not provide such a converter. There is a FormHttpMessageConverter, but that can only read simple form data (application/x-www-form-urlencoded).
In order to get your method working you should remove the #RequestBody annotation and add a parameter for the files:
upload(CsvUploadModel form, #RequestParameter(required=false) MultipartFile file)
#RequestBody is not needed for binding form data. You then have to set the file manually:
form.setFile(file);
Maybe there's a third-party converter that supports reading multipart/form-data. Neither do I use nor know any.
Try retrofit
<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>retrofit</artifactId>
<version>1.6.1</version>
</dependency>
.
import retrofit.http.Body;
import retrofit.http.POST;
public interface IRestController {
#POST("/api-name")
public Response api(#Body Request request);
}
.
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import retrofit.RestAdapter;
public class TestRestAPI {
private static final String SERVER = "http://localhost:8080";
private IRestController service = new RestAdapter.Builder()
.setEndpoint(SERVER).build()
.create(IRestController.class);
#Test
public void basicTest(){
Response response = service.api(new Request());
assertNotNull(response);
}
}

Spring multiple #ModelAttribute methods in the same #Controller

I have a page with two different forms (with two different submits) on Spring MVC 3, and I have a problem with #ModelAttribute methods. When I have two on the same controller, they are not always executed making the model to be NULL.
The code:
#Controller
#RequestMapping(value = "/session/admin/permission/{userId}")
public class PermissionController {
#Autowired
private UserManager userManager;
#ModelAttribute("passwordValidation")
private PasswordValidation getPasswordModel(){
return new PasswordValidation();
}
#ModelAttribute("user")
private User getUserModel(#PathVariable("userId") String userId){
//This is not executed
return userManager.getUser(userId);
}
#ModelAttribute("permissionsAvailable")
private PermissionsAvailable getPermissionsModel(#ModelAttribute("user") User user) {
return new PermissionsAvailable();
}
#RequestMapping(method = RequestMethod.GET)
public String adminPermission(){
return "/security/permission";
}
#RequestMapping(method = RequestMethod.POST, params="changeRoles")
public String modifyPermission(#ModelAttribute("permissionsAvailable") PermissionsAvailable permissions,
HttpServletRequest request, #ModelAttribute("user") User user,
final RedirectAttributes redirectAttributes){
//Modify something
}
#RequestMapping(method = RequestMethod.POST, params="changePassword")
public String modifyPassword(
#ModelAttribute("passwordValidation") PasswordValidation passwordValidation,
#ModelAttribute("user") User user,
HttpServletRequest request, BindingResult bindingResult,
final RedirectAttributes redirectAttributes){
return "newpage";
}
}
Don't know why, sometimes everything goes ok and every method is executed, but sometimes they are not executed.
UPDATE: I have two different controllers with the same problem so it must be an error on Spring or something I'm doing wrong.
Thanks.
The documentation doesn't mention anywhere that it's possible to use #ModelAttribute on an argument to a #ModelAttribute annotated method, like you're doing in your "getPermissionsModel()" method. It's possible that's not supported, since it's not documented as being supported. You might want to try either removing the "#ModelAttribute("user") User user" argument from your "getPermissionsModel()" method, and/or instead try just using one #ModelAttribute method to set all your model attributes:
#ModelAttribute
public void setAttributes(#PathVariable("userId") String userId, Model model) {
model.addAttribute(new PasswordValidation());
model.addAttribute(userManager.getUser(userId));
model.addAttribute(new PermissionsAvailable());
}

How can I make the communication between two web apps using UrlConnection?

I have a server web app implemented with rest services and I want to make a client web application. I have to make the communication using UrlConnection and I don't really know how to make it.
My server app looks like this:
#Controller
public class PersonController {
private PersonDs personDs;
public void setPersonDs(PersonDs ds) {
this.personDs = ds;
}
#Secured(value = { "ROLE_ADMIN" }
#RequestMapping(method = RequestMethod.GET, value = "/person/{id}")
public ModelAndView getEmployee(#PathVariable String id) {
Person e = personDs.get(id);
return new ModelAndView("person", "object", e);
}
}
Until now I have seen the result in a jsp page "person" but now I need to introduce the client app. My controller should return the data in a json format which will be sent to the client, and the client will render the information in a Html page. But how can I make the connection between #RequestMapping(method = RequestMethod.GET, value = "/person/{id}") and the client request..? What the client request url should look like?