java web 学习 --第十天(Java三级考试)

第九天学习内容:http://www.cnblogs.com/tobecrazy/p/3470195.html

需求概述

创建程序模块,读取并显示数据库中的书籍信息。当前有如下需求:需要显示数据库中所有登记的书籍信息,需要显示的字段信息包括ISBN、title、copyright、editionNumber、price。数据保存在数据库中,数据表名称为:tbl_books。编写程序实现该需求。

实现说明

1)采用MVC设计模式, 在JSP页面(listbook.jsp)中显示所有图书;

2)采用自定义标签技术,实现图书列表的显示;

3)创建JAVABEAN作为业务逻辑类,访问数据库资源;

4)数据库配置信息的管理,如:驱动名称,连接字符串,用户名,密码必须从配置文件中读取。

首先创建表,并插入数据:

java web 学习 --第十天(Java三级考试)
/*

MySQL Data Transfer

Source Host: localhost

Source Database: test

Target Host: localhost

Target Database: test

Date: 2010-10-13 15:26:26

*/



SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------

-- Table structure for tbl_books

-- ----------------------------

CREATE TABLE `tbl_books` (

  `isbn` varchar(20) NOT NULL,

  `title` varchar(100) NOT NULL,

  `editionNumber` int(11) NOT NULL,

  `copyright` varchar(4) NOT NULL,

  `publisherID` int(11) NOT NULL,

  `imageFile` varchar(20) NOT NULL,

  `price` double NOT NULL,

  PRIMARY KEY  (`isbn`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;



-- ----------------------------

-- Records 

-- ----------------------------

INSERT INTO `tbl_books` VALUES ('0130125075', 'Java How to Program (Java 2)', '3', '2000', '1', 'jhtp3.jpg', '70');

INSERT INTO `tbl_books` VALUES ('0130161438', 'Internet and World Wide Web How \r\n\r\nto Program', '1', '2000', '1', 'iw3htp1.jpg', '70');

INSERT INTO `tbl_books` VALUES ('0130284173', 'XML How to Program', '1', '2001', '1', 'xmlhtp1.jpg', '70');

INSERT INTO `tbl_books` VALUES ('0130284181', 'Perl How to Program', '1', '2001', '1', 'perlhtp1.jpg', '70');

INSERT INTO `tbl_books` VALUES ('013028419x', 'e-Business and e-Commerce How to \r\n\r\nProgram', '1', '2001', '1', 'ebechtp1.jpg', '70');

INSERT INTO `tbl_books` VALUES ('0130829277', 'The Complete Java Training Course \r\n\r\n(Java 1.1)', '2', '1998', '2', 'javactc2.jpg', '100');

INSERT INTO `tbl_books` VALUES ('0130829293', 'The Complete Visual Basic 6 \r\n\r\nTraining Course', '1', '1999', '2', 'vbctc1.jpg', '110');

INSERT INTO `tbl_books` VALUES ('0130852473', 'The Complete Java 2 Training \r\n\r\nCourse', '3', '2000', '2', 'javactc3.jpg', '110');

INSERT INTO `tbl_books` VALUES ('0130856118', 'The Complete Internet and World \r\n\r\nWide Web Programming Training Course', '1', '2000', '2', 'iw3ctc1.jpg', '110');

INSERT INTO `tbl_books` VALUES ('0130895601', 'Advanced Java 2 Platform How to \r\n\r\nProgram', '1', '2002', '1', 'advjhtp1.jpg', '70');

INSERT INTO `tbl_books` VALUES ('0130895717', 'C++ How to Program', '3', '2001', '1', 'cpphtp3.jpg', '70');

INSERT INTO `tbl_books` VALUES ('0130895725', 'C How to Program', '3', '2001', '1', 'chtp3.jpg', '70');

INSERT INTO `tbl_books` VALUES ('0132261197', 'C How to Program', '2', '1994', '1', 'chtp2.jpg', '50');

INSERT INTO `tbl_books` VALUES ('0134569555', 'Visual Basic 6 How to Program', '1', '1999', '1', 'vbhtp1.jpg', '70');

INSERT INTO `tbl_books` VALUES ('0135289106', 'C++ How to Program', '2', '1998', '1', 'cpphtp2.jpg', '50');

INSERT INTO `tbl_books` VALUES ('0138993947', 'Java How to Program (Java 1.1)', '2', '1998', '1', 'jhtp2.jpg', '50');

INSERT INTO `tbl_books` VALUES ('0139163050', 'The Complete C++ Training Course', '3', '2001', '2', 'cppctc3.jpg', '110');
View Code

 

创建一个web project

添加一个Servlet,命名为BookAction

package com.web;



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 com.service.BookService;



public class BookAction extends HttpServlet {



    /**

     * Constructor of the object.

     */

    public BookAction() {

        super();

    }



    /**

     * Destruction of the servlet. <br>

     */

    public void destroy() {

        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }



    /**

     * The doGet method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to get.

     * 

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        

        doPost(request,response);



        /*response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out

                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

        out.println("<HTML>");

        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");

        out.println("  <BODY>");

        out.print("    This is ");

        out.print(this.getClass());

        out.println(", using the GET method");

        out.println("  </BODY>");

        out.println("</HTML>");

        out.flush();

        out.close();*/

    }



    /**

     * The doPost method of the servlet. <br>

     *

     * This method is called when a form has its tag value method equals to post.

     * 

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        

        BookService bookservice=new BookService();

        List booklist=bookservice.getBookList();

        request.getSession().setAttribute("booklist", booklist);

        request.getRequestDispatcher("listbook.jsp").forward(request, response);



        /*response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out

                .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

        out.println("<HTML>");

        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");

        out.println("  <BODY>");

        out.print("    This is ");

        out.print(this.getClass());

        out.println(", using the POST method");

        out.println("  </BODY>");

        out.println("</HTML>");

        out.flush();

        out.close();*/

    }



    /**

     * Initialization of the servlet. <br>

     *

     * @throws ServletException if an error occurs

     */

    public void init() throws ServletException {

        // Put your code here

    }



}

 

创建book 类,生成get/set method

java web 学习 --第十天(Java三级考试)
ackage bookpojo;



public class Book {



    private String isbn;

    private String title;

    private double price;

    public String getIsbn() {

        return isbn;

    }

    public void setIsbn(String isbn) {

        this.isbn = isbn;

    }

    public String getTitle() {

        return title;

    }

    public void setTitle(String title) {

        this.title = title;

    }

    public double getPrice() {

        return price;

    }

    public void setPrice(double price) {

        this.price = price;

    }

    

     

    

}
View Code

 

创建一个bookservice 类,使用properties拿到数据库相关配置,之后把查询结果放到List中

java web 学习 --第十天(Java三级考试)
package com.service;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

import java.util.Properties;



import bookpojo.Book;



 



public class BookService {

    static  String driver ;//="com.mysql.jdbc.Driver";

    static  String url;//="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";

    static  String user;//="root";

    static  String password;//="3edc4rfv";

    public BookService()

    {

        try{

            Properties p=new Properties();

            p.load(this.getClass().getResourceAsStream("db.properties"));        

            driver=p.getProperty("driver");

            url=p.getProperty("url");

            user=p.getProperty("username");

            password=p.getProperty("password");

            System.out.println(driver+url+user+password);

        }

        catch(Exception e)

        {

            e.printStackTrace();

        }

    }

    

    public List getBookList()

    {

        List list=new ArrayList();

        try{

            Class.forName(driver);

            Connection con= DriverManager.getConnection(url,user,password);

            Statement stmt=con.createStatement();

            java.sql.ResultSet rs=stmt.executeQuery("select * from tbl_books;");

            while(rs.next())

            {

                Book book=new Book();

                book.setIsbn(rs.getString("isbn"));

                book.setPrice(rs.getDouble("price"));

                book.setTitle(rs.getString("title"));

                list.add(book);

                

            }

            

            rs.close();

            con.close();

            

            

        }

        catch(Exception e)

        {

            e.printStackTrace();

        }

        

        return  list;

        

    }



}
View Code

创建一个BookTagHandle继承 SimpleTagSupport 

java web 学习 --第十天(Java三级考试)
package com.tag;



import java.io.IOException;

import java.util.List;



import javax.servlet.jsp.JspException;

import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.tagext.SimpleTagSupport;



import bookpojo.Book;



public class BookTagHandle extends SimpleTagSupport {



    @Override

    public void doTag() throws JspException, IOException {

        // TODO Auto-generated method stub

        JspWriter out=this.getJspContext().getOut();

        List<Book> list=(List<Book>) this.getJspContext().findAttribute("booklist");

        for(Book o:list)

        {

           out.print(o.getIsbn()+"\t"+o.getTitle()+"\t"+o.getPrice()+"<br>");    

        }

        

    }



}
View Code

将mysql-connector5.0-bin.jar放在WebRoot/WEB-INF/lib目录下

将自定义标签放在WebRoot/WEB-INF,名字为book.tld

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"

  "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

  <tlibversion>1.0</tlibversion>

  <jspversion>1.1</jspversion>

  <shortname>Application Tag Library</shortname>

  <uri>http://jakarta.apache.org/taglibs/struts-example-1.0</uri>

  <info></info>



  <tag>

    <name>display</name>

    <tagclass>com.tag.BookTagHandle</tagclass>

    <bodycontent>empty</bodycontent>

    <info></info>

     

  </tag>

   

</taglib>

在booklist.jsp页面添加

<%@ taglib uri="WEB-INF/book.tld" prefix="book" %> 

在body标签添加

java web 学习 --第十天(Java三级考试)
<td width="695">

                    <table>

                        <tr>

                            <td width="3%">

                                &nbsp;

                            </td>

                            <td width="97%">

                                <table width="688">

                                    <tr>

                                        <TD width='20%' height="30" align='center'>

                                            ISBN

                                        </TD>

                                        <TD width='40%' align='center'>

                                            TITLE

                                        </TD>

                                         

                                        <TD align='center' width="20%">

                                            PRICE

                                        </TD>

                                    </tr>

                                    <tr>

                                        <td colspan='5'>

                                        <book:display/>

                                        </td>

                                    </tr>
View Code

大功告成

你可能感兴趣的:(Java Web)