我正在使用Spring boot 2.0.2和Freemarker作为我的Web应用程序。我的 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/images(上看到 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>
我已经查看了以下问题,但找不到有效的解决方案:
如何在 Spring 引导中为所有控制器指定前缀?
Spring Boot:将 REST 与静态内容分开
任何帮助将不胜感激。
您使用的是相对路径。
因此,如果浏览器地址栏中的当前 URLhttp://somehost/userProfile
,则相对于http://somehost/
解析css/homepage.css
的相对路径,因此请求将发送到http://somehost/css/homepage.css
,这工作正常
如果浏览器地址栏中的当前 URL 是http://somehost/user/profile
,则相对路径css/homepage.css
相对于http://somehost/user/
解析,因此请求被发送到不起作用的http://somehost/user/css/homepage.css
,因为这不是 CSS 资源的 URL。
使用绝对路径:
href="/css/homepage.css"
这基本上就像硬盘驱动器上的路径一样工作。如果您在控制器/home/tim
中并执行less foo.txt
,它将/home/tim/foo.txt
显示文件。如果执行less /foo.txt
,它将/foo.txt
显示文件。