如何从html String创建Spring ModelAndView?

时间:2013-05-28 12:19:35

标签: spring spring-mvc

我从Controller获取外部网页(作为字符串)。如何将包含HTML的字符串作为ModelAndView

返回

1 个答案:

答案 0 :(得分:4)

如果您想将该网页返回到客户端/浏览器,则无需创建ModelAndView。

而是这样做

@Controller
public class MyController() {

    @RequestMapping(...)
    @ResponseBody
    public String controllerMethod() {
        String htmlDocument = getHtmlFromSomeWhere();
        return htmlDocument;
    }
}

如果您必须返回ModelAndView,则必须编写自己的View实施。 查看某些模板的AbstractPdfView

return ModelAndView(new MyPlainHtmlView(htmlDocument));


public class MyPlainHtmlView implements View {
     ....

     private final String htmlDocument;

     public MyPlainHtmlView(String htmlDocument) {
         this.htmlDocument = htmlDocument;
     }

     @Override
     renderMergedOutputModelMap<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
           ServletOutputStream out = response.getOutputStream();
           out.write(this.htmlDocument.getBytes("utf-8"));
     }
}