EL表达式
EL只负责显示,并不能创建JavaBean和设置属性
优点:
- 简洁优雅
- 可访问嵌套属性
- 可以访问集合
- 能更好的处理null(是null时不显示)
用法
- ${对象} 对象.toString() 为null时不显示
- ${对象.属性} 对象对应属性的值 无此属性抛出PropertyNotFoundException
- ${map.key} Map中对应key的value
- ${数组/list [下标]} 数组或集合对象下标的值 下标即使越界也不会抛出异常
- ${param.paramaname} 相当于request.getParameter(paramname);
- ${paramValues.paramname[下标]} 取得复选框中选中了的数组下标对应的值 不会有下标越界异常
- ${cookie.cookiename.value} 对应cookie的value
- ${initParam.上下文参数名} 上下文参数的值
- ${算术运算符} 显示运算结果 \${4 div 1 } 4/1是以double的形式除的 结果为4.0
- ${关系运算符} 显示运算结果 \${objct == null } 返回true,false
- ${逻辑运算符} 显示运算结果 \${!true } false
servlet中的代码:设置Attribute
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("user", new UserInfo("wemz", "", "wemz@home.com"));
request.setAttribute("date", new Date());
Object object = null;
request.setAttribute("object", object);
int[] arr = {1,2,3,4,5};
request.setAttribute("arr",arr );
List list = new ArrayList();
list.add("one");list.add("two");list.add("three");
request.setAttribute("list", list);
Map hashMap = new HashMap();
hashMap.put("key1", "value1");hashMap.put("key2", "value2");
request.setAttribute("hashMap", hashMap);
String temp = "key2";
request.setAttribute("temp", temp);
RequestDispatcher rd = request.getRequestDispatcher("/UseBean/ELDemo.jsp");
rd.forward(request, response);
}
JSP代码
<body>
<%-- 对象类型 --%>
<%-- 直接放对象相当调用对象的toString()显示出来 --%>
${date } <br>
${user } <br>
<%-- 对象.属性 显示的是对象对应的属性的值 --%>
${user.firstName } <br>PropertyNotFoundException
${user.firstNamess } <br> --%>
<%-- EL表达式如果是null则他不会显示 --%>
${object } <br>
<hr>
<%-- 数组 list类型 --%>
<%-- 数组对象[下标] 来显示数组对象对应下标的值 --%>
${arr[0] } <br>
${arr["0"] } <br>
${arr[1] } <br>
${arr[2] } <br>
${list[0] } <br>
${list["0"] } <br>
${list[1] } <br>
${list[2] } <br>
<hr>
<%-- Map类型 --%>
<%-- 对象.key 来显示key对应的value --%>
${hashMap.key1 } <br>
${hashMap["key1"] } <br>
<hr>
</body>
结果
不同作用域的EL
当作用域不同名相同的两个Attribute
优先级: page>request>session>application
request.setAttribute("ELTest", "request EL");
HttpSession session = request.getSession();
session.setAttribute("ELTest", "session EL");
${ELTest } = \${requestScope.ELTest }
可以通过 ${sessionScope.ELTest } 指定session域的ELTest
关于[]中的”“
如果在[ ]操作符中,没有使用引号,EL会把它当作表达式,它会把这个表达式当作属性计算
Map hashMap = new HashMap();
hashMap.put("key1", "value1");
hashMap.put("key2", "value2");
request.setAttribute("hashMap", hashMap);
String temp = "key2";
request.setAttribute("temp", temp);
${temp} => “key2”
${hashMap[temp] } = \${hashMap[“key2”] } 显示的值为 value2
但是在数组或集合里,[]中的”“不影响
${arr[0] }
${arr["0"] }
结果是一样的,都是取的数组arr中第一个元素