虽然说jsp以后不怎么用了,但是多了解一些底层原理总归好。此处记录在maven中从加载依赖到进行输出的过程。一共分为
五个步骤
一、写jstl、servlet、jsp、taglibs的依赖
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- servlet的依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- jstl-->
<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>
二、在jsp文件中声明taglibs标签
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
三、准备一张实例表
四、书写servlet,假装从数据库取出数据,进行请求转发
servlet内容:
package com.fldwws.web;
import com.fldwws.pojo.Brand;
import com.sun.net.httpserver.HttpServer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
@WebServlet("/ser01")
public class ServletDemo extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//查询数据库
ArrayList<Brand> brands = new ArrayList<>();
brands.add(new Brand(1,"三只松鼠", "三只松鼠", 100, "三只松鼠好吃不伤害",1));
brands.add(new Brand(2,"优衣库", "优衣库公司", 200, "优衣库的衣服很好看吗",0));
brands.add(new Brand(3,"小米", "雷军的公司", 3000, "雷军喜欢说are you ok",1));
request.setAttribute("brands",brands);
request.getRequestDispatcher("foreach-demo.jsp").forward(request,response);
}
}
五、写jsp代码
①定一个表头
②写forEach标签
<%--User: 彭于晏 --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>foreach-demo</title>
</head>
<body>
<table border="3">
<tr>
<th>序号</th>
<th>品牌</th>
<th>公司</th>
<th>价格</th>
<th>描述</th>
<th>状态</th>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<td>${status.count}</td>
<td>${brand.brandName}</td>
<td>${brand.companyName}</td>
<td>${brand.ordered}</td>
<td>${brand.description}</td>
<c:if test="${brand.status == 1}">
<td>激活</td>
</c:if>
<c:if test="${brand.status == 0}">
<td>禁用🈲</td>
</c:if>
</tr>
</c:forEach>
</table>
</body>
</html>
效果
小结一下吧
这里需要注意的几个地方
①因为我使用的是写jmaven,所以stl、servlet、jsp、taglibs的依赖必须得倒
②你要使用c:if以及c:forEach标签,必须进行申明声明taglibs标签
③forEach里面有4个标签,items是一个集合,var是集合里的值,varstatus可以实现自增,用于定义序号这种
④if 的test里面写代码。$ {这里写代码 },就像<c:if test="${brand.status == 1}">
,而不是<c:if test="${brand.status} " == 1> 判断条件在冒号外面。为什么不报错呢???找那么久