一、servlet部分
package com.aaa.servlet; import com.aaa.dao.IStudentDAO; import com.aaa.dao.Impl.StudentDAOImpl; 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.List; import java.util.Map; @WebServlet("/666") //虚拟路径 不用再配置xml文件 快捷 public class HttpServletDemo extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取数据库中的数据 IStudentDAO dao=new StudentDAOImpl(); List<Map<String, Object>> list = dao.getAllStudent(); /* 2.请求共享数据 就是需要servlet展示什么数据 req.setattribute("shuju",list) 展示list数据 名字叫shuju【关键字的作用】 因为这种文件可能 注意 ----关键字不能是数字! 会有很多 方便servlet找的到 我们所需要的JSP文件 */ req.setAttribute("shuju",list); //3.请求转发到某个JSP 3.1 新建JSP文件 day01.jsp req.getRequestDispatcher("day02.jsp").forward(req,resp); } }
二、JSP部分
<%@ page import="java.util.List" %> <%@ page import="java.util.Map" %> <%-- Created by IntelliJ IDEA. User: Administrator Date: 2019/4/16 Time: 8:31 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%-- 之前是在 JSP中写 java代码 ,发现这样写很麻烦 能否简化呢? 就需要用到 1.EL 和 2.JSTL 一、EL的功能? 1.等同于list <map<string,object>>list=(list <map<string,object>>).request.getAllStudent("key"); 获取数据 key 关键字 2.可以直接将数据显示在页面上。由此可以验证我们是否获得student数据 二、JSTL? 代替java代码 导包 两个 jstl 和 standa 添加 < %@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> < c:forEach var="stu" items="$ {shuju}" > 这里是一个 增强for 循环 var是设置变量 items =" ${ key }}" 获得数据连接 key关键字 放在 ${ key } 中。 <tr> <td>${stu.id}</td> 获得 id <td>${stu.name}</td> 获得 name <td>${stu.age}</td> 获得 age </tr> < /c:forEach> 三。注意 JSP的注释是 < % -- --% > --%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>Title</title> </head> <body> <h1>-------------------------------------------</h1> ${shuju} <!-- key关键字 这里不能 是数字--> <h1>--------------------------------------------</h1> <table border="1px" cellspacing="0" bgcolor="green"> <tr> <td>id</td> <td>name</td> <td>age</td> </tr> <c:forEach var="stu" items="${shuju}" > <tr> <td>${stu.id}</td> <td>${stu.name}</td> <td>${stu.age}</td> </tr> </c:forEach> </table> </body> </html>
原文:https://www.cnblogs.com/ZXF6/p/10727006.html