I am trying to map a page request to return a view and a JSON Object simultaneously. For this I'm utilizing the Jackson JSON provider
Here's my Controller method
@RequestMapping(method = RequestMethod.GET, value = "/reports")
public String getFiles(Model model) {
//
//build array list
//
return files;
}
This returns my view (WEB-INF/jsp/reports.jsp
) fine, however without the JSON Object that Jackson builds, so of course I need to annotate the method with @ResponseBody
which will write the JSON Object to the http response automagically, and return the files
ArrayList...
@RequestMapping(method = RequestMethod.GET, value = "/reports")
@ResponseBody
public ArrayList<String> getFiles(Model model) {
//
///build array list
//
return files;
}
and the JSON object is indeed returned, but in a new view/blank html doc. Is it possible to return the JSON Object and redirect to "reports.jsp" at the same time?
I presume in your first example you're actually returning "reports"
rather than files
. And if you want to return a view, you can't also return a response body - you can only return one thing.
So either you split it into two requests, or you put the JSON into the model, and retrieve it in the JSP, e.g.
Java:
ObjectMapper mapper = new ObjectMapper();
model.addAttribute("json", mapper.writeValueAsString(files));
JSP:
<script>
var files=${json};
</script>
You can either create json object yourself and add to model (return view in this case) or return view and then after the page is loaded call another function which returns ajax object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With