How to manage file path when accessing from different directory location?
I have few web pages sitting in different directories and my goal is to have some sort of organized structure so that I can access to js or css files without hardcoding the path.
For instance, the directory structure is:
root --- js --- some.js
|
|--css --- some.css
|
|---pages ---- main.jsp
|
|---other----foo---- foo.jsp
|
|--bar --- bar.jsp
Then main.jsp and foo.jsp tries to reference some.js but has to have different path.
( main.jsp )
<script type="text/javascript" src="../js/some.js"></script>
( foo.jsp)
<script type="text/javascript" src=开发者_Go百科"../../js/some.js"></script>
This is not ideal if I want to change the location of main.jsp or foo.jsp, I have to come back to each files and change the path manually.
I am thinking to have factory class that has full path for each files so that it would look something like:
<script type="text/javascript" src=<% Factory.getFullPath(some.js) %> ></script>
In this case, I can still move files freely and not have to come back to each file.
Can I get some opinion to my approach? Is there other way to solve this?
Use a context-relative path. It will make the path absolute to the domain root. You can obtain the context path by HttpServletRequest#getContextPath()
. In JSP, the HttpServletRequest
is available by ${pageContext.request}
.
<script type="text/javascript" src="${pageContext.request.contextPath}/js/some.js"></script>
(the contextPath
itself already starts with a /
, so you don't need to prefix it yourself)
You can also set it using the HTML <base>
tag so that every relative URL in the page becomes relative to it. This way you don't need to copy ${pageContext.request.contextPath}
over all the place.
<base href="${pageContext.request.contextPath}"></base>
<script type="text/javascript" src="js/some.js"></script>
This has however one caveat: anchors, like <a href="#foo">
will also become relative to it. You need to take this into account as well if you go for this.
See also:
- Is is recommended to use
<base>
tag in HTML?
mm i'm not really sure if a factory is the most appropriate way to do this, maybe it will work.. i remember that for that i used an interface where i implemented some constants including the JS and CSS folder path
public interface Configuration {
public static final String SERVER_URL = "http://localhost:8080/";
public static final String CSS_URL = SERVER_URL + "css/";
public static final String JS_URL = SERVER_URL + "js/";
}
and then i'd have to import this interface in the servlet and call it like this:
...src="<% Configuration.JS_URL %>some.js" />..
that way if you change your folders name or path. you'll only have to change the configuration
精彩评论