Spring MVC: How to respond a http request with JSON object and view together? - json

It's like user click a link and in the Spring controller class a method will respond to the request with a JSON object and also a view name (meaning, it should return but not only a JSON object but also a HTTP view which hold that JSON object, so #ResponseBody may not enough)? Do we have to split it up into two methods (one for view and the other for JSON object)? Any ideas will be appreciated.
Normally we have
#RequestMapping(value="/someValue")
public #ResponseBody someMethod1(#RequestParam String param){
.....
return someJSONObject
}
To handle JSON object, and
#RequestMapping(value="/someValue")
public String someMethod2(#RequestParam String param){
.....
return someViewInString;
}
To return the view.
How can we combine them together?

You should return the view with a placeholder for the JSON.
In the controller code, create the JSON programatically, convert it to String format and then put it in the model (let's call it json_string)
In the view there should be a placeholder for the JSON string, something like:
<!-- other view stuff -->
var v = ${json_string};
<!-- more view stuff -->

Related

Compress on code json string and return to client

I have a ASP.NET MVC Controller C# and inside I have the following method:
public JsonResult PlayersData()
{
List<Player> players = new List<Player>();
// here some code to fill players list
// ...
return Json(players, JsonRequestBehavior.AllowGet);
}
I would like to send the Json compressed, I mean the List because the json is heavy about 12MB.
I don't want to enable IIS compression, I need to do it within the same code.
Any clue?

Spring MVC : post request and json object with array : bad request

I'm trying to retrieve parameters from a http POST request with Spring MVC.
The request contains the following json object (content-type : application/json), which itself contains an array of customObjects :
{
"globalId":"338",
"lines":[
{
"id": "someId",
"lib":"blabla",
...
}
]
}
Here's the code I'm trying to use :
#RequestMapping(method = RequestMethod.POST, value = "/valider")
#ResponseBody
public void valider(final HttpServletRequest request, #RequestParam("globalId") final String globalId, #RequestParam("lines") final MyCustomObject[] lines) {
All I'm getting is a "bad request" error (http 400).
Is it possible to separately retrieve the two parameters "globalId" and "lines" ? Or since they are in the same json object, it has to be treated has a single parameter ? How do you proceed when you have more than one parameter in a Post request ?
I think you're looking for something like `#RequestBody. Create a class to represent your JSON data. In your case, this class will contain two member variables - globalId as a string and lines as an array of the object it represents. Then in your controller method, you will use the #RequestBody annotation on this class type so that Spring will be able to convert the JSON into object. Check the examples below.
http://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/
JQuery, Spring MVC #RequestBody and JSON - making it work together
http://www.techzoo.org/spring-framework/spring-mvc-requestbody-json-example.html
create model object to map your Json data
class DLibrary{
int id;
String lib;
//getters/setters
}
class GLibrary{
int globalId;
List<DLibrary> lines;
//getters/setters
}
Replace your controller code with below
#RequestMapping(method = RequestMethod.POST, value = "/valider")
#ResponseBody
public void valider(#RequestBody GLibrary gLibrary) {
#RequestBody annotation will map Json to Java Object implicitly.
To achieve this spring must require jackson-core and jackson-mapper library included in your application and your Java class should have getter and setters i.e it must follow bean standards.
Indeed, I have to use #RequestBody to get the JSON object.
Quick summary, depending on how the parameters are passed in the http POST body request :
one JSON object (Content-Type: application/json), use #RequestBody to map the json object to a java object
multiple parameters (Content-Type: application/x-www-form-urlencoded), use #RequestParam for each parameter

How to make a REST call from Spring MVC Controller and return the response as it is

I am trying to make a webservice call from my Spring MVC controller using RestTemplate, I was wondering if there is a way to return the response as it is without unmarshaling to a Java object.
For example like in play framework,
HttpResponse res = WS.url(url).get();
renderJSON(res.getString()); // or res.getJson()
Most of my responses would be JSON or very rare case it might be a String.
Here's some code snippet;
## JAVA Code
#Autowired
RestOperations operations;
#RequestMapping(method = RequestMethod.GET)
public String index( #PathVariable("id") String id, Model model) {
//a) Call webservice using restemplate or using any other method
//b) get the data from service
//c) set data in modal
String jsonFeed = operations.getForObject("URL", String.class);
model.addAttribute("jsonFeed", jsonFeed);
}
## JSP CODE
// fetch the jsonFeed variable set in the modal attribute and set it into a java script variable and use the way u want.
<script type="text/javascript">
var jsonObjToUse = jQuery.parseJSON(${jsonFeed})
</script>

Unsupported Media Type Error in AJAX-Spring

I am trying to pass POST data from my jsp with jquery-ajax to my Spring-MVC controller function. The data is passed fine and I can print the JSON data when I use a String object to receive the RequestBody. But when I employ a DTO which has a List variable declared with its own objects the controller returns a '415 Unsupported Media Type Error' with the following statement,
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
below given is the DTO class
public class anyClassDTO{
private String name;
private List<anyClassDTO> subList = new ArrayList<anyClassDTO>();
//getters and setters here
}
Now, here is the controller function
#RequestMapping(headers ={"Accept=application/json"}, value = "urlFromJsp", method = RequestMethod.POST)
public #ResponseBody
String addData (HttpServletRequest request,
#RequestBody List<anyClassDTO> dtoObject,
Model model)
{
return "{\"value\":\"true\"}";
}
Is it not possible for a list of objects to be received from the jsp page to a controller via AJAX?
Here is a set of sample data being passed from the jsp
[{"name":"module1","subList":[{"name":"chapter1","subList":[{"name":"subchapter1","subList":null}]}]},{"name":"module2","subList":[{"name":"chapter1","subList":[{"name":"subchapter1","subList":null}]}]}]
Make sure your AJAX request sets the request's Content-Type to application/json.
Spring typically uses a MappingJacksonHttpMessageConverter to convert the request body when you specify #RequestBody. This HttpMessageConverter only supports application/*+json type content types, so you have to make sure your request contains it.
Well, we could make it work as it is by adding a little more detail. Instead of receiving the #ResponseBody as a List object I created another DTO which holds a List object of the original DTO. So the second DTO is basically a dummy which receives the data from AJAX as a single object.
Like I have said in the question I have a DTO as follows
public class AnyClassDTO{
private String name;
private List<anyClassDTO> subList = new ArrayList<anyClassDTO>();
//getters and setters here
}
I created another DTO which holds a List of the above DTO
public class DummyDTO{
private List<AnyClassDTO> dummyObj;
//getters and setters here
}
Then in the controller I changed the function to
#RequestMapping(headers ={"Accept=application/json"}, value = "urlFromJsp", method = RequestMethod.POST)
public #ResponseBody
String addData (HttpServletRequest request,
#RequestBody DummyDTO dummyDTOObj,
Model model)
{
return "{\"value\":\"true\"}";
}
Earlier if I was sending a list directly from AJAX, now I am sending a stringified litteral with a variable which holds the whole data.
And it works like a charm!

spring3mvcportlet populate JSON dojo select

I am new to Spring mvc3 portlet and dojo. I am trying to populate select dropdown with JSON data when jsp is loaded. I want to use dojo and give ajax call to controller and return JSON when jsp is loaded. Any tips will be helpful.
#Controller
#RequestMapping("/yourController")
public class YourController
{
#RequestMapping(value="/combo/{id}", method=ReqestNethod.GET)
public String getDropDownData(#ParamValue("id") long id)
{
List<Combo> combos = commonDao.getCombos(id);
String json = JsonUtil.toJson(combos); // or whichever way you use
return json;
}
}
Send requests from dojo to this url
<your-context-path>/yourController/combo/1
where 1 is your combo id.
I haven't checked the syntax here.. Wrote it blind. You might get compilation errors.
I get data in below format
How do I populate dojoType="xwt.widget.form.FilteringSelect"
{"ValuesDTO": {"items": [{},{"default": {"size": 5},"int": 10,"string": "Product1","string": "Product1 ","string": "product3","string": "product4","string": "product5"}]}}
I am sending dat in bean--->DTO--->List