How do get the list from #ResponseBody in JSP? - java

I use Spring MVC, I have controller with a method:
#RequestMapping(value = "/listReader", method = RequestMethod.POST)
public #ResponseBody
List<Reader> getListReader(ModelMap model) {
return libraryService.getAllReaders();
}
But I do not know:
How can use list (that I get from method getListReader by #ResponseBody) in JSP?
How can I get list in JSP?
How do to display a list in JSP-page?
How do to get the list from #ResponseBody in JSP?
Give an example, please.

You can't. #ResponseBody is basically telling Spring: take the object I (method) return and use any serializer you have that supports it and write it directly to the body of the HTTP response. There's no JSP involved here.
Instead you should add the list to the model and return the String view name of your JSP.
#RequestMapping(value = "/listReader", method = RequestMethod.POST)
public String getListReader(ModelMap model) {
model.addAttribute("someKey", libraryService.getAllReaders());
return "my-jsp";
}
then you can use EL in the JSP to retrieve it
<h3>${someKey}</h3>
Use JSTL to iterate over it.

#RequestMapping(value = "/listReader", method = RequestMethod.POST)
That defines an Endpoint.
I would suggest using RequestMethod.GET than RequestMethod.POST, since you want something from the server not POSTING something to the server.
On the other Hand, if you want to use that information on a JSP, there are two ways:
1) Some view could consume that information via a http-GET-Request like $.get in jQuery or ajax. After you got the data, you can insert it in your HTML
2) Instead of using ajax you could display it directly on the page.
Then, you have to put your List into a Model, which you can acces on your JSP with Expression Language. Then you have to remove the #ResponseBody and return an according view instead.

Related

JQuery stringify not working

Simply, I'm trying to parse a List of composite objects passed from Spring controller via ModelAndView object as the following
Spring part
ModelAndView view = new ModelAndView("my view");
List<ActionHistory> histories = myService.getListData();
view.addObject("histories", histories);
return view;
In Jquery i tried couple of alternatives, first used the below line to construct JSON from List:
var list = JSON.stringify('${histories}');
console.log(histories);
the console is returning
"[com.companyname.projectname.domains.ActionHistory#48126327]"
TypeError: invalid 'in' operand a
I also tried from jquery-json by including "jquery.json.min.js" as a suggestion from this topic discussed but getting the same error above Serializing to JSON in jQuery
var histories = $.toJSON('${histories}');
console.log(histories);
Check you contentType in ajax function it should be.
contentType: "application/json"
Also your Spring controller which is handling this mvc call should configure be configired with
produces=MediaType.APPLICATION_JSON_VALUE
e.g. something like
#RequestMapping(value ="/getList", method= RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)

Pass form data from Spring Controller to an external endpoint

My issue:
Having a form in a simple HTML, with action="/myController".
I need to send the form data to my Controller and from there I need to make another POST to an external Controller.
<form method="post" action="/myController">
<textarea name="data"></textarea>
</form>
And my Spring Controller looks something like this:
#RequestMapping(method = RequestMethod.GET, value = "/myController")
#ResponseBody
public String myController(#RequestBody MultiValueMap<String, String[]> formData) {
RestTemplate rest = new RestTemplate();
ResponseEntity<String> response = rest.postForEntity("urlPath", formData, String.class);
String manipulatedResult = manipulateResult(response.getBody());
return manipulatedResult;
}
I need to pass form data, to my controller, it should send form data further to the "urlPath" and recieve a response. I need to manipulate that response and return a result.
My question is, how to send the form data further, without manipulating the request?
Thanks in advance.
Your Response doesn't need to be a String it can be a well formed java object. In this case i do not see any issue returning ResponseEntity object without converting this into String.
#ResponseBody will convert returned java object to JSON/Xml based response to outside world.
you can use ModelAndView class.
Refer the following link: http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/web/portlet/ModelAndView.html

Spring MVC controller view

Hey guys, I have a list to be displayed on a view JSP page from the controller side. What do I return from the modelandview function if I want the list to be displayed in the same view page I am calling it from?
Here is the jQuery which i use to call the controller
$("#customerList").on("keydown",function(){
$.ajax({
url: '/omp/customer',
type: 'GET'
});
});
});
Here is the controller code
#RequestMapping(method= RequestMethod.GET)
public ModelAndView getlist(Model mod)
{
System.out.println("I am here");
CustomerDetails details = new CustomerDetails();
details.setAl();
mod.addAttribute("lists",details.getAl());
return new ModelAndView("dashboard/home");
}
It looks like you want to make an Ajax call to the server and retrieve a list.
Ajax calls are asynchronous and don't require to load a new page.
My advise is that the controller should return the list in JSON format and some
javascript should parse and display it.
Have a look at #ResponseBody annotation in the Spring MVC documentation.

Spring MVC and Request Attributes

I think the original question was confusing.
I have a HashMap that needs to be a Collection from a database that I'd like to send to a view via a Spring Controller. I don't want to put this HashMap in the model.addAttribute() because the Spring Model object returns a Map and my JSP needs the collection to be a Collection<Object>. If I set my HashMap.values() in a request.setAttribute, how do I go about dispatching that request variable to the view if my method is returning a String?
#RequestMapping(method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest request) {
model.addAttribute("surveys", mySurveys); //this is a map and I need a Collection<Object>
//So I'd like to do this, but how do I get to the "evaluations" object in a view if I'm not dispatching it (like below)??
request.setAttribute("evaluations", mySurveys);
//RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
//rd.forward(request, response);
return "home";
}
EDIT: The Spring Tag library cannot be used for this particular usecase.
Thanks.
If mySurveys is a Map, then perhaps you can put mySurveys.values() into the ModelMap instead of mySurveys (Also, are you intending to use a ModelMap instead of a Model?)
In the code below, surveys would be a Collection of Objects and would be accessible in the jsp via ${surveys}
#RequestMapping(method = RequestMethod.GET)
public String home(ModelMap modelMap, HttpServletRequest request) {
Map<String,Object> mySurveys = getMySurveys();
modelMap.addAttribute("surveys", mySurveys.values());
return "home";
}
I think you're confused as to what ModelMap is.
You can annotate whatever variable you want to access in the view by #ModelAttribute and Spring will automatically instantiate it, and add it to the ModelMap. In the view, you can use it like:
<form:form modelattribute="myAttribute">
<form:input path="fieldInAttribute">
</form:form>
Hope this answers your question

Access Model object in a JSP without using the ModelAndView object?

I am using spring mvc with Annotations, see the following snippet
#RequestMapping(value = "/configuration/", method = RequestMethod.GET)
public MyModel viewConfiguration() {
The problem I am having accessing the 'MyModel' class in my JSP.
How can I do this, without using the ModelAndView object?
This shorthand syntax means that MyModel becomes a model attribute named myModel (i.e. class name with the first letter decapitalized).
View name is inferred from the URL.
See also:
15.3.2.3 Supported handler method arguments and return types
15.10.3 The View - RequestToViewNameTranslator
You could set MyModel as a request attribute to be accessed in your JSP. I'm curious, why don't you want to use ModelAndView? After all, it does what you want to do here, which displays the view and provides a container to hold your objects you want to reference in your view.
By the way, if this is an Ajax call, you will need to add #ResponseBody to the API so that your javascript can read the response in the callback function:-
#RequestMapping(value = "/configuration/", method = RequestMethod.GET)
public #ResponseBody MyModel viewConfiguration() {
...
}

Categories

Resources