如何根据条件返回json响应并重定向到另一个视图?

时间:2013-07-22 05:18:01

标签: java spring return return-type

我有一个搜索条件,具体取决于我获得列表的结果。 如果列表只包含1个数据,那么我想返回到该特定数据的编辑视图。如果列表包含多个数据,我想返回jsonResponse以显示数据表。

我试过这个,但我没有得到数据表,也没有得到视图

if(reservationGridDataPage.getSize() > 1){
    GridJSONResponse jsonResponse = ReservationGridHelper.prepareResponse(reservationGridDataPage);
    jsonResponse.setiTotalDisplayRecords(gridManager.getTotalSearchedReservations(pageRequest, null, entityStateCode, searchParams));
    jsonResponse.setsEcho(sEcho);
    return jsonResponse;
}else{
    Long entityKey = null;
    List<ReservationGridData> content = reservationGridDataPage.getContent();
    for (ReservationGridData t : content) {
        entityKey = t.getId();
    }

    RedirectView redirectView = new RedirectView("/xxx/editRes?id="+entityKey);
    return new ModelAndView(redirectView);
}

1 个答案:

答案 0 :(得分:0)

只需返回String类型的视图名称。然后,如果reservationGridDataPage.getSize() > 1返回true,则重定向到将使用@ResponseBody分配的控制器的另一个方法,该方法将返回您的json对象。

@RequestMapping(value = "//... your mapping blah blah ...", method = RequestMethod.POST)
public String method1(){
    if(reservationGridDataPage.getSize() > 1){
        return "redirect:/json-response.do";
    }else{
        Long entityKey = null;
        List<ReservationGridData> content = reservationGridDataPage.getContent();
        for (ReservationGridData t : content) {
            entityKey = t.getId();
        }

        //...
        //some other codes

        return "the-name-of-my-edit-view";
    }
}

@RequestMapping(value = "/json-response.do", method = RequestMethod.GET)
public @ResponseBody GridJSONResponse jsonResponseController(){
    //... some other codes
    GridJSONResponse jsonResponse = ReservationGridHelper.prepareResponse(reservationGridDataPage);
    jsonResponse.setiTotalDisplayRecords(gridManager.getTotalSearchedReservations(pageRequest, null, entityStateCode, searchParams));
    jsonResponse.setsEcho(sEcho);
    //...

    return GridJSONResponse;
}