Render multiple views within a single request

泄露秘密 提交于 2019-12-05 10:00:22

UPDATE: There are some approaches for solving your issue. I'd try this one, but maybe there are cleaner ways.

@Component
public class JsonMultipleViewFactory {

    @Autowired private List<ViewResolver> viewResolverList;

    public View getView(List<ModelAndView> mavList) {
        for (ModelAndView mav : mavList) {
            if (mav.getView()==null) {
                mav.setView(resolve(mav.getViewName()));
            }
        }
        return new JsonMultipleView(mavList);
    }

    private View resolve(String viewName) {
        for (ViewResolver vr : viewResolverList) {
            View view = vr.resolve(viewName, LocaleContextHolder.getLocale());
            if (view!=null) {
                return view;
            }
        }
        return null;
    }
}

public class JsonMultipleView implements View {

    private final List<ModelAndView> mavList;

    public JsonMultipleView(List<ModelAndView> mavList) {
        this.mavList = mavList;
    }

    public String getContentType() { 
        return "application/json"; 
    }

    public void render(Map<String,?> model, HttpServletRequest request, HttpServletResponse response) {
        Json json = new Json(); // You can use several Json libraries here
        for (ModelAndView mav : mavList) {
            MockHttpServletResponse mockResponse = new MockHttpServletResponse();
            mav.getView().render(mav.getModel(), request, mockResponse);
            json.add(mav.getViewName(), mockResponse.getContentAsString());
        }
        json.write(response.getOutputStream());
        response.getOutputStream().close();
    }
}

And can be used like this:

@Autowired private JsonMultipleViewFactory jsonMultipleViewFactory;

@RequestMapping(value = "my-request")
public View myRequest() {
    ...
    List<ModelAndView> mavList = new ArrayList<ModelAndView>();
    mavList.add(modelAndView1);
    mavList.add(modelAndView2);
    return jsonMultipleViewFactory.getView(mavList);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!