【问题标题】:How to serve static html content page in spring-boot如何在spring-boot中提供静态html内容页面
【发布时间】:2015-10-30 19:39:52
【问题描述】:

我正在通过spring-boot 启动一个嵌入式tomcat,并希望将静态index.html 页面作为正在运行的应用程序的一部分。

但以下不起作用:

@SpringBootApplication
public class HMyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}


@RestController 
public class HomeContoller {
    @RequestMapping("/")
    public String index() {
        return "index";
    }
}

src/main/resources/static/index.html

结果:当我调用localhost:8080 时,我只看到“索引”一词,但没有看到我的 html 页面。为什么?

【问题讨论】:

  • 这是因为@RestController@ControllerResponseBody 的元注释,这意味着它将“索引”写入响应输入流。您应该改用@Controller,以便将“索引”解析为视图名称。
  • 天哪,你是对的,绝对的。我可能对并排开发@RestController 感到困惑。无论如何,我现在使用@Controller 得到以下异常:javax.servlet.ServletException: Could not resolve view with name 'index' in servlet with name 'dispatcherServlet'。而是返回index.html 都不起作用。
  • 我认为视图名称应该是static/index.html
  • static/indexstatic/index.html 都不起作用。
  • 在下面看我的答案,我解决了。

标签: java spring spring-mvc spring-boot


【解决方案1】:

那是因为 @RestController 注释,只需删除此注释对我有用。

【讨论】:

    【解决方案2】:

    您可以使用ModelAndView 在 Spring Boot 中提供静态 HTML 内容。

    @RequestMapping("/")
    public ModelAndView home()
    {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }
    

    application.properties:-

    spring.mvc.view.suffix = .html

    HTML 文件:-src/main/resources/static/index.html

    【讨论】:

      【解决方案3】:

      对我来说这行得通,我相信有更好的方法(比如没有 .html)。

      @RequestMapping("/")
      public String index() {
          return "index.html";
      }
      

      【讨论】:

      • 如果你使用JSP页面(index.jsp)那么你可以使用return "index"。
      • 这可行,但是如果我将控制器更改为特定的映射,它会显示 404。例如,控制器映射:@Controller @RequestMapping("/user)" 和方法映射:@RequestMapping(" /{id}"),然后我收到 404 错误。它仅适用于请求映射“/”。
      • 如果您需要 json 数据作为响应,您应该使用 @RestController 类中的映射。如果你需要一个视图,那么它会变得有点复杂。你想让我做什么?通常,如果您将静态资源放在resources/static folder structure it works automatically because of spring boot 下。此外,如果您使用 /{id} 您应该在方法参数中有一个 @PathVariable("id") 以便它工作,不确定您是否故意将其遗漏。
      【解决方案4】:

      我的错:我有一个带有@EnableWebMvc 注释的附加类。这以某种方式弄乱了 spring-boot 自动配置。我删除了它,现在它可以返回 index.html

      【讨论】:

        猜你喜欢
        • 2016-07-14
        • 2020-08-07
        • 2016-09-14
        • 2017-07-12
        • 2019-03-30
        • 1970-01-01
        • 2015-06-21
        • 1970-01-01
        相关资源
        最近更新 更多