The most classic JSP implementation of Web engineering week seventh job

Source: Internet
Author: User

Remember what a classic is.

Using JSP to develop Web projects is undoubtedly recognized for its high level of Java security, but another big feature of Java: The use of classes and constructors can make our web development process more structured and less code-based.

Simply take the data from the knowledge tree and say how to pull the data out of the data stream:

The first thing to confirm is that the file configuration is complete: In my previous blog There is a detailed description, so we do the code section directly here.

The total is divided into four steps: first. DBHelper class design Dbhelper.java under the Util package

Two. Create the entity class Items.java under the entities package

Three. Create business logic Itemsdao.java under DAO package

Four. Create a page layer: index.jsp under Web-inf

By the way: look at the last advice I give you will be a little less detours.

A. DBHelper Class design:

Primarily used to create database connection objects and exception exclusions , note that you should look carefully at the comments of the Code

 Packageutil;Importjava.sql.Connection;ImportJava.sql.DriverManager; Public classDBHelper {Private Static FinalString Driver = "Com.mysql.jdbc.Driver";//Database-driven//the URL address of the connection database    Private Static FinalString url= "Jdbc:mysql://localhost:3306/knowledgetree?useunicode=true&characterencoding=utf-8"; Private Static FinalString username= "root";//user name of the database    Private Static FinalString password= "1234";//password for the database        Private StaticConnection conn=NULL; //The static code block is responsible for loading the driver    Static     {        Try{class.forname (driver); }        Catch(Exception ex) {ex.printstacktrace (); }    }        //Singleton mode Returns a database connection object     Public StaticConnection getconnection ()throwsException {if(conn==NULL) {Conn=drivermanager.getconnection (URL, username, password); returnConn; }        returnConn; }         Public Static voidMain (string[] args) {Try{Connection conn=dbhelper.getconnection (); if(conn!=NULL) {System.out.println ("The database connection is OK!" "); }           Else{System.out.println ("Database connection Exception!" "); }        }        Catch(Exception ex) {ex.printstacktrace (); }            }}

    

Two. Items.java: Create entity class Items The code created for the table name in the corresponding database is best aligned with the attribute names in the corresponding table in the database ;

Look at the database first (for everyone to get started quickly, the database is fairly simple)

Then comes the corresponding entity class,

 Packageentity;//Product Category Public classItems {Private intID; PrivateString Book;//Product number     Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }         PublicString GetBook () {returnBook ; }     Public voidSetbook (String book) { This. Book =Book ; }

Three. Create the business logic Itemsdao.java (also called the Guide package is the import data)

 PackageDAO;Importjava.sql.Connection;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.util.ArrayList;Importutil. DBHelper;Importentity. Items;//business logic classes for commodities Public classItemsdao {//get all the product information     PublicArraylist<items>Getallitems () {Connection conn=NULL; PreparedStatement stmt=NULL; ResultSet RS=NULL; ArrayList<Items> list =NewArraylist<items> ();//Product Collection        Try{conn=dbhelper.getconnection (); String SQL= "SELECT * from items;";//SQL statementsstmt =conn.preparestatement (SQL); RS=Stmt.executequery ();  while(Rs.next ()) {Items Item=NewItems (); Item.setid (Rs.getint ("id")); Item.setbook (Rs.getstring ("Book")); List.add (item);//Add a product to a collection            }            returnList//returns the collection. }Catch(Exception ex) {ex.printstacktrace (); return NULL; } finally {            //releasing the DataSet object            if(rs! =NULL) {                Try{rs.close (); RS=NULL; } Catch(Exception ex) {ex.printstacktrace (); }            }            //Releasing statement objects            if(stmt! =NULL) {                Try{stmt.close (); stmt=NULL; } Catch(Exception ex) {ex.printstacktrace (); }            }        }    }}

Four. Create a page layer: index.jsp under Web-inf

Everything, only the output information.

<%@ page language= "Java"Import= "java.util.*" contenttype= "text/html; Charset=utf-8 "%><%@ pageImport= "entity. Items "%><%@ pageImport= "DAO." Itemsdao "%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >NewItemsdao (); ArrayList<Items> list =Itemsdao.getallitems (); Items item1=list.get (0); Items item2=list.get (1); %> <%=item1.getid ()%> <%=item1.getbook ()%> <br> <%=item2.getid ()%> <%=item2.g Etbook ()%> </body>

Look at the effect;

haha haha is not very words do so much work only mustard point thing,,, is not think I am a bit silly,,, directly in the JSP file inside write Java code is not write less?

Let me tell you in detail, the normal Dynamic Web page is all the code in the HTML file, if the workload is very small, but you think the business logic is very much, can you see? Can you figure out the structure? Can you quickly query for bugs?  No, according to this classic model we can more clearly set up each plate, JSP file only need to call his function can be done instead of every time to do some linked database of repeated events, using the constructor in the code volume and pattern clearer, the exception thrown more accurate. And in the future major projects will be in this way to maintain the safety of the project, reliability. So you know how to get to the right direction to go farther.

The most classic JSP implementation of Web engineering week seventh job

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.