嵌套/前缀控制器的Spring Boot静态内容

时间:2018-10-19 21:52:54

标签: java spring spring-mvc spring-boot

我正在为我的Web应用程序使用Spring Boot 2.0.2和Freemarker。我的Web应用程序的静态内容无法为嵌套/前缀控制器加载。

所有静态内容(图片,CSS,js)都在

/src/main/resources/static/js
/src/main/resources/static/images
/src/main/resources/static/css

如果使用此控制器,一切都很好:

@RequestMapping(value = "/userProfile", method = RequestMethod.GET)
public ModelAndView getUser(@ModelAttribute("model") ModelAndView model,@RequestParam("userId") String userId) {

    UserProfile userProfile = userService.findById(userId);
    model.addObject("userProfile", userProfile);
    model.setViewName("userDetails");
    return model;
}

  userDetails.ftl is located at /src/main/resources/templates/userDetails.ftl

但是,在从浏览器发出GET请求时,我看到此控制器的静态内容(js / css /图像)上有404。

https://localhost:8443/users/js/saveUser.js -- 404
(Please note "users" in the URL while trying to load static content)

@RequestMapping(value = "/user/profile", method = RequestMethod.GET)
public ModelAndView getUser(@ModelAttribute("model") ModelAndView model,@RequestParam("userId") String userId) {

    UserProfile userProfile = userService.findById(userId);
    model.addObject("userProfile", userProfile);
    model.setViewName("userDetails");
    return model;
}

视图代码

<link rel="stylesheet" type="text/css" href="css/homepage.css">
<link rel="stylesheet" type="text/css" href="css/user-profile-display.css">
<script type="text/javascript" src="js/saveUser.js}"></script>
<script type="text/javascript" src="js/authenticate.js}"></script>

我研究了以下问题,但找不到可行的解决方案:

How to specify prefix for all controllers in Spring Boot?

spring boot: separate REST from static content

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您正在使用相对路径。

因此,如果在浏览器地址栏中显示的当前URL为http://somehost/userProfile,则相对路径css/homepage.css相对于http://somehost/被解析,因此请求被发送到http://somehost/css/homepage.css,效果很好

如果在浏览器的地址栏中显示的当前URL为http://somehost/user/profile,则相对路径css/homepage.css相对于http://somehost/user/被解析,因此请求被发送到{ {1}}无效,因为它不是CSS资源的URL。

使用绝对路径:

http://somehost/user/css/homepage.css

这基本上就像硬盘上的路径一样工作。如果您在导演href="/css/homepage.css" 中并执行/home/tim,它将显示文件less foo.txt。如果执行/home/tim/foo.txt,它将显示文件less /foo.txt