EL表达式应用

来源:互联网 发布:excel数据透视表应用 编辑:程序博客网 时间:2024/05/23 05:08
在上篇文章中简单介绍了一下EL表示式,现在就以例子来演示如何应用EL表达式。

注意:如果只是使用EL表达式不需要引入任何jar包,只要jsp/servlet容器实现了
      J2EE1.4/Servlet2.4 、 JSP2.0规范就可以。

1、servlet中,设置一些变量,放到request.setAttribute中:
/** * 测试EL表达式 */public class JstlElServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        //普通字符串        request.setAttribute("hello", "hello world!");                //结构        Group group=new Group();        group.setName("TGB");                User user=new User();        user.setUserName("张三");        user.setAge(23);        user.setGroup(group);                request.setAttribute("user", user);                        //map        Map map=new HashMap();        map.put("k1", "v1");        map.put("k2", "v2");        request.setAttribute("map", map);                //字符串数组        String[] strArray=new String[]{"a","b","c"};        request.setAttribute("strArray", strArray);                //对象数组        User[] users=new User[10];        for (int i=0;i<users.length;i++){            users[i] =new User();            users[i].setUserName("张三"+ i);        }        request.setAttribute("users", users);                //List         List userList =new ArrayList();        for (int i =0;i<10;i++){            User usr=new User();            usr.setUserName("李四_"+i);            userList.add(usr);        }        request.setAttribute("userList",userList);                        //empty        request.setAttribute("v2", "");        request.setAttribute("v3", new ArrayList());        request.setAttribute("v4", "12345");        request.setAttribute("v5", null);        request.getRequestDispatcher("/jstl_el.jsp").forward(request, response);    }}

2、在JSP界面用EL表达式接收
<body>    <h1>测试EL表达式</h1>    <hr>    <li>普通字符串</li>    hello(jsp脚本):<%=request.getAttribute("hello") %><br>    hello(el表达式,语法:$ and {}):${hello }    hello(el表达式,el的内置对象pageScope,requestScope,sessionScope,applicationSdcope)<br>    如果不指定范围,它的搜索顺序为(pageScope->applicationScope):${requestScope.hello }        <br><br>    <li>结构</li><br>    姓名:${user.userName }<br>    年龄:${user.age }<br>    所属组:${user.group.name }<br>        <br><br>    <li>取得Map</li><br>    map.k1:${map.k1 }<br>    map.k1:${map.k2 }<br>        <br><br>    <li>取得字符串数组</li><br>    strArray【1】:${strArray[1] }<br>        <br><br>    <li>取得对象数组</li><br>    User【5】:${users[5].userName }<br>        <br><br>    <li>取得List</li><br>    userList【6】.userName:${userList[6].userName }<br>        <br><br>    <li>el对表达式运算符的支持</li><br>    1+1=${1+1 }<br>    10/5=${10/5 }<br>    10 div 5 =${10 div 5 }<br>    10% 3=${10 % 3 }<br>    10 mod 3=${10 mod 3 }<br>        <br><br>    <li>测试empty</li><br>    v1:${empty v1 }<br>    v2:${empty v2 }<br>    v3:${empty v3 }<br>    v4:${empty v4 }<br>    v5:${empty v5 }<br>    </body>

0 0
原创粉丝点击