I want to pass a preformed JSON string from a Spring MVC controller method using the ModelMap.addAttribute or put method. I have some data that needs to be loaded when the page renders. I do not want to send a Java object list and then have to unpack it with Javascript into JSON. The problem is that ModelMap.addAttribute or ModelMap.put seems to convert the JSON string back into the Java objects.
When I inspect the added attribute in the JSP I get things like:
[foos.web.FOOSController$foosDataHolder#63eef378,foos.web.FOOSController$foosDataHolder#5f395275]
In controller:
model.put("foosData", jsonFoosString); // can I just pass a string here?
In JSP:
var foosData = "${foosData}";
Then the JSON parser in the browser cannot parse foos.web.FOOSController$foosDataHolder#63eef378 and says that '#' is an invalid character, which it is.
Thanks for any suggestions for this Spring MVC novice.
I know that I could do an ajax method and get the JSON string back, or unpack an object array in the JSP, but I want this to be fast.
Related
Hello i am looking if i can handle with only one RestController method multiple params...
with controllers method it could be done... but i couldnt find project with 2 like that.
#PostMapping(value ="upload")
public upload(#RequestParam MultipartFile file,#RequestParam List<String> myParams ){
some code here ....
return;
}
I am just wondering if is also a good practise ... having two deferent type of objects in same controller and if its possible,,, any idea????
Simple answer: Yes, that's possible.
But as you asked for good practice, here's some context:
It is very helpful to understand how HTTP actually transports data.
If your request uses GET as request method, parameters are added to the URL as a query string. That could look like this: http://example.com/index?param1=value1¶m2=value2
In this case, Spring maps the key-value pairs from the query string to your method arguments. But this will only work for text.
If you're using POST, the data is sent inside the request body. How that is encoded depends on the media type of your data. For example, the default media type application/x-www-form-urlencoded would encode the data to the same query string as above.
If you want to upload mixed-type form data like a file/blob along with some textual parameters, your data should be encoded with multipart/form-data.
As long as the request body contains a key-value format, Spring Boot will still be able to distinguish and map the parameters via #RequestParam (If the keys don't differ from your attribute names, you don't even need to assign a name to the value attribute).
I highly recommend you to take a look at the #RequestBody and #RequestPart annotations as i think it often is best practice to use a model class (DTO) for the whole request body (or rather the form, semantically), especially if there are a lot of parameters to process.
You will need to specify the names of the variables.
#PostMapping(value ="upload")
public upload(
#RequestParam(value = "file") MultipartFile file,
#RequestParam(value = "myParams") List<String> myParams
){
some code here ....
return;
}
I understanding how the Model and Controller sections of the MVC pattern and [Spring MVC][1] work.
However, I am not sure on the View.
E.g.: If I want to send data back when my Rest end point is hit e.g. users/{user}, if I send back a JSP/ThymeLeaf page or a, how does it work?
Is the view response sent by the controller?
How is JSP different from sending a JSON response?
The view is the rendered string output. So in general you could say that there is no difference between the JSP output and JSON since both are just string responses which get interpreted by the client. But normally JSP is used for output html sites(Java Server Pages, Html rendered/generated by the server) and JSON to deliver pure data in an object structure.
The controller(in MVC general) is the middleware between model and view, so when the view gets an input the controller digest the events and manipulate the data and also when the model changes the controller triggers the gui to update.
Since the html/web world is a bit different(request->response) the Spring-MVC controller is getting the user input and triggers the rendering of the output string. So you could say the controller is delivering.
The controller is the one who changes things while the data and view are static without it.
I am going to write about tiles and spring mvc. Mvc controller will react on your url like if you send request by localhost:8080/ myapp/classroom/hellostudent.html then spring controller will take /hellostudent.html and remove .html from url and match your string in tiles.xml file.
And about json so Spring mvc comes up with json api you have to use#Responsebody to send json object to client side.
I am getting a JsonObject that i need to return it as a raw json in spring mvc in the controller.
Using #ResponseBody doesn't work. So it's either i fix in the controller or i render it in a jsp , so any idea about any of these 2 solutions?
Note that i don't always know the type of the object returned in the json
Are you able to return String? If so, use Json encoder and decoder. For example, JSON-lib.jar can be used to do these.
Here are few links that will help you
Returning JsonObject using #ResponseBody in SpringMVC
Spring configure #ResponseBody JSON format
I am calling the controller from a plane jsp page with out form submit using ajax and I want to return a hashmap from controller to the jsp page which i can iterate to show the values of hashmap.
If I am sending a message in the response , I can get that in the ajax function inside success: but how to get the whole map. Because if you even set in the request attribute you can't get that in the jsp page.Kindly help.
Use #ResponseBody annotation on your controller's method. For e.g.:
#RequestMapping(value = "/yourAjaxRequestUrl", method = RequestMethod.POST)
public
#ResponseBody
Map<String, Object> performOperation(#RequestParam("someParam") String someParam) {
//Do something
return Collections.<String, Object>singletonMap("yourObject", yourObject);
}
This will return you an object in JSON format, all objects in your map then can be accessed via javascript.
I think you're confusing your server-side code with your client-side code. AJAX is client side, JSPs are server side. You just cannot pass data between the two.
When you're making your AJAX call, the JSP has already finished execution, and the markup it produced is there in the browser, including your AJAX code.
If your Spring Controller is returning JSON (maybe you're representing your Map as a JavaScript associative array), then you can use jQuery to iterate over that array and create dynamic HTML elements according to its contents.
I have a form controller.Form element is a drop down box.
For eg there is user name form element.if user select his name .I want the children names to be loaded for particular user.
I have List getChildernByUser(User user);
Please would like to know how this can be made using jquery or ajax.If user is selected in next form element he gets all his children to select .
In the server side, I'd use a controller method like this:
#RequestMapping("/users/{userId}/children")
public #ResponseBody List<User> getChilden(#PathVariable String userId) { ... }
More info in this kind of controller methods can be found in the Spring reference doc. You'll also need the Jackson libraries in your /lib folder for Spring MVC to convert the bean to JSON.
Then, in your client code (HTML) you can use the getJSON() function to make an Ajax call and get a List of users in JSON format.
Good luck.