首页 > 解决方案 > 静态资源与 Spring Boot 中的 @PathParam 冲突 thymleaf localhost:8080/script.js 与 localhost:8080/{message} 冲突

问题描述

主要课程-

@SpringBootApplication
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

控制器类

@Controller
public class GreetingController {

    @GetMapping("/{message}")
    public String greeting(@PathVariable(name="message", required=false) String message, Model model) {
        model.addAttribute("message", message);
        return "greeting";
    }

}

html文件

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head> 
    <title>Getting Started: Serving Web Content</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="/script.js"></script>
</head>
<body>
    <p th:text="'Hello, ' + ${message} + '!'" />
</body>
</html>

脚本文件

console.log("hi");

索引.html

<!DOCTYPE HTML>
<html>
<head> 
    <title>Getting Started: Serving Web Content</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p>Get your greeting <a href="/greeting">here</a></p>
</body>
</html>

在此处查找目录结构的屏幕截图

此外,此项目参考来自https://spring.io/guides/gs/serving-web-content/并进行了以下修改

标签: spring-boot

解决方案


您最好发布完整的 home.html 文件和完整的 Controller 类。或尝试 @PathVariable 而不是 @PathParam 。由于 @PathParam 只能与 REST 一起使用,而 @PathVariable 在 Spring 中使用,因此它可以在 MVC 和 REST 中使用。


推荐阅读