sxt_ (011) _ The Add books

First, the database design  

create table book(
    bookid int auto_increment primary key,
    bookname varchar(16),
    bookprice double,
    bookauthor varchar(10),
    bookdate date

);


insert into book(bookname,bookprice,bookauthor,bookdate) values('java1',88.01,'akr1','2018-6-1');
insert into book(bookname,bookprice,bookauthor,bookdate) values('java2',88.02,'akr2','2018-6-2');
insert into book(bookname,bookprice,bookauthor,bookdate) values('java3',88.03,'akr3','2018-6-3');
insert into book(bookname,bookprice,bookauthor,bookdate) values('java4',88.04,'akr4','2018-6-4');
insert into book(bookname,bookprice,bookauthor,bookdate) values('java5',88.05,'akr5','2018-6-5');

Second, display books demo

  2.1 Create a new web project

  2.2 introducing the required jar package

  2.3 book entity class

package edu.aeon.booksys.entity;

import java.util.Date;
/**
 * [说明]:book实体类
 * @author qq1584875179
 *
 */
public class Book {
    private int bookId;
    private String bookName;
    private double bookPrice;
    private String bookAuthor;
    private Date bookDate;
    public Book() {
    }
    
    public Book(String bookName, double bookPrice, String bookAuthor, Date bookDate) {
        super();
        this.bookName = bookName;
        this.bookPrice = bookPrice;
        this.bookAuthor = bookAuthor;
        this.bookDate = bookDate;
    }
    
    
    public Book(int bookId, String bookName, double bookPrice, String bookAuthor, Date bookDate) {
        super();
        this.bookId = bookId;
        this.bookName = bookName;
        this.bookPrice = bookPrice;
        this.bookAuthor = bookAuthor;
        this.bookDate = bookDate;
    }

    public int getBookId() {
        return bookId;
    }
    public void setBookId(int bookId) {
        this.bookId = bookId;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public double getBookPrice() {
        return bookPrice;
    }
    public void setBookPrice(double bookPrice) {
        this.bookPrice = bookPrice;
    }
    public String getBookAuthor() {
        return bookAuthor;
    }
    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }
    public Date getBookDate() {
        return bookDate;
    }
    public void setBookDate(Date bookDate) {
        this.bookDate = bookDate;
    }
    
}

   2.4 DBUtils Tools

Package edu.aeon.utils; 

Import java.io.IOException;
 Import a java.io.InputStream;
 Import the java.sql.Connection;
 Import the java.sql.DriverManager;
 Import java.sql.PreparedStatement;
 Import the java.sql.ResultSet;
 Import java.sql.SQLException;
 Import the java.sql.Statement;
 Import the java.util.Properties; 

/ ** 
 * [Description]: jdbc tools 
 * repeat steps encapsulates inside jdbc: database connection and release database resources 
 * @ author qq1584875179 
 * @version 1.2 (version connects the various databases the database configuration information (user name, password, and the drive url) to extract the profile alone)
  * / 
public  class DBUtils {
    private static String username;
    private static String password;
    private static String driverClass;
    private static String url;
    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;
    /**
     * 静态代码块处理读取之前的数据
     */
    static{
        InputStream inputStream = DBUtils.class.getClassLoader().getResourceAsStream("config/database/database.properties");
        Properties properties=new Properties();
        try {
            properties.load(inputStream);
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            driverClass = properties.getProperty("driverClass");
            url = properties.getProperty("url");
        } catch (IOException e) {
            System.out.println("初始化读取数据库配置文件--->database.properties失败!");
            e.printStackTrace();
    
     * database connection/ **
    }
        }
     * @Throws a ClassNotFoundException 
     * @throws SQLException
      * / 
    public   void getMySqlConnection () {
        the try { 
             the Class.forName (driverClass); 
             Connection = the DriverManager.getConnection (URL, username, password); 
        } the catch (Exception E) { 
            e.printStackTrace () ; 
        } 
    } 
    / ** 
     * [Description]: update :( add, delete, change) 
     * @param SQL statement SQL 
     * @param Objects variable parameter array 
     * @return updateNum: the number of rows updated after impact
     */
    public int executeUpdate(String sql,Object...objects){
        this.getMySqlConnection();
        int updateNum = 0;
        try {
            preparedStatement=connection.prepareStatement(sql);
            if(objects!=null){
                for(int i=0;i<objects.length;i++){
                    preparedStatement.setObject((i+1), objects[i]);
                }
            }
            updateNum=preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.closeDB(resultSet, preparedStatement, connection);
        }
        return updateNum;
    }
    
    public ResultSet getAll(String sql,Object...objects){
        this.getMySqlConnection();
        try {
            preparedStatement=connection.prepareStatement(sql);
            if(objects!=null){
                for(int0 = I; I <objects.length; I ++ ){
                    PreparedStatement.setObject ((I + 1'd ), Objects [I]); 
                } 
            } 
            the resultSet = PreparedStatement.executeQuery (); 
        } the catch (SQLException E) { 
            e.printStackTrace (); 
        } / * a finally {// Why can not switch off: Turn off because finding out the data after 
            this.closeDB (resultSet, preparedStatement, Connection); 
        } * / 
        return resultSet; 
    } 
    / ** 
     * release the database resources 
     * @param resultSet result set 
     * @paramsql statement statement execution objects 
     *@param Connection database connection object
      * / 
    public  static  void closedb (the resultSet the ResultSet, the Statement Statement, Connection Connection) {
         IF ( null =! the resultSet) {
             the try { 
                ResultSet.close (); 
            } the catch (SQLException E) { 
                the System.out. the println ( "failed to release the database resources ---> the resultSet!" ); 
                e.printStackTrace (); 
            } 
        } 
        IF ( null ! = Statement) {
             the try{ 
                Statement.close ();
            } The catch (SQLException E) { 
                System.out.println ( "failed to release the database resources ---> Statement!" ); 
                E.printStackTrace (); 
            } 
        } 
        IF ( null ! = Connection) {
             the try { 
                Connection.close () ; 
            } the catch (SQLException E) { 
                System.out.println ( "failed to release the database resources ---> Connection!" ); 
                e.printStackTrace (); 
            } 
        } 
    } 
}

  2.5database.properties  

username=root
password=root
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/booksys

  2.6 BookDao  

package edu.aeon.booksys.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import edu.aeon.booksys.entity.Book;
import edu.aeon.utils.DBUtils;
/**
 * [说明]:dao
 * @author qq:1584875179
 *
 */
public class BookDao extends DBUtils{
    public List<Book> getAll(){
        List<Book> bookList=new ArrayList<Book>();
        ResultSet resultSet=this.getAll("select * from book");
        try {
            while(resultSet.next()){
                bookList.add(new Book(resultSet.getInt(1), resultSet.getString(2), resultSet.getDouble(3), resultSet.getString(4), resultSet.getDate(5)));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return bookList;
    }
    //测试
    public static void main(String[] args) {
        BookDao bookDao=new BookDao();
        List<Book> bookList=bookDao.getAll();
        for (Book book : bookList) {
            System.out.println(book.getBookId()+"\t"+book.getBookName());
        }
    }
}

  2.7 shows a list of books servlet: ListBookServlet  

package edu.aeon.booksys.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.aeon.booksys.dao.BookDao;
import edu.aeon.booksys.entity.Book;
/**
 * [说明]:查询书籍列表的servlet
 * @author qq:1584875179
 *
 */
public class ListServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BookDao bookDao=new BookDao();
        List<Book> bookList=bookDao.getAll();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter=response.getWriter();
        printWriter.print("<html>");
        printWriter.print("<head><title>显示书籍列表</title></head>");
        printWriter.print("<body>");
        printWriter.print("<table border='1' align='center' width='60%'>");
        printWriter.print("<th>书籍号</th>");
        printWriter.print("<th>书籍名</th>");
        printWriter.print("<th>书籍价格</th>");
        printWriter.print("<th> Books Author </ TH> " for);
        " <th> Books Publication Date </ TH> "
        printWriter.print ();(int i=0;i<bookList.size();i++){
            printWriter.print("<tr>");
            printWriter.print("<td>"+bookList.get(i).getBookId()+"</td>");
            printWriter.print("<td>"+bookList.get(i).getBookName()+"</td>");
            printWriter.print("<td>"+bookList.get(i).getBookPrice()+"</td>");
            printWriter.print("<td>"+bookList.get(i).getBookAuthor()+"</td>");
            printWriter.print("<td>"+bookList.get(i).getBookDate()+"</td>");
            printWriter.print("</tr>");
        }
        printWriter.print("</table");
        printWriter.print("</body>");
        printWriter.print("</html>");
    }
}

  2.8 servlet configuration in web.xml

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>booksys</display-name>
  <servlet>
      <servlet-name>listServlet</servlet-name>
      <servlet-class>edu.aeon.booksys.servlet.ListServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>listServlet</servlet-name>
      <url-pattern>/listBookServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

 

  2.9 Test Results

    

 

Guess you like

Origin www.cnblogs.com/aeon/p/10989867.html
011