Hands-on to do a JSP Getting Started program (v): Get all Product Rendering home page (JSP)

Source: Internet
Author: User
Tags button type sql injection
get all products render home to implement a class that interacts with a database: Bookdao.java

You need to interact with the database at the beginning. Here you need to introduce the concept of a DAO (Data Access Object). DAO is working on the persistence layer, primarily responsible for writing/reading data from the underlying storage, and for the business layer it is necessary to know the DAO interface to complete the crud operation without having to care about the underlying data storage mode. The development of the DAO for the acquisition of goods, namely JDBC (Java Data Base connectivity) programming, will have the following process:

JDBC Programming Process:
1. Connecting to the database
2. Execute the SQL statement, receive the execution result set resultset;
3. Processing execution result set resultset
4. Closure of 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; Database interaction class public class Bookdao {/* JDBC Programming Process: 1. Connect to database 2. Executes the SQL statement, receives the execution result set resultset 3. Process Execution Result set ResU Ltset 4. necessary to close resultset, Statement/* * Get all books/public arraylist<book> getallbooks () {//Database
Connection Connection conn = null;
Database operations: A precompiled statment of SQL used to execute SQL statements PreparedStatement prestmt = null; Database results: ResultSet is the result set of the database execution.
The data structure and tables in the database are quite ResultSet bookset = null;
        Store all the book results arraylist<book> books = new Arraylist<book> (); try{//---------------1. Connect database------------------conn = dbhelper.getconnection ();//---------------2. Execute SQL To receive execution result set resultset------------------String sql = "SELECT * from book where state= ' n '";
Precompile the SQL statement to get the Preparedstament object prestmt = conn.preparestatement (sql);
The result of executing the compilation bookset = Prestmt.executequery (); The method for traversing the result set is as follows://---------------3.

                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 to books;
            }catch (Exception ex) {ex.printstacktrace ();
        return null; }finally{//---------------4.  necessary to close resultset, Statement------------------///To ensure that resources are not occupied, the need to release resources in fianlly, note that this can not be closed connection, or will be an error//release
                    ResultSet 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 ();
 }
            }
        }
    }
}

Here's a little explanation for statement and Prestatement .
Statement
The statement object in the JDBC program is used to send SQL statements to the database. can be obtained by statement stmt = Conn.createstatement ();

/************* Common Methods **************/
executequery (String sql);  Used to send a query statement to the data. SELECT statement, which returns a value resultset result set.
executeupdate (String sql);//used to send INSERT, UPDATE, or DELETE statements to the database. The return value is int: The number of rows affected.
execute (String sql);       For sending arbitrary SQL statements to the database, the return value is Boolean: Returns True if the first result is a ResultSet object, or False if it is an update count or no results exist.

/************* Batch Method **************/
addbatch (String sql);//Put multiple SQL statements into a batch.
ExecuteBatch ();       The database sends a batch of SQL statement execution.

PreparedStatement
PreparedStatement is a statement sub-interface whose instance object can be obtained by calling connection.preparedstatement (String SQL), and the following advantages are relative to the statement object: Preperedstatement can avoid problems with SQL injection. Statement causes the database to compile SQL frequently, potentially causing a database buffer overflow. PreparedStatement SQL can be precompiled to improve the efficiency of database execution. preperedstatement for parameters in SQL, the substitution of placeholders is allowed, simplifying the writing of SQL statements. such as: prestmt = Conn.preparestatement ("SELECT * from Users where name=?"); Parameter value in setting: Prestmt.setstring (1, "xiaoming");

You can read the article on JDBC in this book: Java and Database bridge--JDBC display all merchandise information

Each JSP page corresponds to a servlet class, so we can actually write it directly as a Java file. Then we need to know a little bit of the basic syntax. Basic Syntax

Each JSP file is composed of static code (HTML) and dynamic code (Java). JSP Comments

<%--This is a JSP comment that is not visible in the browser after it is run--%>
<!--This is an HTML annotation, which can be seen in the browser after it is run-->
JSP Declaration
<%!
Declares a variable public
int count;
Declares a method public
String info () {return
    "Hello";
}
%>

You can define member variables and member methods in a declaration. the JSP declaration is converted to the member variables and member methods of the servlet after compilation . We can work\catalina\localhost in tomcat (or the default path for Eclipse. Metadata.plugins\org.eclipse.wst.server.core\tmp0\work\ CATALINA\LOCALHOST\SIMPLESHOP\ORG\APACHE\JSP), see the corresponding code snippet in the corresponding servlet class file within the corresponding project in the. You cannot use abstract for JSP declarations because abstract methods can cause the Servlet programming abstract class corresponding to the JSP to be instantiated.
It's also important to note that JSP pages are compiled into a servlet class, with only one instance in each servlet container, so variables declared in the JSP share variables , all of the client shares the same count variable, And the variable is persisted until the instance is destroyed. output JSP expression

This is a simple way for JSP to provide an output expression value

<%= expression%>

<%--case--%>
<%=count%> <%=info
()%>
JSP Scripts

JSP scripts are used extensively in applications and are the main part of Java code writing.

<%
    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, since we have previously and encapsulated the Bookdao class that interacts with the database, so just instantiate the class, call the Getallbooks () method to get the book information, and render it to the HTML code. Here need to remember to modify the encoding method for Utf-8, otherwise you will see Chinese garbled.

<%@ page language= "java" import= "java.util.*" contenttype= "text/html; Charset=utf-8 "pageencoding=" utf-8%> <%--uses page import to introduce package--%> <%@ page import= "entity. Book "%> <%@ page import=" DAO.
Bookdao "%> <% String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE html> 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.