输出一表格,表格中有5个学生的信息,表格包含学号,姓名,年龄,性别,地址的信息。这里的学生对象及集合对象,在Servlet中创建,转发给jsp显示。(注意:Servlet使用的是Request域传值,所以跳转方式为转发形式,JSP使用的是"原生态"语法,没有使用EL表达式,直接与Html拼接而成)
后端代码:

package com.atguigu.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.bean.Student;

public class StudetServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<Student> list = new ArrayList<>();
		list.add(new Student(1, "章登", 22, "男", "河北保定"));
		list.add(new Student(2, "朱一龙", 23, "男", "河南郑州"));
		list.add(new Student(3, "孙悟空", 500, "公", "花果山"));
		list.add(new Student(4, "王靖雯", 23, "女", "哈尔滨"));
		list.add(new Student(5, "猪八戒", 1500, "公", "高老庄"));
		request.setAttribute("list", list);
		request.getRequestDispatcher("Student.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

JSP代码:

<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.atguigu.bean.Student" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
	table{
		width: 500px;
		border: 1px solid red;
		border-collapse: collapse;
	}
	th , td{
		border: 1px solid red;
	}
</style>
</head>
<body>
	<h1>request域取值</h1>
		<% List<Student> list = (List)request.getAttribute("list");%>
	<table>
		<tr>
			<th>学号</th>
			<th>姓名</th>
			<th>年龄</th>
			<th>性别</th>
			<th>地址</th>
		</tr>
		<% for(Student student:list){ %>
		<%="<tr>" %>
			<%="<td>"+student.getStuNo()+"</td>"%>
			<%="<td>"+student.getStuName()+"</td>"%>
			<%="<td>"+student.getStuAge()+"</td>"%>
			<%="<td>"+student.getStuSex()+"</td>"%>
			<%="<td>"+student.getAddress()+"</td>"%>
		<%="</tr>" %>
		<% } %>
	</table>
</body>
</html>

结果:
在这里插入图片描述

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐