preface

Consolidate Servlet+JSP development mode, do a relatively complete small project.

Results figure

The project consists of two parts, foreground and background.

Foreground for display

Background for management

The project can be divided into five modules: classification module, user module, book module, purchase module, order module.


Set up the environment

Build package structure

Importing the Development Package

Foreground frames the page

  • Index.jsp [without the body tag]

  <frameset rows="25%, *">
    <frame src="${pageContext.request.contextPath}/client/head.jsp"/>
    <frame src="${pageContext.request.contextPath}/client/body.jsp"/>
  </frameset>

Copy the code
  • head.jsp
<body style="text-align: center">
<h1>Welcome to the mall</h1>

Copy the code
  • The body is a blank JSP page

  • Effect:


Background frame page

  • Manager.jsp [insert framset tag, also without body tag]

<frameset rows="25%, *">
    <frame src="${pageContext.request.contextPath}/background/head.jsp"/>

    <frameset cols="15%, *">
        <frame src="${pageContext.request.contextPath}/background/left.jsp"/>
        <frame src="${pageContext.request.contextPath}/background/body.jsp"/>
    </frameset>
</frameset>
Copy the code
  • head.jsp

<body style="text-align: center">
<h1>Background management</h1>

Copy the code
  • left.jsp


<a href="#">Classification management</a>

<br>
<br>
<a href="#">Books management</a>
<br>
<br>

<a href="#">The order management</a>
<br>
<br>

Copy the code
  • The body.jsp is blank

  • Effect:

Frame folder directory structure

It is worth noting:

  • The folder name cannot be “manager”; otherwise, 403 Access Denied is displayed
  • Frameset tags can be nested, using “COLs” for categories and “rows” for branches.

Import code for utility classes and methods

  • Filter Chinese garbled data
  • HTML escaping
  • DAOFactory
  • The JDBC connection pool
  • UUID tools
  • C3p0.xml configuration file

All of this code can be found in my blog category: Codebase!


Classification module

First, let’s do the classification module

Creating an entity Category

    private String id;
    private String name;
    private String description;

	// Various setters and getters
Copy the code

Create tables in the database


CREATE TABLE category (

  id          VARCHAR(40) PRIMARY KEY.name        VARCHAR(10) NOT NULL UNIQUE ,
  description VARCHAR(255));Copy the code

Write CategoryDAO


/** * Category module * 1: Add category * 2: Find category * 3: modify category ** ** /
public class CategoryImpl {

    public void addCategory(Category category) {

        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        String sql = "INSERT INTO category (id, name, description) VALUES(? ,? ,?) ";
        try {
            queryRunner.update(sql, new Object[]{category.getId(), category.getName(), category.getDescription()});

        } catch (SQLException e) {
            throw newRuntimeException(e); }}public Category findCategory(String id) {
        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());
        String sql = "SELECT * FROM category WHERE id=?";

        try {
            Category category = (Category) queryRunner.query(sql, id, new BeanHandler(Category.class));

            return category;

        } catch (SQLException e) {
            throw newRuntimeException(e); }}public List<Category> getAllCategory(a) {
        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());
        String sql = "SELECT * FROM category";

        try {
            List<Category> categories = (List<Category>) queryRunner.query(sql, new BeanListHandler(Category.class));

             return categories;
        } catch (SQLException e) {
            throw newRuntimeException(e); }}}Copy the code

Test the DAO


public class demo {

    @Test
    public void add(a) {

        Category category = new Category();
        category.setId("2");
        category.setName("Database Series");
        category.setDescription("This is the database series.");

        CategoryImpl category1 = new CategoryImpl();
        category1.addCategory(category);

    }

    @Test
    public void find(a) {

        String id = "1";
        CategoryImpl category1 = new CategoryImpl();
        Category category = category1.findCategory(id);

        System.out.println(category.getName());
    }
    @Test
    public void getAll(a) {


        CategoryImpl category1 = new CategoryImpl();
        List<Category> categories = category1.getAllCategory();

        for(Category category : categories) { System.out.println(category.getName()); }}}Copy the code

Extract into DAO interfaces


public interface CategoryDao {
    void addCategory(Category category);

    Category findCategory(String id);

    List<Category> getAllCategory(a);
}

Copy the code

Background page to add classification

  • On the hyperlink, the binding displays the page for adding categories

<a href="${pageContext.request.contextPath}/background/addCategory.jsp" target="body">Add the classification</a>

Copy the code
  • Displays the JSP page for adding categories


<form action="${pageContext.request.contextPath}/CategoryServlet? method=add" method="post">Classification Name:<input type="text" name="name"><br>Classification Description:<textarea name="description"></textarea><br>
    <input type="submit" value="Submit">

</form>

Copy the code
  • Handles servlets that add categories

        if (method.equals("add")) {

            try {
                // Encapsulate the data from the browser into a bean
                Category category = WebUtils.request2Bean(request, Category.class);
                category.setId(WebUtils.makeId());

                service.addCategory(category);
                request.setAttribute("message"."Added category succeeded!");

            } catch (Exception e) {
                request.setAttribute("message"."Failed to add category");
                e.printStackTrace();
            }
            request.getRequestDispatcher("/message.jsp").forward(request, response);

        }
Copy the code
  • Effect:


Background page view classification

  • On the hyperlink, bind the Servlet that handles the request

		else if (method.equals("look")) {

            List<Category> list = service.getAllCategory();
            request.setAttribute("list", list);
            request.getRequestDispatcher("/background/lookCategory.jsp").forward(request, response);

        } 
Copy the code
  • A JSP that displays the categorization page
< c: if test = "${empty (list)}" > not classified data oh, would you please add the < / c: if > < c: if test = "${! Empty (list)} "> < table border =" 1 px "> < tr > < td > classification name < / td > < td > classification description < / td > < td > action < / td > < / tr > < c: forEach items =" ${list}" Var = "category" > < tr > < td > ${category. The name} < / td > < td > ${category. The description} < / td > < td > < a href = "#" > delete < / a > < a Href = "#" > change < / a > < / td > < / tr > < / c: forEach > < / table > < / c: if >Copy the code
  • Effect:


The book module

Analysis of the

When designing library management, we should think of the relationship between books and classification. One category can correspond to more than one book.

Why is it designed this way? This is more humanized, when the user buys books, the user can view the relevant classified books, rather than all books are displayed to the user, let the user to find one by one.

The design entity


    private String id;
    private String name;
    private String author;
    private String description;
    private double price;

    // Remember the name of the picture
    private String image;

    // Remember the category id
    private String category_id;

	// Various setters and getters
Copy the code

Designing database tables


CREATE TABLE book (
  id          VARCHAR(40) PRIMARY KEY.name        VARCHAR(10) NOT NULL UNIQUE,
  description VARCHAR(255),
  author      VARCHAR(10),
  price       FLOAT,
  image       VARCHAR(100),
  category_id VARCHAR(40),
  CONSTRAINT category_id_FK FOREIGN KEY (category_id) REFERENCES category (id));Copy the code

Write the DAO



/** * Books module * 1: Add books * 2: view books * 3: find books page data */
public class BookDaoImpl {

    public void addBook(Book book) {

        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        String sql = "INSERT INTO book (id,name,description,author,price,image,category_id) VALUES(? ,? ,? ,? ,? ,? ,?) ";
        try {
            queryRunner.update(sql, new Object[]{book.getId(), book.getName(), book.getDescription(), book.getAuthor(), book.getPrice(),book.getImage(), book.getCategory_id()});

        } catch (SQLException e) {
            throw newRuntimeException(e); }}public Book findBook(String id) {

        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        String sql = "SELECT * FROM book WHERE id=?";

        try {
            return (Book) queryRunner.query(sql, id, new BeanHandler(Book.class));
        } catch (SQLException e) {
            throw newRuntimeException(e); }}/** Get page data for the book */
    public List<Book> getPageData(int start, int end) {

        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        String sql = "SELECT * FROM book limit ? That?";

        try {
            return (List<Book>) queryRunner.query(sql, new BeanListHandler(Book.class), new Object[]{start, end});
        } catch (SQLException e) {
            throw newRuntimeException(e); }}/** get paging data for books by category */
    public List<Book> getPageData(int start, int end,String category_id) {

        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        //WHERE is the limit?
        String sql = "SELECT * FROM book WHERE category_id=? limit ? That?";

        try {
            return (List<Book>) queryRunner.query(sql, new BeanListHandler(Book.class), new Object[]{ category_id,start, end});
        } catch (SQLException e) {
            throw newRuntimeException(e); }}/** * get the total number of books */
    public int getTotalRecord(a) {
        QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

        String sql = "SELECT COUNT(*) FROM book";

        try {
            return (int) queryRunner.query(sql, new ScalarHandler());
        } catch (SQLException e) {
            throw newRuntimeException(e); }}/** ** getCategoryTotalRecord */
    public long getCategoryTotalRecord(String category_id) {

        try {
            QueryRunner queryRunner = new QueryRunner(Utils2DB.getDataSource());

            String sql = "SELECT COUNT(*) FROM book WHERE category_id=?";
            return (long) queryRunner.query(sql, category_id, new ScalarHandler());

        } catch (SQLException e) {
            throw newRuntimeException(e); }}}Copy the code

Test the DAO


public class BookDemo {

    BookDaoImpl bookDao = new BookDaoImpl();


    @Test

    public void add(a) {
        Book book = new Book();
        book.setId("5");
        book.setName("SQLServer");
        book.setAuthor(I don't know.);
        book.setImage("33333332432");
        book.setPrice(33.22);
        book.setDescription("This is a good book.");
        book.setCategory_id("2");

        bookDao.addBook(book);
    }

    @Test
    public void look(a) {

        List<Book> bookList = bookDao.getPageData(3.3);

        for (Book book : bookList) {
            System.out.println(book.getName());
        }

        List<Book> books = bookDao.getPageData(0.2."2");

        for(Book book : books) { System.out.println(book.getName()); }}@Test
    public void find(a) {
        String id = "2"; Book book = bookDao.findBook(id); System.out.println(book.getName()); }}Copy the code

Extract into DAO interfaces


public interface BookDao {
    void addBook(Book book);

    Book findBook(String id);

    List<Book> getPageData(int start, int end);

    List<Book> getPageData(int start, int end, String category_id);

    long getTotalRecord(a);

   	long getCategoryTotalRecord(String category_id);
}

Copy the code

Write the Service layer


    /* Add books */
    public void addBook(Book book) {
        bookDao.addBook(book);

    }

    /* Find a book */
    public Book findBook(String id) {
        return bookDao.findBook(id);
    }

    /* Find a book */
    public Book findBook(String id) {
        return bookDao.findBook(id);
    }

    /* Get paging data for books */
    public Page getPageData(String pageNum) {
        
        Page page=null;
        if (pageNum == null) {
            page = new Page(1, bookDao.getTotalRecord());
        } else {
            page = new Page(Integer.valueOf(pageNum), bookDao.getTotalRecord());
        }

        List<Book> books = bookDao.getPageData(page.getStartIndex(), page.getLinesize());
        page.setList(books);
        
        return page;

    }

    /* Get pagination data */
    public Page getPageData(String currentPageCount,String category_id) {

        Page page=null;
        if (currentPageCount == null) {
            page = new Page(1, bookDao.getCategoryTotalRecord(category_id));
        } else {
            page = new Page(Integer.valueOf(currentPageCount), bookDao.getCategoryTotalRecord(category_id));
        }

        List<Book> books = bookDao.getPageData(page.getStartIndex(), page.getLinesize(), category_id);
        page.setList(books);
        return page;

    }


Copy the code

Background Add books

When adding a book in the background, you should specify the type of book.

To know the ids of all types on the page that displays the added book, you pass the set of types through a Servlet

Binding links


<a href="${pageContext.request.contextPath}/BookServlet? method=addUI" target="body">Add books</a><br>
Copy the code

A Servlet that delivers a collection of types


        String method = request.getParameter("method");
        BussinessServiceImpl service = new BussinessServiceImpl();

        if (method.equals("addUI")) {

            List<Category> list = service.getAllCategory();
            request.setAttribute("list", list);
            request.getRequestDispatcher("/background/addBook.jsp").forward(request, response);

        } 
Copy the code

Display JSP pages

<form action="${pageContext.request.contextPath}/BookServlet? method=add" method="post" enctype="multipart/form-data">

    <table border="1px" width="30%">
        <tr>
            <td>Book Name:</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>The author:</td>
            <td><input type="text" name="author"></td>
        </tr>
        <tr>
            <td>Book price:</td>
            <td><input type="text" name="price"></td>
        </tr>
        <tr>
            <td>Type:</td>
            <td>
                <select name="category_id">
                    <c:forEach items="${list}" var="category">
                        <option value="${category.id}">${category.name}</option>
                    </c:forEach>
                </select>
            </td>
        </tr>
        <tr>
            <td>To upload pictures</td>
            <td><input type="file" name="image"></td>
        </tr>
        <tr>
            <td>A detailed description</td>
            <td><textarea name="description"></textarea></td>
        </tr>
        <tr>
            <td>
                <input type="submit" value="Submit">
                <input type="reset" value="Reset">
            </td>
        </tr>
    </table>
</form>


Copy the code

Servlet for processing form data


else if (method.equals("add")) {

            // The uploaded file is separated from ordinary data and encapsulated in the Book object
            Book book = uploadData(request);

            book.setId(WebUtils.makeId());
            service.addBook(book);
            request.setAttribute("message"."Add book succeeded");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }

Copy the code
  • UploadData () method code

    private Book uploadData(HttpServletRequest request) {

        Book book = new Book();
        try{

            //1. Get the parser factory
            DiskFileItemFactory factory = new DiskFileItemFactory();

            //2. Get the parser
            ServletFileUpload upload = new ServletFileUpload(factory);

            // Set the encoding
            upload.setHeaderEncoding("UTF-8");


            // For the upload form, the parser is called to parse the upload data
            List<FileItem> list = upload.parseRequest(request);  //FileItem

            // Iterate through the list to get the fileItem object that encapsulates the first uploaded input data
            for(FileItem item : list){

                if(item.isFormField()){

                    // Get a normal input
                    String name = item.getFieldName();  // Get the name of the input item
                    String value = item.getString("UTF-8");

                    // Encapsulate data with BeanUtils
                    BeanUtils.setProperty(book, name, value);
                }else{

                    // Get the upload input

                    // Get the full path of the upload file name
                    String filename = item.getName();

                    // Intercepts the file name
                    filename = filename.substring(filename.lastIndexOf("\ \") +1);

                    InputStream in = item.getInputStream();   // Get the uploaded data

                    int len = 0;
                    byte buffer[]= new byte[1024];

                    // If the directory does not exist, create it
                    String savepath = this.getServletContext().getRealPath("/image");
                    File file = new File(savepath);
                    if(! file.exists()) { file.mkdir(); } FileOutputStream out =new FileOutputStream(savepath + "\ \" + filename);
                    while((len=in.read(buffer))>0){
                        out.write(buffer, 0, len);
                    }
                    // Set the name of the image
                    book.setImage(filename);

                    in.close();
                    out.close();

                    // Close temporary filesitem.delete(); }}}catch (Exception e) {
            e.printStackTrace();
        }
        return book;
    }
Copy the code
  • Effect:


Background display book module

Since we are using paging technology, let’s import the Page class and JSP we wrote earlier….. This code can be found in my categorized code base

Bind hyperlink



<a href="${pageContext.request.contextPath}/BookServlet? method=look" target="body">Look at books</a>
Copy the code

Servlets handle requests


		else if (method.equals("look")) {

            String currentPageCount = request.getParameter("currentPageCount");
            Page page = service.getPageData(currentPageCount);

            request.setAttribute("page",page);
            request.getRequestDispatcher("/background/listBook.jsp").forward(request, response);
        }
Copy the code

Displays the book JSP page

The Servlet side passes Page objects instead of lists

You can make a hyperlink according to the name of the picture recorded in the Book object. The hyperlink points to the picture on the server, so you can view the picture!

< c: if test = "${empty (page. The list)}" > temporarily don't have any books oh < / c: if > < c: if test = "${! Empty page. The list)} "> < table border =" 1 px "> < tr > < td > title < / td > < td > author < / td > < td > price < / td > < td > description < / td > < td > images < / td > < td > < / td > operation </tr> <c:forEach var="book" items="${page.list}" > <tr> <td>${book.name}</td> <td>${book.author}</td> <td>${book.price}</td> <td>${book.description}</td> <td><a Href = "${pageContext. Request. ContextPath} / images / ${book. Image}" > view images < / a > < / td > < td > < a href = "#" > delete < / a > < a href = "#" > change < / a > </td> </tr> </c:forEach> </table> <br> <jsp:include page="page.jsp"/> </c:if>Copy the code

Effect:


The front desk page

Looking back at our renderings of the foreground page, we can think of the entire body page as three divs

  • The body takes up the entire div
  • The navigation bar is a DIV
  • The place to display the book is a div


Design the general layout

  • HTML code introduces CSS

    <link rel="stylesheet" href="body.css" type="text/css">
Copy the code
  • Three HTML div

<div id="body">
    <div id="category">
        <c:forEach items="${categorys}" var="category">

        </c:forEach>This is the navigation bar</div>

    <div id="bookandpages">
        <div id="books">This is the place for books</div>

        <div id="page">This is the page number</div>
    </div>
    
</div>
Copy the code
  • The CSS code:

#body {
    position: relative;
}


#category {
    border: 1px solid #000;
    position: absolute;
    width: 300px;
    height: 400px;
    float: left;
    left: 200px;
    top: 70px;;
}

#bookandpages {
    border: 1px solid #000000;
    position: absolute;
    width: 600px;
    height: 600px;;
    float: left;
    left: 500px;
    margin-left: 50px;
}

#books {
    border: 1px solid #000;
    width: 600px;
    height: 550px;;
}

#page {
    border: 1px solid #000;
    position: absolute;
    height: 48px;
    width: 600px;
}


Copy the code
  • General layout


IndexServlet

When displaying the next section of the home page, you should first look for a Servlet to hand the data to the corresponding JSP.

Because our JSPS are generally stored in web-INF, they are not directly accessible. There is JSP often need our background data, so we use Servlet to get the data, and then by JSP to show the best.


    <frame src="${pageContext.request.contextPath}/IndexServlet"/>
Copy the code
  • The Servlet code:

        // Get all the classification data for the body page
        BussinessServiceImpl service = new BussinessServiceImpl();
        List<Category> categories = service.getAllCategory();
        request.setAttribute("categories", categories);
        String currentPageCount = request.getParameter("currentPageCount");

        // Get all the categorized books to the body page
        Page page = service.getPageData(currentPageCount);
        request.setAttribute("page", page);

        request.getRequestDispatcher("/client/body.jsp").forward(request,response);
Copy the code

JSP display data


<div id="body">
    <div id="category">Book Category:<br>
        <c:forEach items="${categories}" var="categories">
            <li>
                <a href="${pageContext.request.contextPath}/ListBookServlet? category_id=${categories.id}">${categories.name}</a>
            </li>
        </c:forEach>
    </div>

    <div id="bookandpages">
        <c:forEach items="${page.list}" var="book">
        <div id="books">

                <div id="image">
                    <img src="${pageContext.request.contextPath}/image/${book.image}" width="83px" height="118px">
                </div>
                <div id="bookinfo">
                    <li>Title: ${book. The name}</li>
                    <li>Price: ${book. Price}</li>
                    <li>Author: ${book. The author}</li>
                </div>


        </div>
            <%- it is very important to clear the float here! - %>
            <div style="clear: both"></div>
        </c:forEach>
      
    </div>
    <div id="page">
        <jsp:include page="/client/page.jsp"/>
    </div>
</div>

Copy the code

The CSS code:

Important: If div floats are stuck together, add another div after it to remove the float effect


#body {
    position: relative;
}

#category {
    border: 1px solid #000;
    position: absolute;
    width: 300px;
    height: 400px;
    float: left;
    left: 200px;
    top: 70px;;
}

#bookandpages {
    border: 1px solid #000000;
    position: absolute;
    width: 780px;
    height: 538px;;
    float: left;
    left: 500px;
    margin-left: 50px;
}

#books{
    margin-left: 50px;
    margin-top: 30px;
}
#image{
    float: left;
}
#bookinfo{
    float: left;
}
#page {
    height: 62px;
    width: 780px;
    position: fixed;
    margin-left: 549px;
    margin-top: 477px;
    text-align: center;
    line-height: 50px;
}
Copy the code
  • Effect:


Display books by category

We can display the corresponding classified books according to the navigation bar on the left.

  • The Servlet code:
        BussinessServiceImpl service = new BussinessServiceImpl();
        String currentPageCount = request.getParameter("currentPageCount");
        String category_id = request.getParameter("category_id");

        Page page = service.getPageData(currentPageCount, category_id);
        List<Category>  categories = service.getAllCategory();

        request.setAttribute("page", page);
        request.setAttribute("categories", categories);
        request.getRequestDispatcher("/client/body.jsp").forward(request,response);
Copy the code

Effect:


If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat can follow the wechat public account :Java3y