您的位置:首页 > Web前端 > JavaScript

EL和JSTL表达式语言

2016-06-22 00:31 405 查看
1. EL语法很简单,其最大的特点是使用方便

如以下代码:

User user=(User)session.getAttribute("user");

String sex=user.getSex();

out.print(sex);

其作用是从session中得到User对象,然后打印到user中的sex属性,并进行显示,但是相当冗长,如下面EL语言的描述

${sessioScope.user.sex}

上述EL范例的意思是:从session的范围中,取得user的属性,显然,使用EL,需要编写输出信息的代码时,工作的效率就会提高

综上,EL的最基本的语法结构如下所示:

${Expression}

2.EL表达式详细说明

    形式:${ }

    作用:从一个范围里面取值或者从一个对象中取值或是向页面输出值.

    1.接收客户端参数.

       ${param.name1 }

 

    2.指定范围并取值

       ${pageScope.name2 }

         ${requestScope.name3 }

         ${sessionScope.name4 }

         ${applicationScope.name5 }

 

        3.可以不指定范围再去取值

       ${name}

       这时候会按照pageContext request session application这样一个顺序依次的去找有没有一个叫name的值存在,一旦找到了就输出出来,最终没有找到那么就什么都不输出。

    

    4.取出一个对象中的属性值.

       ${requestScope.student.id}

       ${requestScope.student.name}

       ${requestScope.student.age}

       或者

       ${student.id}

       ${student.name}

       ${student.age}

       或者

       ${student["id"]}

       ${student["name"]}

       ${student["age"]}

 

       注意:${student.id}表示是要调用student对象中的getId方法,至于对象中有没有id属性对这个操作没有任何影响.所以这和id指的是对象中的property而不是attribute

 

       如果Student类中一个方法是getAddress,返回一个Address类的对象,Address类中有一个方法getCity,这个时候我们就可以这样写去拿到city属性的值.

       ${student.address.city}

    

 

    5.输出字符串

        ${"hello"}

 

    6.输出运算结果或者boolean表达式

        ${1+1 }

        ${(1+2)*3-4+5*3 }

        ${1<3 }

        //为空的话返回true

        ${empty "" }

        ${empty "hello" }

        //取否 不为空的话返回true

        ${not empty "hello" }

        ${! empty "hello" }

        ${param.score >50 }

        ${param.score >60?"good":"bad" }

    

    7.输出数组、集合中的元素

        <%

        String[] str = {"hello","world"};

    

        List<String> list = new ArrayList<String>();

        list.add("zhangsan");

        list.add("lisi");

        

        Map<String,Integer> map = new HashMap<String,Integer>();

        map.put("a",100);

        map.put("b",200);

        map.put("c",300);

        

        request.setAttribute("str",str);

        request.setAttribute("list",list);

        request.setAttribute("map",map);

        

        %>

    

        ${str[0] }<br>

        ${list[1] }<br>

        ${map["c"] }<br>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: