【发布时间】:2017-12-03 19:24:46
【问题描述】:
我是一个新的 spring-boot 和 spring 框架。据我说,使用 spring-boot 创建和部署 web 应用程序非常容易,但是当我运行我的示例 spring web 应用程序时,应用程序找不到“welcome.html”页面。我在stackoverflow上检查了所有类似的问题,但对我没有用。我看不到小问题,但我没有找到我的问题。我的应用结构和代码如下:
MyApplication 类如下:
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
WelcomeController 类如下:
@Controller
public class WelcomeController {
@RequestMapping(value = "/welcome")
public String welcome() {
return "welcome"; //<- this is your login.html if it is directly in resource/templates folder
}
}
application.properties 文件如下:
spring.mvc.view.prefix = templates/
spring.mvc.view.suffix = .html
spring.mvc.static-path-pattern=/resources/**
WebMvcAppConfig 类如下:
public class WebMvcAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry); //To change body of generated methods, choose Tools | Templates.
registry.addViewController("/welcome").setViewName("welcome.html");
}
}
【问题讨论】:
-
你几乎从不想在 Spring Boot 应用程序中使用
@EnableWebMvc。此外,@SpringBootApplication已经启用了对使用它的包的组件扫描,在本例中为net.samplespringboot。 -
@forever_software 如果您的 HTML 页面是静态的,那么除了您的主应用程序类之外,您不需要共享的任何内容。您需要做的就是将您的静态文件放在
src/main/resource/static中,它们将由 Spring Boot 自动配置的静态资源支持自动提供。 -
将 src/main/resources 中的 application.properties 移到该默认包中
标签: java spring spring-mvc spring-boot