1.对属性进行封装
package stu; public class Student { private String name; private int sex; private String major; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
2.创建servlet项目
package stu; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; @WebServlet(name = "StuListServlet", value = "/StuListServlet") public class StuListServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Student> students=new ArrayList<>(); Student stu1=new Student(); stu1.setName("刘德华"); stu1.setSex(1); stu1.setMajor("软件工程"); students.add(stu1); Student stu2=new Student(); stu2.setName("张曼玉"); stu2.setSex(0); stu2.setMajor("数字媒体"); students.add(stu2); Student stu3=new Student(); stu3.setName("张学友"); stu3.setSex(1); stu3.setMajor("软件工程"); students.add(stu3); request.setAttribute("students", students); request.getRequestDispatcher("stuList.jsp").forward(request, response); } // @Override // protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // // } }
3.导入jar包
下载地址:https://tomcat.apache.org/taglibs/standard/
添加到依赖中
4.创建jsp文件
<%@ page import="java.util.List" %> <%@ page import="java.util.ArrayList" %><%-- Created by IntelliJ IDEA. User: 璀璨的SUN Date: 2022/10/17 Time: 18:37 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!-- 引入核心标签库 --> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</title> </head> <body> <%--效果一代码--%> <%--<table border="1">--%> <%-- <tr><th>姓名</th><th>性别</th><th>专业</th></tr>--%> <%-- <c:forEach var="stu" items="${students}">--%> <%-- <tr>--%> <%-- <td>${stu.name}</td>--%> <%-- <td>${stu.sex==0?'女':'男'}</td>--%> <%-- <td>${stu.major}</td></tr>--%> <%-- </c:forEach>--%> <%--</table>--%> <%--效果二代码--%> <% List<String> names=new ArrayList<>(); names.add("刘德华"); names.add("张曼玉"); names.add("张学友"); request.setAttribute("names", names); %> <c:forEach var="name" items="${names}"> <br>${name} </c:forEach> </body> </html>
5.引入核心库标签
<!-- 引入核心标签库 --> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
6.配置web.xml
7.运行效果
效果一:
效果二: