In a JSP, how do I make a static content URL dynamic based on whether I'm in development or production?
In a JSP-based web application, let's say I'm hosting my static content on a CDN, but during development I want serve that content from my web application -- just to make life easy.
How do I make the URL for my static content dynamic in a way that any JSP can automatically see it?开发者_C百科
Do I define some singleton class to contain all my settings and just grab an instance of that from my JSP? Is there some way to make some parameters available to all JSPs? Or is there some other way altogether?
You need this set as request or servlet context attribute. It can be done in a Filter
(per request) or (better, as BalusC suggested) - ServletContextListener
. You put a request attribute called staticRoot
and then all URLs to static resources: <img src="${staticRoot}/images/logo.ong" />
The setting can be read at startup by the filter from a properties file (usually placed outside the .war file), so that you can supply different properties for different environments.
Just set it as an application wide variable with help of a ServletContextListener
:
@WebListener
public class Config implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
String staticHost = determineItSomehowBasedOnContextParamOrSystemPropertyOrPropertiesFileOrWhatever();
event.getServletContext().setAttribute("staticHost", staticHost);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP.
}
}
It'll be available as ${staticHost}
in EL. You could then use it as follows:
<link rel="stylesheet" href="${staticHost}/style.css" />
<script src="${staticHost}/script.js"></script>
<img src="${staticHost}/image.png" />
精彩评论