what is use case of #ResponseBody in Spring MVC - spring

what is the usage of #ResponseBody in Spring MVC?
Because Can't I access that without that?
#RequestMapping(value = { "/employees" }, method = RequestMethod.GET)
public #ResponseBody ResponseEntity<JSONObject> employees( #SessionAttribute("emp") Employee emp, Model model ) {

The #ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

Related

redirect from get method to post method in spring controller

I have a link retailerId after clicking the link control will go to the below controller:
#Controller
#RequestMapping(value = "/auth/adminsearchowner")
public class AdminSearchOwnerController {
#RequestMapping(value = "/retailerId/{retailerId}",method = RequestMethod.GET)
public ModelAndView viewRetailerInfo(
#PathVariable("retailerId") String retailerId,
#ModelAttribute EditRetailerLifeCycleBean editLicenseBean) {
editLicenseBean.setSelectedIDsString(retailerId);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("editLicenseBean",editLicenseBean);
modelAndView.setViewName("redirect:/auth/adminlicense/viewlicense");
return modelAndView;
}
}
where /auth/adminlicense/viewlicense is in another controller and we have both GET and POST method for this /auth/adminlicense/viewlicense request mapping. I want to call the post method from the earlier controller.
#Controller
#RequestMapping("/auth/adminlicense")
public class AdminViewLicenseController {
#RequestMapping(value = "/viewlicense", method = RequestMethod.GET)
public ModelAndView searchRetailerLicense(
#ModelAttribute("editLicenseBean") EditRetailerLifeCycleBean editLicenseBean,
HttpSession session) {
}
#RequestMapping(value = "/viewlicense", method = RequestMethod.POST)
public ModelAndView getLicenseDetails(
#ModelAttribute EditRetailerLifeCycleBean lifeCycleBean,
HttpSession session) {
}
}
but it is going to GET method. Could you tell me the solution?
There is no solution. A redirect cannot cause a POST to be sent by the browser.
Rethink your design.
Try:
modelAndView.setViewName("forward:/auth/adminlicense/viewlicense");
instead of
modelAndView.setViewName("redirect:/auth/adminlicense/viewlicense");
A design in which you are trying to send some data from one controller(server-side) to another(server-side) via user's browser(client-side) is probably not the best idea, anyway.
Hope it helps!

Why Spring REST do not analyze "get","post" methods with same url

I am using spring rest , I have two methods
#RequestMapping(value="/",method = RequestMethod.POST)
public #ResponseBody
Object test1(HttpServletRequest request) {}
#RequestMapping(value="/",method = RequestMethod.GET)
public #ResponseBody
Object test2(HttpServletRequest request) {}
But it is not able to detect the two methods. Is it necessary that the URL should be different for each http method in spring.
Spring can support GET and POST for the same url. I've done it many times. For example (this is POST and PUT, but it's the same difference):
#Controller
#RequestMapping(value="player")
public class PlayerController {
#Autowired
private PlayerService playerService;
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public Player createNewPlayer(#RequestBody Player player) {
return playerService.createNewPlayer(player);
}
#RequestMapping(method = RequestMethod.PUT)
#ResponseBody
public Player updatePlayer(#RequestBody Player player) {
return playerService.updatePlayer(player);
}
}
If you can post the error message you're getting, maybe we can help you figure out what's wrong.
I am bit late but i might be useful for someone who still wants to know this concept. In below code we will be getting the error: java.lang.IllegalStateException: Ambiguous mapping.Cannot map 'XXX' method.
#RequestMapping(value="/",method = RequestMethod.POST)
public #ResponseBody
Object test1(HttpServletRequest request) {}
#RequestMapping(value="/",method = RequestMethod.GET)
public #ResponseBody
Object test2(HttpServletRequest request) {}
this error occurs because RequestHandlerMapper delegates the request on the basis of pattern of URL only and not on the method type.Hence if we have the same URL pattern, handlermapping will fail to distinguish that to which method it should map because of ambiguity.

Passing json object to spring mvc controller using Ajax

I am trying to send a json via Ajax request to a Spring mvc controller without success.
The json string has the following form:
{"Books":
[{'author':'Murakami','title':'Kafka on the shore'},{'author':'Murakami','title':'Norwegian Wood'}]}
The controller that parses the json wraps it through this java bean:
class Books{
List <Map<String, String>> books;
//...get & set method of the bean
}
The controller method has the following form:
#RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/checkBook.do")
public ModelAndView callCheckBook(
#RequestBody Books books){....}
Unfortunately this does not work, I get the following error when invoking the method:
"Null ModelAndView returned to DispatcherServlet with name..."
Where am I getting wrong?
Thank you in advance!
Regards
create a Model class
class Books
{
private string author;
private string title;
// gets and sets
}
And Also create Wrapper class like this
class BookWrapper{
private List<Books> Books; // this name should matches the json header
}
Now in controller
#RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/checkBook.do")
public ModelAndView callCheckBook(
#RequestBody BookWrapper Books){....}
in Ajax call create a seralizeArray of you forum this will give you json object and then it will bind to the wrapper class

how to use #Requestparam #RequestBody together in spring restful

how to use #Requestparam #RequestBody together in spring restful
#RequestMapping(method = RequestMethod.POST, value = "/upate")
#ResponseBody
public ModelAndView availableCheck(
#RequestParam("key") String key, #RequestBody User user)
throws Exception {
//handle
//
}
I want to update user by unique key,so I need request key paramer and the new user json object.
Advance thanks!
There is some possible mistake: if you return a ModelAndView then it is highly unlikely that you want to be it the ResponseBody, therefore remove #ResponseBody.
The other problem is that RespondeBody is for strings. It mean put the Body string in this variable.
So it your user is the command object populated by some form, then just remove the #RequestBody annotation
#RequestMapping(method = RequestMethod.POST, value = "/upate")
public ModelAndView availableCheck(
#RequestParam("key") String key, User user)
throws Exception {
//handle
//
}

Spring MVC to Spring REST tutorials misunderstanding

I have developed a Spring MVC - Hibernate application as told here.
Now I am trying to modify this code to create a REST application as told here.
I have added Jackson library to the classpath and added #XmlRootElement.
#XmlRootElement(name = "persons")
public class Person implements Serializable {
But if I do a application/json request then I still get the html code back.
What I am doing wrong / forgot to do?
My controller:
#RequestMapping(value = "/persons", method = RequestMethod.GET)
#ResponseBody
public String getPersons(Model model) {
logger.info("Received request to show all persons");
// Retrieve all persons by delegating the call to PersonService
List<Person> persons = personService.getAll();
model.addAttribute("persons", persons);
return "personspage";
}
Changed the Controller, but get an error:
t
ype Status report
message /Buddies/WEB-INF/jsp/main/persons/1.jsp
description The requested resource (/Buddies/WEB-INF/jsp/main/persons/1.jsp) is not available.
Your controller should look like this:
#RequestMapping(value = "/persons/{id}", method = RequestMethod.GET)
#ResponseBody
public Person getPerson(#PathVariable int id) {
Person person = personService.getPersonById(id);
return person;
}
If you want to return a list of Person objects, you need an extra wrapper object, see: Using JAXB to unmarshal/marshal a List<String>.
You are probably missing AnnotationMethodHandlerAdapter and messageConverter in your spring configuration.

Resources