EL表达式用${}表示,可用在所有的HTML和JSP标签中 作用是代替JSP页面中复杂的JAVA代码.
一、语法
① ${域名称.键名}
jsp 4个域对象 pageContext、requestScope、session、applicationScope
②${键名}
表示依次从最小的域中查找是否有该键对应的值,直到找到为止
二、如何用el表达式取变量、数组、map、List
public class ElAction extends Action {
// @Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setAttribute("hello", "hello World!");
// 对象
Group group = new Group();
group.setName("java Group");
User user = new User();
user.setName("张北");
user.setAge(23);
user.setGroup(group);
request.setAttribute("user", user);
//Map
Map map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
request.setAttribute("map", map);
//数组
String[] strArr = new String[]{"a", "b" ,"cc"};
request.setAttribute("strArr", strArr);
//对像数组
User[] users = new User[10];
for(int i=0; i<10; i++){
User u = new User();
u.setName("u" + i);
users[i] = u;
}
request.setAttribute("users", users);
//List
List userList = new ArrayList();
for(int i=0; i<10; i++){
User uu = new User();
uu.setName("UU" + i);
userList.add(uu);
}
request.setAttribute("userList", userList);
return mapping.findForward("success");
}
}
jsp
<body>
<%=request.getAttribute("hello") %><br/>
<h2>普通变量</h2>
${hello}<br/>
${requestScope.hello}
<hr/>
<h2>对像</h2>
name: ${user.name }<br/>
age: ${user.age }<br/>
group: ${user.group.name }<br/>
<hr/>
<h2>map</h2>
map.key1 = ${map.key1 }<br/>
map.key2 = ${map.key2 }<br/>
<hr/>
<h2>数组</h2>
strArr[0] = ${strArr[0] }<br/>
strArr[2] = ${strArr[2] }<br/>
<hr/>
<h2>对像数组</h2>
users[2].username = ${users[2].name }<br/>
<hr/>
<h2>List</h2>
userList[2].username = ${userList[2].name }<br/>
</body>