JSP + JavaBean step-by-Step Tutorial (iv)

Source: Internet
Author: User
Tags error handling getmessage rowcount stmt
js| Tutorial JavaServer Pages+javabeans Database Operations Application
The above has said a simple JavaBean application of the counter example, of course, in the actual program process, involves more and database-related operations, so in this section we will focus on JavaServer pages and JavaBeans How to operate the database. Here we have selected a more representative and practical example, that is the user registration management, because this is used on the Internet more frequently, whether it is registered email, award-winning survey, purchase items or join the community, etc. will involve a user registration problem; On the other hand, it is more representative, Related to the database record increase, record display and other common operations, so we take the user registration surgery.
The program uses the Oracle Jdeveloper3.1 development, the operating environment is wiin2000+tomcat3.1, the database system uses the oracle8.16i.
First we set up a database Demodb, and the fields are as shown below
Username VARCHAR2 (20) User name
Password VARCHAR2 (20) password
Email VARCHAR2 (email address)
Homepage VARCHAR2 (50) Home
Signs VARCHAR2 (200) signature
Regtime Date Registration Time
Then we build several JavaBeans and JavaServer pages files
Db.java files (encapsulates database connections and some underlying operations)
Adduser.java files (for user data reading and adding operations)
newuser.jsp file (user new page, for entering user registration information)
donewuser.jsp files (add for user registration information)
listuser.jsp file (all registered user Information list)
In order to facilitate everyone to see the code, in many places have been detailed comments and explanations, as for JavaBean in the Java grammar structure of things, please refer to Java books.
Db.java file
Description: This JavaBean encapsulates database connections and some underlying operations, derived classes can call these methods directly, and provides a Tochinese method, which is mainly used for processing Chinese data.
Copyright (c) http://jspbbs.yeah.net
Package Lyf;
/**
* A class class.
* <P>
* @author Liuyufeng
*/
Declaring Class library files
Import oracle.jdbc.driver.*;
Import java.net.*;
Import java.sql.*;
Import java.lang.*;
Import java.io.*;
Import java.util.*;
public class db
{
Member Variable initialization
Connection conn = null; Database connection
ResultSet rs = null; Set of records
String username= ""; User name
String password= ""; Password
String email= ""; Email
String homepage= ""; Home
String signs= ""; Signature
DB Builder
Public db ()
{
Try
{//Register database driver for Oracle driver
Class.forName (New Oracle.jdbc.driver.OracleDriver ());
}
catch (Java.lang.ClassNotFoundException e)
{
This is written in order to facilitate debugging programs, error printing mydb () know where the error occurred
System.err.println ("MyDB ():" + e.getmessage ());
}
}
The ExecuteQuery method is used for logging query operations
The entry parameter is an SQL statement that returns the ResultSet object
Public ResultSet executequery (String sql)
{
rs = null;
Try
{//Establish a database connection, using an Oracle thin connection, demo for the host name, Demodb for the database, followed by the two demo for username and password
conn = Drivermanager.getconnection ("Jdbc:oracle:thin: @demo: 1521:demodb", "Demo", "Demo");
Statement stmt = Conn.createstatement ();
Performing database query operations
rs = stmt.executequery (SQL);
}
catch (SQLException ex)
{
System.err.println ("Db.executequery:" + ex.getmessage ());
}
Return RS;
}
The Executeupdate method is used to manipulate add or update records
The entry parameter is a SQL statement, returns true successfully, or false
public boolean executeupdate (String sql)
{
Boolean bupdate=false;
rs = null;
Try
{
Set up a database connection, other parameter description same as above
conn = Drivermanager.getconnection ("Jdbc:oracle:thin: @demo: 1521:demodb", "Demo", "Demo");
Statement stmt = Conn.createstatement ();
int rowcount = stmt.executeupdate (SQL);
If it doesn't work, bupdate will return 0.
if (rowcount!=0) bupdate=true;
}
catch (SQLException ex)
{
Print error messages
System.err.println ("db.executeupdate:" + ex.getmessage ());
}
return bupdate;
}
The Tochinese method is used to handle a string in Chinese
Otherwise it's going to be???. Such a string
public static string Tochinese (String strvalue)
{
Try
{
if (strvalue==null)
{
return null;
}
Else
{
strvalue = new String (strvalue.getbytes ("Iso8859_1"), "GBK");
return strvalue;
}
}
catch (Exception e)
{
return null;
}
}
}

Adduser.java file
Note: The main user data read and add operations, derived from the DB, Addnewuser method used to add user data, CheckUser () method to check the user name is duplicated, there are some set/get methods used to deal with the property, The dousernew.jsp file will be used in strips.
Copyright (c) http://jspbbs.yeah.net
Package Lyf;
/**
* A class class.
* <P>
* @author Liuyufeng
*/
Importing Java class libraries
Import java.sql.*;
Import java.lang.*;
Import oracle.jdbc.driver.*;
AddUser is derived from DB and has the member variables and methods of DB
public class AddUser extends db {
Builder
public Boolean addnewuser () {
Boolean boadduser=false;
try {
Create a user-registered record add operation to generate an SQL statement
String Ssql=new string (insert into User (regtime,username,password,email,homepage,signs));
ssql=ssql+ "VALUES (Sysdaye," "+username+") "," "+password+" "," "+email+" "," "+homepage+" "," "+signs+" "" ";
A method of debugging that can print out SQL statements to facilitate viewing errors
System.out.println (sSQL);
Invokes the Executeupdate method of the parent class and sets the return value based on success
if (Super.executeupdate (sSQL)) boadduser=true;
}
catch (Exception ex) {
Error handling
System.err.println ("Adduser.addnewuser:" + ex.getmessage ());
}finally{
return value regardless of error
return boadduser;
}
}
CheckUser () method to check whether the user name is duplicated
If you repeatedly return a false
public Boolean checkUser () {
Boolean boadduser=false;
try {
Building SQL query Statements
String ssql= "SELECT * from user where username=" "+username+" "";
Invoke the ExecuteQuery method of the parent class
if ((Super.executequery (sSQL)). Next ()) {
Query out Recordset is empty
Boadduser=false;
}else{
Boadduser=true;
}
}
catch (Exception ex) {
Error handling
System.err.println ("Adduser.addnewuser:" + ex.getmessage ());
}finally{
return value
return boadduser;
}
}
The Set/get method of the property, consistent with the requested parameter
/*
In fact, all the following get/set methods are repetitive labor, in order to avoid duplication of copy and paste work, I wrote a software JSP Code faster, as long as the input a series of field names, all the Get/set method can be automatically generated, you can in my website http:// jspbbs.yeah.net Download the Software
*/
Get/set method for username of attribute user name
Public String GetUserName () {
return Username;}
public void Setusername (String newusername) {
User name may be in Chinese and need to be converted
Username =db.tochinese (newusername);}
Get/set method of attribute password password
Public String GetPassword () {
return Password;}
public void SetPassword (String newpassword) {
Password = NewPassword;}
Get/set Method of attribute email
Public String Getemail () {
return Email;}
public void Setemail (String newemail) {
Email = Newemail;}
Properties Home Page Homepage Get/set method
Public String Gethomepage () {
return homepage;}
public void setHomePage (String newhomepage) {
Homepage = newhomepage;}
Properties Home Page Signs Get/set method
Public String getsigns () {
return signs;}
public void setsigns (String newsigns) {
The signature may be Chinese and needs to be converted
Signs = Db.tochinese (newsigns);}
}
OK, here, JavaBean program basically finished, should pay attention to the Chinese processing must be converted, and not necessarily all the attributes need to Set/get method, depending on the situation, and finally need to compile the class file, You can use some visual software, such as JBuilder or VisualAge, to compile. After compiling, you will find that there are two files Db.class and Adduser.class files, all in the LYF subdirectory. These two files will allow the following JSP pages to be invoked.



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.