目录
简介
表达式语言(Expression Language)EL ,主要功能是输出标志位上的数据信息,在JSP里面一共有四种标志位:page属性、request属性、session属性、application属性。
范例:两者比较
不用表达式
<%= request.getAttribute("msg")==null ? "" : request.getAttribute("msg")%>
用表达式
${msg}
基础语法
1、表达式语言需要与四种属性范围结合,形式:${属性名称},如果四种属性名称保存了相同的属性名称,使用:${属性标记.属性名称}。最好不要重名。
2、表达式不仅可以处理属性,还可以处理参数,形式:${param.参数名称}。例如:路径为:web的url?msg=hello,使用${param.msg}就可以在页面输出。同时可以加上逻辑判断,使用三目运算,逻辑列如:“==”
3、EL可以通过pageContext对对象处理;
${pageContext.request.contextPath}
在pageContext对象里面存在有getRequest()方法(request)、而HttpServletRequest接口才有getContextPath()方法(contextPath),如果依靠的是反射实际上是不关心返回类型的子类还是父类,通过反射都能找到方法。
4、既然EL支持反射处理,就意味着可以通过Servlet传递一个VO类对象
package cn.ren.vo;
public class Dept {
private Integer deptno;
private String dname;
}
public class Emp {
private Integer empno;
private String ename;
private Dept dept ;
}
package cn.ren.myservlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.ren.vo.Dept;
import cn.ren.vo.Emp;
@SuppressWarnings("serial")
public class ObjectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Dept dept = new Dept() ;
dept.setDeptno(001);
dept.setDname("test");
Emp emp = new Emp() ;
emp.setEmpno(7369);
emp.setEname("smith");
emp.setDept(dept);
request.setAttribute("emp", emp);
request.getRequestDispatcher("/show.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
<body>
${emp.empno} <br>
${emp.ename} <br>
${emp.dept.deptno} <br>
${emp.dept.dname} <br>
</body>
List集合输出与map集合输出
需要注意EL不支持Integer类型
JSTL
标签编程可以解决页面中的所有Scriplet,主要依靠的对象就是pageContext。在Java开发中,提供有JSTL(JSP的标准标签库),JSTL结合EL就可以消除Scriplet代码。
需要将JSTL开发包配置到项目开发中,在百度搜mvnresponsity可以找到。
主要使用的是c标签,常用:if标签、迭代标签、函数标签。
具体使用时再查看。