EL expressions are only evaluated by the therefor capable servlets. Examples of such servlets are JSP's JspServlet
and JSF's FacesServlet
. The one is capable of evaluating ${...}
in template text and the other is capable of evaluating both ${...}
and #{...}
in template text. The container's default servlet who's responsible for static resources like *.js
files isn't.
Given that you're using JSP, just tell your webapp to use JspServlet
to process any *.js
requests. The container's builtin JspServlet
has usually a default servlet name of jsp
(at least, that's true for Tomcat and clones), so the below entry in your webapp's web.xml
should do in order to get EL to be evaluated in *.js
files.
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
This has one small caveat though. Some containers forcibly change the content type header to text/html
regardless of the js
file extension and then browsers got confused while downloading the JS file. One way to prevent that is to explicitly set the desired content type header in top of JS file the JSP way:
<%@page contentType="application/javascript" %>
A completely different alternative would be to print the context path as HTML5 data attribute of the <html>
tag.
<!DOCTYPE html>
<html lang="en" data-baseuri="${pageContext.request.contextPath}/">
...
</html>
It's then just available anywhere in JS as below:
var baseuri = document.documentElement.dataset.baseuri;
Or if you're a jQuery fan:
var baseuri = $("html").data("baseuri");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…