Java+myeclipse+tomcat (v) DAO and Java beans Implement separate database and interface operations

Source: Internet
Author: User
Tags java web

as described in the previous article, when submitting forms and JSP database queries using a servlet, it is always a cross-cutting process, either by manipulating the database through <%...%> embedded Java code in the JSP, orThe form form is submitted by the Post method in the JSP,Get the request/response through the servlet in Java, and then output the values in the database via Out.println ("This article mainly describes the operation of the database through DAO and Java beans, the link database, database operations, the front-end Interface display sub-modular implementation. Refer to the previous article:
Java+myeclipse+tomcat (i) Introduction to the configuration process and JSP Web site development
        Java+myeclipse+tomcat (ii) Configuring the servlet and simply implementing the form submission
        Java+myeclipse+tomcat (c) Configure MySQL and query data to be displayed in the JSP Web page
Java+myeclipse+tomcat (iv) servlet submission forms and database operations
        DAO and Java beans are the most effective two methods for layering and modularity of JDBC. DAO (database operand, db Access object) is a common pattern under JDBC, and before DAO appears, the code that operates the database and the business code appear in the servlet or JSP, without the separation of business code. When DAO appears, all database-related operations are taken to the DAO layer implementation, and the servlet or JSP only operates the Java bean or DAP layer, while the DAO layer value operates the database.
       The following directly on the code, I hope the article is helpful to you ~ part of the article refer to the Java Web King return.



I. Project Structure

The structure of the project is as follows:


among beans, Student.java is the corresponding database student table, mainly including SetID (), GetId () and other operations In DAO, Studentdao.java is the database additions and deletions to the students table, and the Util Jdbcconnect.java is mainly the operation of database MySQL; student.jsp is the JSP front-end interface for displaying data. You also need to load the Mysql-connector-java.jar package in the Lib folder.

two. Create a database

Open MySQL, enter the default super root user's password, then the database operation is as follows code:

--Creating database testdao;--using Database use testdao;--creating Student table CREATE table student (stuid int,username varchar), password varchar (20));--Inserts Data insert student (Stuid,username,password) VALUES ("10001", "Eastmount", "111111"), insert student ( Stuid,username,password) VALUES ("10002", "Yangxiuzhang", "123456");--Display table structure DESC student;--query table data select * from student;

Where the table structure and data in the table appear as:



three. Java Code

1. Under SRC, create a new folder Util, and then add the class Jdbcconnect.java. The code is as follows:

Package Util;import Java.sql.*;import Com.mysql.jdbc.driver;public class Jdbcconnect {//Get default database connection public static Connection getconnection () throws SQLException {return getconnection ("Testdao", "root", "123456");//database name Default User password}// Connection database parameters: Database name root login password public static Connection getconnection (String dbName, string username,string password) throws SQ lexception {String url = "jdbc:mysql://localhost:3306/" + DbName + "? Characterencoding=utf-8";//connection to MySQL " Com.mysql.jdbc.Driver "Drivermanager.registerdriver (New Driver ()); return drivermanager.getconnection (URL, userName , password);} Set PreparedStatement parameter public static void SetParams (PreparedStatement prestmt, Object ... params) throws SQLException {I F (params = = NULL | | params.length = 0) return;for (int i = 1; I <= params.length; i++) {Object param = params[i-1];i F (param = = null) {Prestmt.setnull (I, types.null);} else if (param instanceof Integer) {Prestmt.setint (I, (Integer) param) ;} else if (param instanceof String) {prestmt.setstring (I, (String) param);} else if (param instanceof Double) {prestmt.setdouble (I, (Double) param);} else if (param instanceof Long) {Prestmt.setdoub Le (i, (Long) param);} else if (param instanceof Timestamp) {Prestmt.settimestamp (I, (Timestamp) param);} else if (param instanceof Boolean) {Pre Stmt.setboolean (i, (Boolean) param);} else if (param instanceof date) {Prestmt.setdate (I, (date) param);}}} Executes SQL, returns the number of rows affected exception handling public static int executeupdate (String sql) throws SQLException {return executeupdate (SQL, New Object [] {});} Execute SQL with parameters, return the number of rows affected exception handling public static int executeupdate (String sql, Object ... params) throws SQLException {Connection conn = NULL; PreparedStatement prestmt = null;try {conn = getconnection ();p restmt = conn.preparestatement (sql); SetParams (preStmt, params); return prestmt.executeupdate (); Execute SQL Operation} finally {if (prestmt! = null) prestmt.close (); if (conn! = null) Conn.close ();}}

The main is to call getconnection (URL, userName, password); method to connect the database operation, my database name is Testdao, the default connection object is root, The password is 123456. It also defines two functions to perform parameterless SQL statement operations and SQL statement operations with parameters.

2. Create a new folder Bean under SRC, and then add the class Student.java. The code is as follows:

Package Bean;public class Student {private Integer ID;       Study number private String name;      Name private String password;  Password public Integer getId () {return ID;} Public String GetName () {return name;} Public String GetPassword () {return password;} public void SetId (Integer id) {this.id =  ID;} public void SetName (String name) {this.name =  name;} public void SetPassword (String pwd) {this.password = pwd;}}

The variables and types in the student correspond to one by one in the database, and their values are obtained and set through the get and set methods. Also if your database has teachers, school tables, you only need to add Teacher.java and School.java under the Bean folder.

3. Under SRC, create a new folder DAO, and then add the class Studentdao.java. The code is as follows:

Package Dao;import Java.sql.connection;import Java.sql.preparedstatement;import java.sql.resultset;import Java.util.arraylist;import Java.util.list;import Bean. Student;import util. Jdbcconnect;public class Studentdao {//INSERT student public static int insert (Student stu) throws Exception {String sql = ' Insert in to student (Stuid,username,password) VALUES (?,?,?) "; return jdbcconnect.executeupdate (SQL, Stu.getid (), Stu.getname (), Stu.getpassword ());} Update student name public static int update (Student stu) throws Exception {String sql = "Update Student SET stuid =?" WHERE username =? "; return Jdbcconnect.executeupdate (Sql,stu.getid (), Stu.getname ());} Delete operation public static int delete (Integer id) throws Exception {String sql = "Delete from student WHERE Stuid =?"; return jdbcconnect.executeupdate (SQL, id);} Find records a school number public static Student find (Integer id) throws Exception {String sql = "SELECT * from Student WHERE stuid =?"; Connection conn = null; PreparedStatement prestmt = null; ResultSet rs = null;try {//Link database executionSQL Statement conn = jdbcconnect.getconnection (); Connect the default database prestmt = conn.preparestatement (sql);p Restmt.setint (1, id), rs = Prestmt.executequery ();//Get query results if (Rs.next ( ) {Student Student = new Student (); Student.setid (Rs.getint ("Stuid")); Student.setname (rs.getstring ("username")); return student;} else {return null;}} Finally {//Turns off Recordset Declaration Connection object if (rs! = null) rs.close (); if (prestmt! = null) prestmt.close (); if (conn! = null) Conn.close ();} }//Query all student information public static list<student> liststudents () throws Exception {list<student> List = new arraylist& Lt Student> (); String sql = "SELECT * from student"; Connection conn = null; PreparedStatement prestmt = null; ResultSet rs = null;try {conn = jdbcconnect.getconnection ();p restmt = conn.preparestatement (sql); rs = Prestmt.executequery (); while (Rs.next ()) {//Set table parameter in database otherwise error java.sql.SQLException:Column ' ID ' not found.      Student Student = new Student () Student.setid (Rs.getint ("Stuid")); Student.setname (rs.getstring ("username")); Student.setpassword (RS.GEtstring ("password")); List.add (student);}} Finally {if (rs! = null) rs.close (); if (prestmt! = null) prestmt.close (); if (conn! = null) Conn.close ();} return list;}}
Typically DAO (data Access Object) is responsible for connecting with the database, and the primary function performs CUDR operations on the data table.
C (Create) Operation: Create record, execute INSERT INTO statement;
U (UPDATE) operation: the corresponding attribute in the business table is updated, and the UPDATE statement is executed;
D (delete) Action: Delete the record corresponding to the DTO object and execute the DELETE statement;
R (Read) operation: reading data from a table, you can return more than one list of records corresponding to a Dto object.
The original classmate suggested that this, dare not contact worry is complex, but after the use of the knowledge that it does not need to import how to jar package, configure Web. xml or what software to install, only through the DAO interface implementation of DAO object CUDR operation.
Each data table defines a DAO interface or class implementation that implements read and write operations on this table. In other words, it is in the domain name. Project. module. Create a DAO class under the DAO folder.
For example "package Com.neusoft.dao;"

four. JSP Code

Then there is the JSP code under the Webroot folder. Among them index.jsp are as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%string path = Request.getcontextpath () ; String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Then click the JDBC action to jump to the student.jsp operation, the code is as follows: involving El and Jstl.

<%@ page language= "java" pageencoding= "UTF-8"%><%@ taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C "%><jsp:directive.page import=" DAO. Studentdao "/><jsp:directive.page import=" java.util.List "/><%list studentlist = studentdao.liststudents (); Request.setattribute ("Studentlist", studentlist);%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

The article runs as shown in the results:


Finally, the article mainly describes how to implement the Java database operation through the DAO and Java Bean, the interface display separates the operation, the same reason, implements the modification, the deletion, the insertion method is similar, may explain later. This method is mainly through the previous article own experience, found the solution. Finally hope that the article will help you, if there are errors or shortcomings, please Haihan ~
One of the most important issues that you may encounter in this process is the following two errors: (Troubled me for 4 hours)
Servlet.service () for Servlets [JSP] in context with path
Javax.el.PropertyNotFoundException:Property ' id ' not found on type bean. Student
Its solution reference: http://blog.csdn.net/eastmount/article/details/45835481
(By:eastmount 2015-5-19 2 o'clock in the morninghttp://blog.csdn.net/eastmount/)

Java+myeclipse+tomcat (v) DAO and Java beans Implement separate database and interface operations

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.