EL表达式

EL表达式

不要在JSP直接写Java代码,使用EL表达式和JSTL标签简化JSP里的Java代码。

注意:要在对应的JSP文件头中添加<%@page isELIgnored="false"%>启用EL表达式,不然会访问不到request域中的值。

//ServletDemo1.java 将brands数据封装到request域中
@WebServlet("/demo1")
public class ServletDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 准备数据,将来连接数据库
        List<Brand> brands = new ArrayList<Brand>();
        brands.add(new Brand(1, "三只松鼠", "三只松鼠", 100, "三只松鼠,好吃不上火", 1));
        brands.add(new Brand(2, "优衣库", "优衣库", 200, "优衣库,服适人生", 0));
        brands.add(new Brand(3, "小米", "小米科技有限公司", 1000, "为发烧而生", 1));

        // 2. 存储到request域中
        req.setAttribute("brands", brands);

        // 3. 转发到el-demo.jsp
        req.getRequestDispatcher("/el-demo.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false"%>   <%--启用EL表达式--%>
<html>
<head>
    <title>Title</title>
</head>
<body>
${brands}   <%--访问request域中的brands的值--%>
</body>
</html>

JavaWeb中的四大域对象

范围大小如图(常用的是request域和session域):

el表达式获取数据,会依次从这4个域中寻找,直到找到为止。