expression language
表达式语言
在JSP中,
如果想拿到服务器带回的数据可以用表达式脚本,但是这种方法太复杂。
<%@page import="com.xx.entity.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%User user=(User)request.getAttribute("user"); %>
username:<%=user.getUsername() %><br/>
password:<%=user.getPassword() %><br/>
</body>
</html>
用EL表达式来简洁的访问数据
语法${表达式}
例如${3/2}
,结果为1.5
- empty非空运算符
${empty ""}
空串返回true
${empty list}
长度为0的的列表返回true
${empty obj}
判断对象
jsp中四个作用域对象分别为
- pageContext、request、session、application
servlet的三个作用域对象
- HttpServletRequest、 HttpSession、 ServletContext
EL表达式可以获取作用域对象中的值
${作用域.变量名}
${作用域.对象名.属性名}
作用域对象 | 作用域 | 有效范围 |
---|---|---|
pageContext | pageScope | 当前页面有效 |
request | requestScope | 在一次请求内有效 |
session | sessionScope | 在一次会话内有效(默认30分钟) |
application | applicationScope | 在整个应用运行期间有效 |
例如:
- 存基本数据类型
Servlet中写:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("username", "admin");
request.getRequestDispatcher("test.jsp").forward(request, response);
}
jsp中两种方法取值:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
requestScope.username:${requestScope.username}<br/>
username:${username}<br/>
</body>
</html>
- 存User对象
Servlet中
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = new User();
user.setUsername("bob");
user.setPassword("123456");
request.setAttribute("user",user);
request.getRequestDispatcher("test.jsp").forward(request, response);
}
jsp中
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
requestScope.username:${requestScope.user.username}<br/>
requestScope.password:${requestScope.user.password}<br/>
username:${user.username}<br/>
password:${user.password}<br/>
</body>
</html>
总结:
若存在jsp的作用域对象中时,取值的时候可以直接取出,不需要写具体的那个作用域对象,
当每个作用域中都存了相同的值时候,若没有指定出作用域则按照以下顺序依次寻找,找不到返回空串。
pageContext–>request–>session–>application
谢谢!