如何从HTML字符串创建Spring ModelAndView?

Tar*_*ken -1 spring spring-mvc

我正在从控制器中获取外部网页(作为字符串)。如何将包含HTML的字符串作为返回ModelAndView

Ral*_*lph 5

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

而是这样做

@Controller
public class MyController() {

    @RequestMapping(...)
    @ResponseBody
    public String controllerMethod() {
        String htmlDocument = getHtmlFromSomeWhere();
        return htmlDocument;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果必须返回a 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"));
     }
}
Run Code Online (Sandbox Code Playgroud)