Why is my EL-statement only working in a script-tag where I do not import a js.file through a src-reference?

回眸只為那壹抹淺笑 提交于 2019-11-29 17:01:07
BalusC

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