如何使用 Spring Boot 应用程序从 Rest API 返回 html

Posted

技术标签:

【中文标题】如何使用 Spring Boot 应用程序从 Rest API 返回 html【英文标题】:How to return html from Rest API with spring boot application 【发布时间】:2018-03-01 14:33:39 【问题描述】:

我需要在 Spring Boot Application 中从 Rest API 返回一个 html 页面。 html "test.html" 位于 src/main/resource 目录中。下面是我的代码sn-p

    @RequestMapping(value ="/get/getReportById",method = RequestMethod.GET)
    @ResponseBody()
    public String getReportsByCategory(String id) throws Exception

        try
        //Do something

        catch(Exception e)
            e.printStackTrace();
        


        return "test";
    

【问题讨论】:

【参考方案1】:

类应该是@Controller,去掉@ResponseBody,你还应该配置模板处理器(例如Thymeleaf)。

更新

如果你查看@RestController 的代码,你会发现它是由@Controller 和@ResponseBody 注释组成的。所以 ResponseBody 会自动应用于所有方法。

【讨论】:

我们可以将它与@RestController 一起使用吗? 不,@RestController 只是一个 @Controller,其中每个方法都被自动假定为 @ResponseBody,但你不希望它是 @Riyash.D Plog 是对的,但你不能。更新了答案。【参考方案2】:

如果你想返回一个视图,你不希望你的控制器方法被注释为@ResponseBody,所以删除它,它应该可以工作。

【讨论】:

如果您的班级是@RestController,您需要将其设为@Controller【参考方案3】:

您需要从类路径中读取test.html 并将其作为字符串返回:

InputStream htmlStream = getClass().getResourceAsStream("test.html");
return new Scanner(htmlStream, "UTF-8").useDelimiter("\\A").next();

【讨论】:

【参考方案4】:

@RestController

是处理webservices,都是关于数据的,HTML之类的表示标记在这里没有任何作用。

@控制器

如果涉及到视图,这就是您想要使用的。 view 可以是任何会吐出 html 的东西(有或没有插值模型)。您可以使用良好的旧 JSP、JSF 或模板引擎,如 thymeleaf、velocity、freemarker 等。

【讨论】:

【参考方案5】:

您可以使用ModelAndView查看HTML页面如下,

 @RequestMapping(value ="/get/getReportById")
 public ModelAndView getReportsByCategory() throws Exception

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test.html");
    return modelAndView;

 

导入库,

import org.springframework.web.servlet.ModelAndView;

这个test.html 文件应该在src/main/resource/static/ 目录中。

【讨论】:

以上是关于如何使用 Spring Boot 应用程序从 Rest API 返回 html的主要内容,如果未能解决你的问题,请参考以下文章