JSP中EL表达式取值问题记录(已解决)

***************************2015-10-28 22:21*************************

问题描述如下:

在当前的jsp页面已经有了如下代码:

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

在JS代码中有如下代码:

    $(function() {
        console.info(${basePath});
        console.info("${basePath}");
        console.info('${basePath}');
        console.info("<%=basePath%>");
        console.info(<%=basePath%>);
    }

目前能够正常输入的只有:

console.info("<%=basePath%>");

为什么了?遇到这个怎么处理了?

***************************2015-10-29 10:21*************************

PS:基础不牢靠导致出现上述问题啊。

EL表达式的本质是从4个域空间取值,但是如下这句代码是JSP的脚本片段,在后台会被处理为Java代码的,但是这段代码并没有往域空间存值,所以EL表达式取值不成功。

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

而表达式<%=basePath%> 这个表示JSP中的输出,其本质是调用JspWriter的out默认对象进行输出,会在服务端被解析为Java代码然后输出,只要页面定义了basePath这个变量就可以访问到。

解决方法

1.只通过JSP的表达式<%=basePath%>取值。

2.在脚本片段中将basePath存入page域空间。

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    pageContext.setAttribute("basePath", basePath);
%>

PS:基础的东西也不是说看了一定理解,但是一定要在实际开发中多反思多体会。

原文地址:https://www.cnblogs.com/LiuChunfu/p/4918910.html