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

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

是否可以在控制器映射方法中将视图呈现为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());
Mr.CryptoMr.Crypto提问于
梦飞翔758WEB工程师 硬件玩家 CHH不负责版主回答于

如果要在与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当自动装配失败时,也会采取退路。

回答过的其他问题

做小程序用得上哪些云服务?

梦飞翔758WEB工程师 硬件玩家 CHH不负责版主
分两种情况:新开发的小程序,或者有一定规模的小程序 新开发的小程序推广起来需要一个过程,前期用一个普通双核,2G内存以上配置的云主机基本就能满足需求.云主机也可以中途升级配置. 有一定规模的小程序.则需要根据规模和访问量的大小来决定选择什么样的配置.如果...... 展开详请

如何寻找最适合自身的云应用模式?

梦飞翔758WEB工程师 硬件玩家 CHH不负责版主
1.“私有云”模式就是自己购买部署自己的“CRM”系统,自己维护自己的服务资源。这种模式适合有足够实力的企业公司选用,因为这类型的企业公司会忽略成本因素。对于大多数中小企业不太适合,为什么呢?因为他们要考虑成本,降低成本和提高收入是企业追求的永恒目标。下面从优点和缺点二个角度进行...... 展开详请

如何解决吃鸡中的卡顿问题?

梦飞翔758WEB工程师 硬件玩家 CHH不负责版主

也可能是你的内存出了问题,内存对吃鸡影响很大。《绝地求生》的官方最低推荐配置为8GB,但其实8G不足以满足需求,内存容量将直接影响《绝地求生》的帧数波动!

如何利用腾讯云冷迁移工具将主机迁移至云主机CVM中?

梦飞翔758WEB工程师 硬件玩家 CHH不负责版主
这里有一个冷迁移实例。用于将一个系统盘镜像迁移到一个实例中。用户需要首先在腾讯云创建一个实例,然后通过本接口将需要运行的操作系统系统盘镜像迁移到该实例,实例的配置信息保持不变。 注意:为了防止兼容性错误,建议用户在创建实例的时候尽量选取与需要迁移的系统盘相似的操作系统。 输入...... 展开详请

什麼是消息推送 ?

梦飞翔758WEB工程师 硬件玩家 CHH不负责版主

消息推送简单的说就是一组实现RESTAPI的推送标签~

cos-nodejs-sdk-v5 找不到getObjectUrl接口的说明?

梦飞翔758WEB工程师 硬件玩家 CHH不负责版主

关于作者

梦飞翔758

WEB工程师 硬件玩家 CHH不负责版主

所属标签

扫码关注云+社区