Get all merchandise rendering homepages
Classes for interacting with databases: BookDAO.java
_Here we need to interact with the database from the beginning! A DAO (Data Access Object) concept needs to be introduced here. DAO works in the persistence layer and is mainly responsible for writing/reading data from the underlying storage. For the business layer, it only needs to know the interface of DAO to complete the CRUD operation, but does not need to care about the underlying data storage mode. For the development of Dao to obtain goods, that is JDBC (Java Data Base Connectivity) programming, there will be the following process:
JDBC programming process:
1. Connecting to the database
2. Execute the SQL statement and receive the execution result set ResultSet.
3. Processing execution result set ResultSet
4. Close ResultSet, Statement and Connection as necessary
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import entity.Book;
import util.DBHelper;
// Interactive class with database
public class BookDAO {
/*
JDBC Programming process:
1. Connect to the database
2. Execute the SQL statement and receive the execution result set ResultSet
3. Processing the execution result set ResultSet
4. Necessary closure of ResultSet, Statement
*/
/*
* Get all the books
*/
public ArrayList<Book> getAllBooks(){
// Database Connection
Connection conn = null;
// Database operations: Statment that precompiles SQL to execute SQL statements
PreparedStatement preStmt = null;
// Database results: ResultSet is the result set of database execution. The data structure is similar to the tables in the database.
ResultSet bookSet = null;
// Store all book results
ArrayList<Book> books = new ArrayList<Book>();
try{
//1. Connect to database - --------------------------------------------------------------------------------------------------------------------------------
conn = DBHelper.getConnection();
//Execute the SQL statement and receive the execution result set ResultSet----------------------------------------------------------------------------------------------------------------------------------
String sql = "select * from book where state='n'";
// Pre-compile sql statement to get PreparedState object
preStmt = conn.prepareStatement(sql);
// The result of executing compilation
bookSet = preStmt.executeQuery();
// The method of traversing the result set is as follows:
//Processing execution result set ResultSet--------------------------------------------------------------------------------------------------------------------------------------
while(bookSet.next()){
Book book = new Book();
book.setAuthor(bookSet.getString("author"));
book.setImg(bookSet.getString("img"));
book.setIntro(bookSet.getString("intro"));
book.setIsbn(bookSet.getString("isbn"));
book.setName(bookSet.getString("name"));
book.setPrice(Float.parseFloat(bookSet.getString("price")));
book.setPrice_original(Float.parseFloat(bookSet.getString("price_original")));
books.add(book);
}
return books;
}catch(Exception ex){
ex.printStackTrace();
return null;
}finally{
//4. Necessary closure of ResultSet, Statement------------------------------------------------------------------------------------------------------------------------------
// In order to ensure that resources are not occupied, resources need to be released in fianlly. Note that Connection can not be closed here, otherwise errors will be reported.
// ResultSet Release
if(bookSet != null){
try{
bookSet.close();
bookSet = null;
}catch(Exception ex){
ex.printStackTrace();
}
}
// Release statement object: PreparedStatement
if(preStmt != null){
try{
preStmt.close();
preStmt = null;
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
}
Statement and restatement are explained here.
Statement
Statement objects in Jdbc programs are used to send SQL statements to databases. Statement stmt = conn.createStatement(); is available.
/ Common methods of *****************/ executeQuery(String sql); used to send queries to data. select statement that returns the ResultSet result set. ExcuteUpdate (String sql); // Used to send insert, update, or delete statements to the database. The return value is int: the number of rows affected. Excute (String sql); // Used to send arbitrary SQL statements to the database with a boolean return value: true if the first result is a ResultSet object; false if it is an update count or no result exists. / ***************** Batch Processing ******************************/ Add Batch (String sql); // Put multiple SQL statements in a batch. executeBatch(); // The database sends a batch of sql statements to execute.
PreparedStatement
_PreparedStatement is a sub-interface of Statement. Its instance object can be obtained by calling Connection.preparedStatement(String sql). The method has the following advantages over Statement object:
- PreperedStatement avoids the problem of SQL injection.
- Statement can make the database compile SQL frequently, which may cause database buffer overflow. PreparedStatement can pre-compile SQL to improve the efficiency of database execution.
- PreperedStatement allows placeholder substitution for parameters in sql to simplify the writing of sql statements. For example: preStmt = conn.prepareStatement("select * from users where name=?"); parameter value in setting: preStmt.setString(1,"xiaoming");
Take a look at the article on JDBC in this brief book: JDBC: A Bridge between Java and Database
Display all merchandise information
_Each jsp page corresponds to a servlet class, so we can actually write as a java file. So we need to know a little basic grammar.
Basic grammar
_Each jsp file is composed of static code (html) and dynamic code (java).
JSP notes
<%- This is the jsp comment, which is not visible in the browser after running -%> <! - This is an HTML comment, which is visible in the browser after running - >
JSP statement
<%!
// Declare a variable
public int count;
// Declare a method
public String info(){
return "Hello";
}
%>
Membership variables and membership methods can be defined in the declaration. JSP declarations are translated into Servlet member variables and member methods after compilation. We can see the corresponding code segments in Tomcat's work Catalina localhost (or in the corresponding Serlet class file of the default path of Eclipse. metadata. plugins org. eclipse. wst. server. core tmp0 work Catalina localhost SimpleShop org apache jsp). JSP declarations cannot be made using abstract, because abstract methods can lead to JSP corresponding Servlet programming abstract classes that cannot be instantiated.
Another thing to note is that JSP pages are compiled into a Servlet class with only one instance in each Servlet container, so there are variables declared in JSP, and all clients share the same count variable, which remains until the instance is destroyed.
Output JSP expression
This is a simple way for JSP to provide output expression values
<%= expression%> <%-Case--%> <%=count %> <%=info() %>
JSP script
JSP script is widely used in applications, and it is also the main part of writing java code.
<%
BookDAO bookDao = new BookDAO();
ArrayList<Book> books = bookDao.getAllBooks();
if(books != null && books.size() > 0){
for(Book book:books){
%>
··· html Code ···
<%
}
}
%>
index.jsp code
The logic here is relatively simple, because we have previously and encapsulated the BookDAO class for database interaction, so as long as we instantiate this class, call getAllBooks() method to get book information, and render it into html code. Here you need to remember to change the encoding mode to utf-8, otherwise you will see Chinese scramble code.
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%-- utilize page Of import To import packages. --%>
<%@ page import="entity.Book" %>
<%@ page import="dao.BookDAO" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- base It's optional here. -->
<base href="<%=basePath%>">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>DIAGRAM</title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link href="./bootstrap-3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="./css/style.css" rel="stylesheet"/>
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="logo-big"><span>D I A G R A M</span></div>
<div class="container-fluid">
<div class="row nav-menuare">
<div class="navbar-header">
<a class="navbar-brand logo-small" href="#">DIAGRAM</a>
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="row navbar-row">
<div class="nav-divider col-md-3 col-sm-3"><span class="divider"></span></div>
<div id="navbar" class="col-md-6 col-sm-6 collapse">
<ul>
<li class="li-col"><a href="#">SHOPINDEX</a></li>
<li class="li-col"><a href="#">NEWBOOK</a></li>
<li class="li-col li-logo"><a href="./index.jsp"><img class="logo-img" src="./img/robot.png"/></a></li>
<li class="li-col"><a href="#">CART(2)</a></li>
<li class="li-col"><a href="#">CUSTOMER</a></li>
</ul>
</div>
<div class="nav-divider col-md-3 col-sm-3"><span class="divider"></span></div>
</div>
</div>
</div>
</nav>
<div class="main">
<div class="container-fluid">
<div class="row">
<%-- adopt BookDao Getting Book Data in the Database --%>
<%
BookDAO bookDao = new BookDAO();
ArrayList<Book> books = bookDao.getAllBooks();
if(books != null && books.size() > 0){
for(Book book:books){
%>
<div class="book-box col-md-3 col-sm-6">
<div class="book">
<a href="single.jsp?isbn=<%= book.getIsbn() %>"><img src="img/<%= book.getImg() %>"/></a>
<p class="book-name"><<%= book.getName() %>></p>
<p class="book-intro"><%= book.getIntro() %></p>
<div class="add-button">
<span class="cost">¥<%= book.getPrice() %></span> / <span class="cost-original">¥<%= book.getPrice_original() %></span><button>Add To Cart</button>
</div>
</div>
</div>
<%
}
}
%>
</div>
</div>
</div>
<div class="footer">
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
</div>
<div class="blog-coyp col-md-6">
<div class="blog text-left"><a href="https://github.com/donespeak" target="_blank">GITHUB</a> | <a href="http://blog.csdn.net/donespeak" target="_blank">CSDN</a> | EMAIL:yangguanr@gmail.com </div><div class="copy text-right">©DoneSpeak.inc</div>
</div>
</div>
</div>
</div>
<script src="./js/jquery-2.1.4.min.js"></script>
<script src="./bootstrap-3.3.0/js/bootstrap.min.js"></script>
<script src="./js/script.js"></script>
</body>
</html>