【问题标题】:Spring Boot not loading views from templatesSpring Boot 不从模板加载视图
【发布时间】:2019-05-26 02:05:15
【问题描述】:

我的 Spring Boot 项目没有从 src/main/resources/templates/login.html 加载视图。但是它确实从 src/main/resources/static/index.html 加载视图。

这是我的项目结构:

我添加了简单的<a> 标签,用于在我的index.html

中打开我的登录页面
    <div>
        <a class="btn" href="login">Login</a>
    </div>

登录控制器:

@RequestMapping("/login")
public String showLogin() {
    System.out.println("Login method called");
    return "login";
}

这个方法不会被调用。此外,我看到很多教程表明您不需要将视图添加到 static 文件夹中,只需将视图添加到 templates 文件夹中,Spring Boot 就会自动选择它。

但 Spring Boot 似乎没有从 templates 文件夹中选择视图并显示白标错误页面。

我没有使用 jsp 页面,而是使用 Thymlead 模板。

application.properties

server.servlet.context-path=/hisservices

server.port=8081

welcome.message: Welcome to the HIS Services Dashboard

WelcomeController: index.html 页面

// inject via application.properties
@Value("${welcome.message:test}")
private String message = "Hello World";

@RequestMapping("/")
public String welcome(Map<String, Object> model) {
    model.put("message", this.message);
    return "welcome";
}

我需要为 templates 文件夹添加显式映射吗?

【问题讨论】:

  • 如果不调用控制器,则与视图无关。将您的应用程序类移动到 ...securejwt 包。
  • HisservicesJwtApplication.java移至外层/上层包,即com.skm.hisservice.secueejwt
  • 请发HisservicesJwtApplication.java的邮编

标签: spring spring-boot


【解决方案1】:

IMO,您需要进行包重组。

将主应用程序文件(HisserviceJwtApplication.java)移动到 com.skm.hisservice.securejwt 包中,并在 com.skm.hisservice 下创建新包 config。 securejwt 并移动 SecurityConfig。无需更改其他包。

通过这样做,您的 LoginController 将通过 spring-boot 自动扫描并且方法 showLogin 也会被调用。

如果您想继续使用现有的包结构(不建议),则将 @ComponentScan('com.skm.hisservice.securejwt.controller') 添加到主应用程序文件中。

【讨论】:

  • 是的,没错。这完全是关于包重组。谢谢。我从 Spring Boot Initializer 创建了项目,它创建了这个包结构。非常感谢。
【解决方案2】:

除非使用 Thymeleaf,否则 Just Spring Boot 无法从模板中找到视图。您必须将以下存储库添加到您的项目中才能获得解决方案。像这样的方式

main/webapp/WEB-INIF/*.html

在文件 application.properties 中输入这两行代码

spring.mvc.view.prefix: /WEB-INF/
spring.mvc.view.suffix: .html

现在,运行项目,希望问题得到解决。

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 2020-04-17
    • 2015-01-03
    • 2021-05-23
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多