JQuery stringify not working - java

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)

Related

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.

How do get the list from #ResponseBody in JSP?

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.

spring json writes more json then i want

I am using the json spring view in order to return a simple JSON object from my controller.
The problem is that its returning more data then i want. it is returning the validation errors and things inside of my model when all i am doing is this in the controller:
Map model = new HashMap()
model.put("success", "true");
return new ModelAndView("jsonView", model);
If you look at the bottom of this page in the docs it looks like i am getting back data that POST would return. i am not doing a post, i am doing a GET by going directly to the URL with params.
How do i get this lib to return just the data in my model?
We have used this library and it has worked as expected. Could you try with the following variation of the above code to see if it works? We use this in some places...
ModelAndView modelAndView = new ModelAndView("jsonView");
ModelMap map = modelAndView.getModelMap();
map.addAttribute("success", "true");
return modelAndView;

Parsing json into java objects in spring-mvc

I'm familiar with how to return json from my #Controller methods using the #ResponseBody annotation.
Now I'm trying to read some json arguments into my controller, but haven't had luck so far.
Here's my controller's signature:
#RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(#RequestParam("json") #RequestBody SearchRequest json) {
But when I try to invoke this method, spring complains that:
Failed to convert value of type 'java.lang.String' to required type 'com.foo.SearchRequest'
Removing the #RequestBody annotation doesn't seem to make a difference.
Manually parsing the json works, so Jackson must be in the classpath:
// This works
#RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(#RequestParam("json") String json) {
SearchRequest request;
try {
request = objectMapper.readValue(json, SearchRequest.class);
} catch (IOException e) {
throw new IllegalArgumentException("Couldn't parse json into a search request", e);
}
Any ideas? Am I trying to do something that's not supported?
Your parameter should either be a #RequestParam, or a #RequestBody, not both.
#RequestBody is for use with POST and PUT requests, where the body of the request is what you want to parse. #RequestParam is for named parameters, either on the URL or as a multipart form submission.
So you need to decide which one you need. Do you really want to have your JSON as a request parameter? This isn't normally how AJAX works, it's normally sent as the request body.
Try removing the #RequestParam and see if that works. If not, and you really are posting the JSON as a request parameter, then Spring won't help you process that without additional plumbing (see Customizing WebDataBinder initialization).
if you are using jquery on the client side, this worked for me:
Java:
#RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(#RequestBody SearchRequest json) {
Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):
$.ajax({
type: "post",
url: "sync", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(jsonobject), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(){
alert('failure');
}
});

Categories

Resources