栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在单个请求中呈现多个视图

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在单个请求中呈现多个视图

更新: 有一些方法可以解决您的问题。我会尝试这种方法,但也许有更清洁的方法。

@Componentpublic 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();    }}

可以这样使用:

@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);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/466494.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号