【问题标题】:Spring boot static content for nested / prefixed controllers嵌套/前缀控制器的 Spring Boot 静态内容
【发布时间】:2019-03-24 19:37:24
【问题描述】:

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

所有的静态内容(图片、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>

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

How to specify prefix for all controllers in Spring Boot?

spring boot: separate REST from static content

任何帮助将不胜感激。

【问题讨论】:

  • 这可能是因为您使用的视图中静态资源的相对路径不正确。贴出相关代码。
  • @JBNizet - 我已经为控制器添加了整个代码。如果您需要更多信息,请告诉我
  • 问题,正如我所说,很可能是您使用的静态资源的相对路径不正确在您的视图中。因此,发布相关代码:视图的代码,您将在其中链接到静态资源
  • 对不起,我误会了。更新了@JBNizet

标签: java spring spring-mvc spring-boot


【解决方案1】:

您正在使用相对路径。

所以,如果在浏览器地址栏中显示的当前 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/,因此请求被发送到 http://somehost/user/css/homepage.css工作,因为那不是 CSS 资源的 URL。

使用绝对路径:

href="/css/homepage.css"

这基本上就像硬盘驱动器上的路径一样。如果您在director /home/tim 中并执行less foo.txt,它将显示文件/home/tim/foo.txt。如果你执行less /foo.txt,它会显示文件/foo.txt

【讨论】:

    猜你喜欢
    • 2020-01-26
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2016-01-05
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    相关资源
    最近更新 更多