如何将SpringMVC视图手动呈现为html?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (3)
  • 关注 (0)
  • 查看 (79)

是否可以在控制器映射方法中将视图呈现为html,以便将呈现的html作为json对象的一部分返回?

常用的控制器方法示例:

@RequestMapping(value={"/accounts/{accountId}"}, method=RequestMethod.GET)
public String viewAcc(final HttpServletRequest req, 
        final HttpServletResponse resp, final Model model,
        @PathVariable("accountId") final String docId) {

    // do usual processing ...

    // return only a STRING value, 
    //   which will be used by spring MVC to resolve into myview.jsp or myview.ftl
    //   and populate the model to the template to result in html
    return "myview";
}

我所期望的是:

@RequestMapping(value={"/accounts/{accountId}"}, method=RequestMethod.GET)
public String viewAcc(final HttpServletRequest req, 
        final HttpServletResponse resp, final Model model,
        @PathVariable("accountId") final String docId) {

    // do usual processing ...

    // manually create the view
    ModelAndView view = ... ? (how)

    // translate the view to the html
    //   and get the rendered html from the view
    String renderedHtml = view.render .. ? (how)

    // create a json containing the html
    String jsonString = "{ 'html' : " + escapeForJson(renderedHtml) + "}"

    try {
        out = response.getWriter();
        out.write(jsonString);
    } catch (IOException e) {
        // handle the exception somehow
    }

    return null;
}

我想知道在控制器方法中创建视图并将视图手动呈现为html的正确方法是什么。

以下是从公认答案的指导中得到的工作示例:

View resolvedView = thiz.viewResolver.resolveViewName("myViewName", Locale.US);
MockHttpServletResponse mockResp = new MockHttpServletResponse();
resolvedView.render(model.asMap(), req, mockResp);
System.out.println("rendered html : " + mockResp.getContentAsString());
提问于
用户回答回答于

如果要在与DispatcherServlet,试着去处理它render-方法:

/** LocaleResolver used by this servlet */
private LocaleResolver localeResolver;

/** List of ViewResolvers used by this servlet */
private List<ViewResolver> viewResolvers;

/**
 * Render the given ModelAndView.
 * <p>This is the last stage in handling a request. It may involve resolving the view by name.
 * @param mv the ModelAndView to render
 * @param request current HTTP servlet request
 * @param response current HTTP servlet response
 * @throws ServletException if view is missing or cannot be resolved
 * @throws Exception if there's a problem rendering the view
 */
protected void render(ModelAndView mv, HttpServletRequest request, HttpServletResponse response) throws Exception {
    // Determine locale for request and apply it to the response.
    Locale locale = this.localeResolver.resolveLocale(request);
    response.setLocale(locale);

    View view;
    if (mv.isReference()) {
        // We need to resolve the view name.
        view = resolveViewName(mv.getViewName(), mv.getModelInternal(), locale, request);
        if (view == null) {
            throw new ServletException("Could not resolve view with name '" + mv.getViewName() +
                    "' in servlet with name '" + getServletName() + "'");
        }
    }
    else {
        // No need to lookup: the ModelAndView object contains the actual View object.
        view = mv.getView();
        if (view == null) {
            throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
                    "View object in servlet with name '" + getServletName() + "'");
        }
    }

    // Delegate to the View object for rendering.
    if (logger.isDebugEnabled()) {
        logger.debug("Rendering view [" + view + "] in DispatcherServlet with name '" + getServletName() + "'");
    }
    try {
        view.render(mv.getModelInternal(), request, response);
    }
    catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Error rendering view [" + view + "] in DispatcherServlet with name '" +
                    getServletName() + "'", ex);
        }
        throw ex;
    }
}

/**
 * Resolve the given view name into a View object (to be rendered).
 * <p>The default implementations asks all ViewResolvers of this dispatcher.
 * Can be overridden for custom resolution strategies, potentially based on
 * specific model attributes or request parameters.
 * @param viewName the name of the view to resolve
 * @param model the model to be passed to the view
 * @param locale the current locale
 * @param request current HTTP servlet request
 * @return the View object, or {@code null} if none found
 * @throws Exception if the view cannot be resolved
 * (typically in case of problems creating an actual View object)
 * @see ViewResolver#resolveViewName
 */
protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,
        HttpServletRequest request) throws Exception {

    for (ViewResolver viewResolver : this.viewResolvers) {
        View view = viewResolver.resolveViewName(viewName, locale);
        if (view != null) {
            return view;
        }
    }
    return null;
}

它通常应该足够添加@Autowired到上面的字段,但是DispatcherServlet当自动装配失败时,也会采取退路。

热门问答

对象存储COS有没有日志功能?

Hyman Wang

腾讯云 · 高级产品经理 (已认证)

推荐已采纳

你的cos 是否开通了 CDN 加速,如果开通了CDN 加速,可以去 CDN 的控制台下: (统计分析 --- 监控 )页面下拉到底部,可以通过 URL 查看流量情况。

对象存储里的视频能在线播放么?

Jinqn

腾讯 · 高级工程师 (已认证)

腾讯云COS前端开发
推荐

购买的云数据库里面有什么类型的数据库?有SQLserver吗?可以自己安装SQLserver吗?

帅的惊动我国计算机大神
推荐已采纳
云关系型数据库让您在云中轻松部署、管理和扩展的关系型数据库,提供安全可靠、伸缩灵活的按需云数据库服务。腾讯云关系型数据库提供 MySQL、SQL Server、MariaDB、PostgreSQL 数据库引擎,并针对数据库引擎的性能进行了优化。云关系型数据库是一种高度可用的托管服...... 展开详请

linux如何限制单一ip对服务器的日访问量?

小爱同学

腾讯云 · 技术支持 (已认证)

推荐
您根据当前网站规模和业务了解下【网站管家 WAF】,企业站点可有效抵御恶意攻击,垃圾访问。 图片.png 您反馈网站短信验证码被盗刷,也可结合自己业务,可自行部署iptables进行手动拦截。或其他方式 例如您的网站是nginx,在web配置文件中开启配置HttpLimitR...... 展开详请

兼容性测试只能上传apk测试的吗?

WeTest质量开放平台团队专注游戏,提升品质
推荐

目前不支持公众号的兼容测试,还请知晓

关于群自动解散的问题?

安稳

腾讯科技 · 工单技术支持 (已认证)

推荐
您好,临时群是没有的。云通信的群组只有私有群(Private)、公开群(Public)、聊天室(ChatRoom)、音视频聊天室(AVChatRoom)和在线成员广播大群(BChatRoom)这五种。 您说的这个需求,思路:创建群组时,服务端记录一下时间,到达约定解散的时间以后,...... 展开详请

所属标签

扫码关注云+社区