Style Paths In Java EE Applications

岁酱吖の 提交于 2019-12-22 01:37:32

问题


I have a Java EE application and in the application I have the following structure.

WEB-INF
    layout
        header.jsp
    styles
        main.css

I want to include the main.css in the header.jsp. Which I am attempting to do with the following (where ... is the path):

<link rel="stylesheet" href="..."> 

However, I can't seem to get the right path. I have tried each of the following with no luck:

../styles/main.css
/styles/main.css
styles/main.css
/WEB-INF/styles/main.css
WEB-INF/styles/main.css

What is the correct path?


回答1:


First of all, resources in /WEB-INF folder are not directly publicly accessible without a intermediating (front controller) servlet (this also covers JSP files themselves! the <jsp:include> runs at webserver, not at webbrowser). So you've to put CSS (and JS and image) files outside the /WEB-INF folder.

WebContent
 |-- WEB-INF
 |    `-- layout
 |         `-- header.jsp
 |-- styles
 |    `-- main.css
 :

Assuming that it's now in /styles/main.css, then you can reference it as follows:

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

Using ${pageContext.request.contextPath} (which prints the current context path with a leading slash and thus makes the CSS URL guaranteed relative to the domain root) is not necessary per se, but it is your safest bet as the current request URL is unknown. All relative paths in HTML <link>, <script>, <img>, <a>, etc elements are namely namely by the webbrowser resolved relative to the current request URL (as you see in browser's address bar). As long as it's unclear what your request URL is, I can't answer the right CSS path without using ${pageContext.request.contextPath}.

See also:

  • Moving resources under WEB-INF
  • Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP


来源:https://stackoverflow.com/questions/12344406/style-paths-in-java-ee-applications

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!