Iterable object as parameter in spring data rest api - spring

Hi I need to pass a json object in POST request of the SPRING DATA REST. Is it possible to pass directly and make it process with save(iterable) with any Jackson script or we have to use a Controller with #RequestBodyand process the Iterableand save it using repository function??
Now I am doing,
#RequestMapping(value = "batchInsert", method = RequestMethod.POST)
#ResponseBody
public String batchInsert(#RequestBody List<Test> test){
testRepo.save(test);
return "loaded";
}
and implements Serilizable in DAO objectand my doubt whether there is any default format to pass whole json without using any controller as CRUD operates normally. Please help me find solution. Am new to springs and I am unable to use the same url to get request in spring-data-rest API, if I use batchInsertin controller and in rest api. Fortunate to use different api calls now for inserting and searching purpose. Thanks in advance.

Have you tried specifying the consumable media type?
#RequestMapping(value = "batchInsert", method = RequestMethod.POST, consumes="application/json")
It's quite common to pass JSON objects to Spring controllers, so it should work...

Related

How do I test form submission with Spring MVC test?

Most of my experience with creating controllers with Spring are for REST controllers that consume JSON formatted requests. I've been searching for documentation on how to do testing for form submission, and so far this is how I understand it should go using MockMvc:
MvcResult result = mockMvc.perform(post("/submit")
.param('title', 'test title')
.param('description', 'test description'))
.andReturn()
However, I'm not sure how to map the form parameters to a model object. I've seen the #ModelAttribute annotation pop up in my searches but I can't figure out how it should be used for mapping. In addition, this quick start guide from the official documentation does not elaborate on how things like th:object and th:field translate to HTML and subsequently to URL encoded form.
I have my controller code similar to the following:
#PostMapping('/submit')
def submit(#ModelAttribute WriteUp writeUp) {
//do something with writeUp object
'result'
}
I discovered through trial and error that my specific problem might have been Groovy specific. There test code and the controller code, it turns out, have no issues. To reiterate, for testing form submission, use the param method through perform method of MockMvcRequestBuilders. Another thing to note is that this doesn't seem to work if content type is not specified. Here's a sample test code that works for me:
MvcResult result = webApp.perform(post("/submit")
.contentType(APPLICATION_FORM_URLENCODED) //from MediaType
.param('title', 'test title')
.param('description', 'test description'))
.andReturn()
As you can see, it's not much different from what I posted originally. The controller code is pretty much just the same, with #ModelAttribute working just fine.
The problem with my setup though was that since I was using Groovy, I assumed that getters and setters were automatically generated in my WriteUp class. Here's how the WriteUp class looked originally:
class WriteUp {
private String title
private String description
}
I haven't written code in Groovy for a while, and the last time I did, classes like the one above can be assumed to have getters and setters implicitly. However, it turns out that is not the case. To solve my specific issue, I updated the access modifier in the fields to be default (package level):
class WriteUp {
String title
String description
}
I've seen the #ModelAttribute annotation pop up in my searches but I
can't figure out how it should be used for mapping.
When you mark your writeUp object with #ModelAttribute, then the Spring container populates the parameters (like title, description, etc..) from HttpServletRequest object & injects the object to the controller method, when the request comes to the server from the client (could be a Browser or MockMvc unit test client or anything else).
Also, few other basic points for your quick understanding:
(1) Controller methods are mapped to an URI and RequestMethod (like POST/GET/DELETE/PUT et..) like shown below:
#RequestMapping(value="/submit", method=RequestMethod.POST)
public String submit(#ModelAttribute WriteUp writeUp) {
//Call the service and Save the details
model.addAttribute("Writeup details added successfully");
return "writeUpResult"; //Returns to the View (JSP)
}
(2) #ModelAttribute will be mapped to an object (like your writeUp) for http POST/PUT requests where the html formd data is part of http body.
(3) #RequestParam or #PathParam will be used for http GET requests where the parameters are part of URL (i.e., not part of http body).
You can look here for understanding the DispatcherServlet request handling & Spring MVC basic web flow.

Spring ROO - To get value in java class

I have created Spring ROO application using below link in Eclipse.
http://www.cubrid.org/blog/dev-platform/spring-roo-fast-java-application-development-tool/
In this i am having a controller named BookController which is having #RequestMapping("/book"). This works fine but When i want to get data from textfield to java class i am not getting by moving this RequestMapping to method level.
The actionURL of page is = /SPringDemo/book
When i am moving this to method level like this
#RequestMapping(value = "/book")
public String gettingData(Book book) {
System.out.println("Book is = " +book.getName());
return null;
}
This is not performing opeartion
Spring web mvc try to match request with methods. This include parameters required. In your request definition you ask for a Book instance but, if Spring can locate any parameter or model attribute which make matching to definition, your method will not be invoked.
Check this example which is similar to your case.
Good luck!

How to troubleshoot spring mvc mapping issue?

I have a simple Spring program, the backend is Spring MVC with Restful web service, the front end is pure HTML + ajax.
My problem is, when I try to use the following to map a HTTP request params to a pojo, it always fails:
#RequestMapping(value = "/books", method = RequestMethod.PUT)
public #ResponseBody
String updateBook(BookInfo book)
Here I use PUT method, because it's a modification operation. There's no exception, but I get nothing injected into book object.
With same HTTP request parameters, if I change the method to POST, and client send it via a POST, it would be success:
#RequestMapping(value = "/books", method = RequestMethod.POST)
public ResponseEntity<String> addBook(BookInfo book)
This time book will always get the filled.
Why there's difference between PUT and POST? or it's the issue of return type? (one is ResponseBody, the other is ResponseEntity)? Or, if you use PUT, then the pojo must be in persistent context?
How should I investigate the issue?
I think its not the problem with your configuration or code.
In Spring Framework there is a filter provided named HiddenHttpMethodFilter that serves all the method but initially it will do the POST request but with a hidden _method form field. And this filter reads this hidden field value and then changes the method value accordingly. Please refere this link to know more about this. I think configuring with this filter will resolve your problem.
Hope this helps you. Cheers.

Uriinfo for PUT method

I am using Urinfo for accessing query parameters in my restful web service as follows
#GET
#Produces("text/plain")
#Path("/association")
public Response Association(
#Context UriInfo uriInfo){
String clinicianId = uriInfo.getQueryParameters().getFirst("clinicianId");
List<String> providerList = uriInfo.getQueryParameters().get("clinicialProviderId");
How to access Parameters for PUT metod using uriinfo.
The same way.
Perhaps I don't understand the question. Query parameters are accessed the same way regardless of the HTTP method. Are you talking about different parameters for PUT? Do you mean Form fields? If you are sending form data in your PUT request and you want to access that, you can use #FormParam to inject them into your method parameters or fields. Btw, there is also #QueryParam you can use to inject query parameters instead of using UriInfo.

Handling JSON and form data request with Spring MVC

I'm working on simple Spring-MVC application and I love new Spring REST features. I'd like to use the same method to process regular form and JSON data. It seems to be a little tricky, however. For example, method
public #ResponseBody String process(#RequestBody Bean bean);
will work for JSON request (Content-type: application/json), and
public #ResponseBody String process(Bean bean);
will match request with Content-type: application/x-www-form-urlencoded.
These methods are obviously will have almost the same content, so I'd prefer to avoid such duplication. With Jersey it's possible with #Consumes annotations, but I can't figure out how to do it with Spring.
First, the above declaration won't compile, because you are having duplicate signature.
Btw, #Consumes wouldn't help, I think, because it only designates what content type the method can handle.
In spring you can specify the content-type with
#RequestMapping(headers="Content-Type=application/json")
Just add #RestController annotation for the controller class.

Resources