jsp+EL+JSTL实现将数据库中的信息显示到jsp页面中
案例描述:将数据库中的所有学生的信息显示到浏览器页面。
创建数据库以及添加数据
create table student( sid int primary key auto_increment, sname varchar(20) not null, sex varchar(2) not null, age int ); //添加数据 insert into student(sname,sex,age)values ("张三","男",18), ("李四","男",18), ("王五","男",18), ("赵柳","男",18);
数据库截图
项目的整体结构
实体类-Student.java(用来存放数据)
package domain; /** * @author ztr * @version 创建时间:2021年4月18日 下午4:47:51 * 类说明 */ public class Student { private int sid; private String sname; private String sex; private int age; public Student(int sid, String sname, String sex, int age) { super(); this.sid = sid; this.sname = sname; this.sex = sex; this.age = age; } public Student() { super(); // TODO Auto-generated constructor stub } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [sid=" + sid + ", sname=" + sname + ", sex=" + sex + ", age=" + age + "]"; } }
model类-StudentModel(用来处理数据)
package model; import java.sql.Connection; import java.util.List; import utils.BaseDao; import utils.JdbcUtils; import domain.Student; /** * @author ztr * @version 创建时间:2021年4月18日 下午4:49:08 * 类说明 */ public class StudentModel { /** * 出库数据的java类 */ public List<Student> findAll(){ Connection connection = null; List<Student> list = null; try { connection = JdbcUtils.GetConnection(); String sql = "select * from student"; list = BaseDao.getList(connection, Student.class, sql); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ JdbcUtils.closeResource(connection, null); } return list; } }
utils包
工具类JdbcUtils.java(用来获取数据库连接以及资源的关闭)
package utils; import java.io.InputStream; import java.util.Properties; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; /** * @author ztr * @version 创建时间:2021年3月29日 上午10:20:16 类说明 */ /* * 获取连接 * * @return Connection */ public class JdbcUtils { public JdbcUtils() { super(); // TODO Auto-generated constructor stub } private static DataSource source; static { try { Properties pro = new Properties(); InputStream is = JdbcUtils.class.getClassLoader() .getResourceAsStream("druid.properties"); pro.load(is); source = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection GetConnection() throws Exception { Connection connection = source.getConnection(); return connection; } /* * 关闭资源 */ public static void closeResource(Connection connection, PreparedStatement ps) { try { if (ps != null) ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (connection != null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * 关闭资源 */ public static void closeResource1(Connection connection, PreparedStatement ps, ResultSet rs) { try { if (ps != null) ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (connection != null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (rs != null) rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
工具类-BaseDao.java(用来获取数据库中的数据)
package utils; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.List; /** * @author ztr * @version 创建时间:2021年4月16日 上午11:21:09 类说明 */ public class BaseDao { // 通用的增删改操作 public static void update(Connection connection, String sql, Object... args) { // 获取数据连接 // 预编译sql语句返回preparedStatement PreparedStatement prepareStatement = null; try { prepareStatement = connection.prepareStatement(sql); // 填充占位符 // prepareStatement.setObject的下标从1开始 for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } // 执行 prepareStatement.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 资源的关闭 JdbcUtils.closeResource(null, prepareStatement); } } /** * 返回一个数据 * * @param clazz * @param sql * @param args * @return */ public static <T> T GetInstance(Connection connection, Class<T> clazz, String sql, Object... args) { PreparedStatement prepareStatement = null; // 获取结果集 ResultSet resultSet = null; try { prepareStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } resultSet = prepareStatement.executeQuery(); // 获取元数据 ResultSetMetaData metaData = resultSet.getMetaData(); // 通过metaData获取结果集中的列数 int columnCount = metaData.getColumnCount(); if (resultSet.next()) { T newInstance = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { // 获取列值 Object columnValue = resultSet.getObject(i + 1); // 获取每列的列名 String columnName = metaData.getColumnLabel(i + 1); // 利用反射 Field field = clazz.getDeclaredField(columnName); // 考虑该属性是否为私有 field.setAccessible(true); field.set(newInstance, columnValue); } return newInstance; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 关闭资源 JdbcUtils.closeResource1(null, prepareStatement, resultSet); } return null; } /** * 返回多条数据 * @param connection * @param clazz * @param sql * @param args * @return */ public static <T> List<T> getList(Connection connection, Class<T> clazz, String sql, Object... args) { PreparedStatement prepareStatement = null; // 获取结果集 ResultSet resultSet = null; try { prepareStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } resultSet = prepareStatement.executeQuery(); // 获取元数据 ResultSetMetaData metaData = resultSet.getMetaData(); // 通过metaData获取结果集中的列数 int columnCount = metaData.getColumnCount(); // 创建集合对象 ArrayList<T> list = new ArrayList<T>(); while (resultSet.next()) { T newInstance = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { // 获取列值 Object columnValue = resultSet.getObject(i + 1); // 获取每列的列名 String columnName = metaData.getColumnLabel(i + 1); // 利用反射 Field field = clazz.getDeclaredField(columnName); // 考虑该属性是否为私有 field.setAccessible(true); field.set(newInstance, columnValue); } list.add(newInstance); } return list; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 关闭资源 JdbcUtils.closeResource1(null, prepareStatement, resultSet); } return null; } }
controller类-StudentServlet.java
package controller; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import domain.Student; import model.StudentModel; /** * Servlet implementation class StudentServlet */ public class StudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //调用java类处理数据 StudentModel model = new StudentModel(); List<Student> list = model.findAll(); //显示到jsp页面中 request.setAttribute("list",list); request.getRequestDispatcher("/jsp/list.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
jsp页面-list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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> </head> <body> <h1>学生信息显示页面</h1> <table border="1" width="600"> <tr> <td>学生编号</td> <td>学生姓名</td> <td>学生性别</td> <td>学生年龄</td> </tr> <c:forEach var = "student" items="${list }"> <tr> <td>${student.sid }</td> <td>${student.sname }</td> <td>${student.sex}</td> <td>${student.age }</td> </tr> </c:forEach> </table> </body> </html>
将web项目部署到tomcat服务器中进行访问结果如下图所示
笨鸟先飞