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服務器中進行訪問結果如下圖所示

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM