使用Spring MVC进行静态内容渲染


问题内容

我是春天的新手,正在尝试。

我有一个包含css和图像的jsp文件,如下所示

<link href="css/style.css" rel="stylesheet" type="text/css" />

现在我有一个url路径,/localhost/myapp/test/tst它映射到一个控制器,然后将其转发给jsp

view.jsp存在

/web-inf/jsp/view.jsp

但是当点击路径时/localhost/myapp/test/tst,css和images路径会解析为

/localhost/myapp/test/tst/css/style.css

实际上,我希望它能够作为 /localhost/myapp/css/style.css webapp根目录中的css和html出现

我如何在spring配置中关注

 <mvc:annotation-driven />
    <mvc:resources mapping="/images/**" location="/images/" />
    <mvc:resources mapping="/css/**" location="/css/" />

问题答案:

您的CSS
href当前是相对于您的页面的,您需要通过添加前导斜线(加上上下文等)使其相对于服务器根目录。添加contextPath也是一个好主意,这样,如果/当您更改Web应用程序名称或将其部署为根Web应用程序时,资源仍然有效。

<link href="${pageContext.request.contextPath}/css/style.css" rel="stylesheet" type="text/css" />