返回JSON时返回ModelAndView

时间:2014-06-30 15:15:52

标签: json jsp spring-mvc

我们可以从spring控制器返回JSON对象,并在jsp页面上编写该JSON对象。 以下是我的jsp页面:

  <script type="text/javascript">
 dojo.require("dojox.grid.EnhancedGrid");
            dojo.require("dojox.data.QueryReadStore");
  dojo.ready(function(){

                mystore=new dojo.data.ItemFileReadStore({url:"<%=request.getContextPath()%>/showData.htm"});

                 var layout= [
                 {field: 'ID', name: 'SID',formatter: hrefFormatter,datatype:"number" },
                 {field: 'SPREAD',name: 'SPREAD',autoComplete: true}
]
 var grid = new dojox.grid.EnhancedGrid({
                        id: 'myGrid',
                       ----
                        });
</script>

控制器:

@RequestMapping(value = "/showData", method = RequestMethod.GET)
    public void getSTIDData(HttpServletRequest request,
            HttpServletResponse response, @ModelAttribute VINDTO vinData,
            BindingResult beException) throws IOException {
        try {
              ......
              ......
             XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
                public HierarchicalStreamWriter createWriter(Writer writer) {
                    return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
                }
            });

            xstream.alias("items", com.loans.auto.DTO.VINRequestDTO.class);
            String str = xstream.toXML(vinListCopy);

            StringBuffer rowData = new StringBuffer();
            rowData.append("{'numRows':").append(vinListCopy.size())
                    .append(",'items':").append(str).append("}");
            PrintWriter out = response.getWriter();
            out.print(rowData);
}

而不是getSTIDData(..)返回void,我希望这个方法返回ModelAndView对象,但是当我返回ModelAndView对象时,在jsp页面中数据没有被加载并且它表示&#34;没有找到数据&#34; 。请建议。感谢。

以下是我使用Gson时产生的异常

SyntaxError {stack: "SyntaxError: Unexpected identifier↵    at Object.d… at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)", message: "Unexpected identifier"}
message: "Unexpected identifier"
stack: "SyntaxError: Unexpected identifier↵    at Object.dojo.fromJson (/MYWebProject/dojo/_base/json.js:26:23)↵    at Object.dojo._contentHandlers.dojo.contentHandlers.json (/MYWebProject/dojo/_base/xhr.js:78:16)↵    at Object.dojo._contentHandlers.dojo.contentHandlers.json-comment-optional (/MYWebProject/dojo/_base/xhr.js:156:28)↵    at _deferredOk (/MYWebProject/dojo/_base/xhr.js:432:42)↵    at notify (/MYWebProject/dojo/_base/Deferred.js:187:23)↵    at complete (/MYWebProject/dojo/_base/Deferred.js:168:4)↵    at resolve.callback (/MYWebProject/dojo/_base/Deferred.js:248:4)↵    at eval (/MYWebProject/dojo/_base/xhr.js:627:8)↵    at signalListener (/MYWebProject/dojo/Deferred.js:37:21)↵    at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)"
__proto__: Error

2 个答案:

答案 0 :(得分:1)

是的,您可以在GSON API的帮助下返回JSON response.showing

@RequestMapping(value = "/showData", method = RequestMethod.GET)
public @ResponseBody String getUserHomePage(HttpServletRequest request,HttpServletResponse response, @ModelAttribute VINDTO vinData,BindingResult beException) throws IOException {
//you code stuff to create model object bean
Gson gson = new  Gson();
return gson.toJson(objectBean);
}

答案 1 :(得分:0)

保持简洁......

这是一段真实的代码片段......

 @RequestMapping(value = "/actions/getImplGroups", method = RequestMethod.POST)
    public ResponseEntity<String> getImplGroups(HttpServletRequest request, HttpServletResponse response) {

        List<String> groups = bpmClient.getAllGroups();

        ObjectMapper mapper = new ObjectMapper();
        String jsonString;
        try {
            jsonString = mapper.writeValueAsString(groups);
        } catch (JsonGenerationException e) {
            jsonString = "Error with json generation: " + e.getMessage();
        } catch (JsonMappingException e) {
            jsonString = "Error with json mapping: " + e.getMessage();
        } catch (IOException e) {
            jsonString = "Error with json: " + e.getMessage();
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED);
    }

要考虑的重点是发送正确的网页标题,以便您的网页期望看到json。

我在上面的情况下使用Jackson库来创建json,但实际上你可以按照自己喜欢的方式格式化json。以下是一个简单的手动格式化字符串的示例...

@RequestMapping(value = "/actions/getTicketsNotUpdatedWithinShift", method = RequestMethod.POST)
public ResponseEntity<String> getTicketsNotUpdatedWithinShift(String center, String sections, String minutesInShift, Model model) {

    String[] sectionArray = sections.split(",");

    String json = "";
    String rowsString = "";

    for (String section : sectionArray) {
        List<Map<String, String>> rows = service.getMinutesSinceLastTicketUpdate(center, section);

        for (Map<String, String> row : rows) {
            int minutesSinceUpdate = Integer.parseInt(row.get("minutes"));

            if (minutesSinceUpdate > Integer.parseInt(minutesInShift)) {
                String description = row.get("description");
                rowsString = rowsString + "\"" + description + "\",";
            }
        }
    }

    // Build the json structure
    if (!rowsString.isEmpty()) {
        // Trim the trailing comma.
        rowsString = rowsString.replaceAll(",$", "");
        json = "[" + rowsString + "]";
    } else {
        json = "[]";
    }


    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}