今天搞一下el和jstl表达式
maven项目
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html > <html> <head> <title>Insert title here</title> </head> <body> <a href="./DataServlet">链接</a> </body> </html>
DataServlet
package com.jd.area.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jd.vo.Area; public class DataServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("age", 12); request.setAttribute("area", new Area("a","b","c","d")); request.setAttribute("names", new String[] {"1","2","3","4"}); request.getRequestDispatcher("target.jsp").forward(request, response); } }
Area类
package com.jd.vo; public class Area { private String id; private String name; private String code; private String parentCode; public Area(String id, String name, String code, String parentCode) { this.id = id; this.name = name; this.code = code; this.parentCode = parentCode; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getParentCode() { return parentCode; } public void setParentCode(String parentCode) { this.parentCode = parentCode; } }
target.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="zzu" %> <!DOCTYPE html > <html> <head> <title>Insert title here</title> </head> <body> <!--基本数据类型或String类型${key} --> ${age} <!--自定义类型:${key.成员变量} --> ${area.id} ${area.name} ${area.code} ${area.parentCode} <!--数组:${数组名[索引]} --> ${names[0]} <!-- 数组遍历 --> <zzu:forEach var="name" items="${names }"> ${name } </zzu:forEach> </body> </html>
结果
12 a b c d 1 1 2 3 4
补充一下
web.xml文件还是需要2.5及以上版本
pom.xml里面加点东西
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>