Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Controller Return View and JSON Together

Tags:

java

json

spring

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?

like image 241
Clay Banks Avatar asked Apr 01 '15 22:04

Clay Banks


2 Answers

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>
like image 163
CupawnTae Avatar answered Nov 10 '22 12:11

CupawnTae


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.

like image 32
Alex Avatar answered Nov 10 '22 13:11

Alex