<dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency>
<body> <h1> 我是JSP </h1> <% System.out.println("我是Java代码"); %> </body>
PS
_jspService()
方法中out.print()
中,作为out.print()
的参数_jspService()
方法之外,被类直接包含${expression}
${brands}
:获取域中存储的key为brands的数据Servlet
@WebServlet("/demo02") public class ServletDemo02 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.准备数据 List<Brand> brands = new ArrayList<>(); brands.add(new Brand(2,"优衣库","优衣库",200,"优衣库,服适人生",0)); brands.add(new Brand(3,"小米","小米科技有限公司",1000,"为发烧而生",1)); brands.add(new Brand(5,"华为","华为科技有限公司",1000,"为发烧而生",1)); brands.add(new Brand(6,"三只松鼠","三只松鼠",100,"三只松鼠,好吃不上火",1)); // 2.存储数据到request域中 request.setAttribute("brands", brands); request.setAttribute("username", "zhangsan2"); request.setAttribute("age", 162); // 3.转发到jsp request.getRequestDispatcher("04el.jsp").forward(request, response);
JSP
<body> username: ${username}<br/> brands: ${brands} </body>
JSP标准标签库(Jsp Standarded Library),使用标签取代JSP页面上的Java代码
eg
<c:if test="${flag == 1}"> 男 </c:if> <c:if test="${flag == 2}"> 女 </c:if>
1.导入坐标
<dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
2.在JSP页面上引入JSTL标签库
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3.使用
<c:if test="...">...</c:if>
,test用于定义条件表达式
<c:if test="${flag == 1}"> 男 </c:if> <c:if test="${flag == 2}"> 女 </c:if>
<c:forEach>
:相当于for循环(跟Java中的for循环类似,有增强for循环和普通for循环)
增强for循环
items
:被遍历的容器
var
:遍历产生的临时变量
varStatus
:遍历状态对象
<c:forEach items="${brands}" var="brand"> <tr align="center"> <td>${brand.id}</td> <td>${brand.brandName}</td> <td>${brand.companyName}</td> <td>${brand.description}</td> </tr> </c:forEach> <%--相当于Java代码中的增强for循环 for (Brand brand : brands) { Integer id = brand.getId(); String imgUrl = brand.getImgUrl(); String brandName = brand.getBrandName(); String companyName = brand.getCompanyName(); } --%>
普通for循环
begin
:开始数
end
:结束数
step
:步长
<c:forEach var="i" begin="0" end="10" step="1"> ${i} </c:forEach> <%--相当于Java代码中的普通for循环 for (int i = 0; i <= 10; i++) { System.out.println(i); } --%>