【问题标题】:Why same-name variable in different included jsp doesn't cause exception?为什么不同包含的jsp中的同名变量不会导致异常?
【发布时间】:2017-12-17 15:53:23
【问题描述】:

我有一个 index.jsp,其中包含 header.jsp 和 frontpage.jsp 如下:

<body>
...
    <%@ include file="include/header.jsp"%>
...
<table>...<td> <%@ include file="include/frontpage.jsp"%></td>....

在 header.jsp 中:

...
    String __jspName = this.getClass().getSimpleName().replaceAll("_", ".");
    System.out.println("[header.jsp] used user quota = "+usedNum);
...

在frontpage.jsp中:

...
    String __jspName = this.getClass().getSimpleName().replaceAll("_", ".");
    System.out.println("[frontpage.jsp] "front_url = " + fp_front_url);
...

其实这是一个意外,我忘记删除其中的一个声明。但是当我在 Tomcat 6 下运行 index.jsp 时,它在 catalina.out 中运行正常(注意:出于安全原因,我省略了 front_url 的值

...
[header.jsp] used user quota = 0
[frontpage.jsp] front_url = ...
...

我的困惑是:“为什么 JVM 不报告‘变量重定义’异常?”

【问题讨论】:

    标签: java jsp include redefinition redefine


    【解决方案1】:

    JSP 编译器将您的两个 JSP 文件编译为两个不同的 servlet。每种情况下的变量都被限定在其各自的 servlet 类中,因此它与在两个单独的 Java 类中声明具有相同名称的字段非常相似:不会发生冲突。

    这在您的代码中很明显,因为您依赖已编译 JSP 页面的类名来设置 __jspName 变量:

    String __jspName = this.getClass().getSimpleName().replaceAll("_", ".");
    

    这将为您的两个包含文件生成header.jspfrontpage.jsp,表明它们已被编译为两个单独的类。

    【讨论】:

    • 但我以为你说的是​​针对 jsp:include 的。我认为@include 就像宏一样。如果不是,那么 jsp:include 和 @include= 有什么区别?
    猜你喜欢
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 2016-10-29
    • 2015-07-30
    相关资源
    最近更新 更多