开发者

Question about some calculation using JSP EL?

I am new to JSP EL. I am reading some EL text and got the following code:

<body>
        <h1>Hello World!</h1>
        <%
        String s1 = 开发者_如何学C"aaa ";
        String s2 = "22";
        Double dObj = new Double(3.5);
        int a;
        a = 12;
        %>
        s1 + s2 = ${ s1 + s2 } <br>
        a + 2 = ${a + 2} <br>
        dObj + 2 = ${dObj + 2} <br>
        2 + 2 = ${"2" + 2}
    </body>

And the results:

s1 + s2 = 0  (1)
a + 2 = 2 (2)
dObj + 2 = 2  (3)
2 + 2 = 4 (4)

I can understand the result of (4) but have no ideas with the results of (1), (2), and (3). Can anyone elaborate on that?


The EL variables reference a page-, or request-, or session-, or application-scope attribute (each scope is inspected, in that order). They don't reference a local scriptlet variable.

So, since you don't have any attribute in any scope named s1, s2, a or dObj, default values are used (0).

The results would be the ones that you're expecting if the scriptlet code would be the following:

    <%
    String s1 = "aaa ";
    String s2 = "22";
    Double dObj = new Double(3.5);
    int a;
    a = 12;

    request.setAttribute("s1", s1);
    request.setAttribute("s2", s2);
    request.setAttribute("dObj", dObj);
    request.setAttribute("a", a);

    %>

In a well-architected application, these attributes would be set by a servlet which would dispatch to your JSP, or by a JSP tag (<c:set> for example), but not by a scriptlet. Scriptlets should not be used anymore.


Just google "JSP EL arithmetic" and you should find a lot of examples, like here: http://www.roseindia.net/jsp/simple-jsp-example/ExpressionLanguageBasicArithmetic.shtml

The results are dependent on how the objects are evaluated inside EL {} tags.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜