Java Component JavaBean User Login instance detailed _java

Source: Internet
Author: User
Tags unique id

This article simply describes the use of JavaBean to achieve user login, including user login, registration and exit.

1. About JavaBean
JavaBean is a reusable component written in the Java language. To write JavaBean, the class must be concrete and public, and have a constructor without parameters. JavaBean exposes member properties, set, and get methods to the internal domain by providing a public method that conforms to the consistent design pattern. As we all know, attribute names conform to this pattern, and other Java classes can discover and manipulate the properties of these javabean through an introspection mechanism.

2. System Architecture
2.1 Login Case Diagram

2.2 Page Flowchart

2.3 System Architecture Diagram

2.4 Database Design
This example uses the Oracle database

User table includes ID, username, password, email, total 4 fields

--Create TABLE 
CREATE TABLE P_user 
( 
 ID  VARCHAR2 () not NULL, 
 username VARCHAR2, 
 Password VARCHAR2, 
 email VARCHAR2) 
tablespace USERS 
 pctfree 
 1 
 Maxtrans 255 
 Storage 
 ( 
 initial minextents 
 1 
 maxextents 
 ); 
--ADD comments to the table 
Comment in table p_user is 
 ' user table '; 
--ADD comments to the columns 
comment in column p_user.id is 
 ' id '; 
Comment on column p_user.username is 
 ' username '; 
Comment on column p_user.password is 
 ' password '; 
Comment on column p_user.email is 
 ' email '; 

3.javabean Writing
3.1 Development Database low-level processing JavaBean
Dbacess.java

Package Com.baosight.bean; 
Import java.sql.Connection; 
Import Java.sql.DriverManager; 
Import Java.sql.ResultSet; 
Import java.sql.SQLException; 
 
Import java.sql.Statement; 
 /** database Operations Class * <p>title:dbacess </p> * <p>description:todo </p> * <p>company: </p> * @author yuan * @date 2016-5-22 pm 12:40:24*/public class Dbacess {private String driver = "Oracle.jdbc.driver.Or 
 Acledriver "; 
 Private String URL = "jdbc:oracle:" + "THIN:@127.0.0.1:1521:ORCL"; 
 Private String username = "Scott"; 
 Private String Password = "Tiger"; 
 Private Connection Conn; 
 Private Statement STM; 
 Private ResultSet RS; 
  Create Connection public boolean Createconn () {Boolean b = false; 
   try {class.forname (driver);//load Oracle Driver conn = drivermanager.getconnection (URL, username, password); 
  B = true; 
  catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); }//Get connection catch (ClassNotFoundException e) {// TODO auto-generated Catch block E.printstacktrace (); 
 return b; 
  //Modify public boolean update (String sql) {Boolean b = false; 
   try {stm = Conn.createstatement (); 
   Stm.execute (SQL); 
  B = true; 
  catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); 
 return b; 
   }//Query public void query (String sql) {try {stm = Conn.createstatement (); 
  rs = stm.executequery (SQL); 
  catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); 
  }//Determine whether there is data public boolean next () {Boolean b = false; 
   try {if (Rs.next ()) {B = true; 
  The catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); 
 return b; 
  //Get table field value public String getValue (string field) {string value = null; 
   try {if (rs!= null) {value = rs.getstring (field); 
 The catch (SQLException e) {//TODO auto-generated catch block  E.printstacktrace (); 
 return value; 
   //close connection public void Closeconn () {try {if (conn!= null) {conn.close (); 
  The catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); 
   }//Turn off statement public void Closestm () {try {if (STM!= null) {stm.close (); 
  The catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); 
   }//Close resultset public void closers () {try {if (rs!= null) {rs.close (); 
  The catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); 
 } public String Getdriver () {return driver; 
 } public void Setdriver (String driver) {this.driver = driver; 
 Public String GetUrl () {return URL; 
 public void SetUrl (String url) {this.url = URL; 
 Public String GetUserName () {return username; } public void Setusername (String username) {This.username = UsernaMe 
 Public String GetPassword () {return password; 
 } public void SetPassword (String password) {this.password = password; 
 Public Statement getstm () {return STM; 
 public void Setstm (Statement stm) {this.stm = STM; 
 Public ResultSet Getrs () {return rs; 
 public void Setrs (ResultSet rs) {this.rs = rs; 
 public void Setconn (Connection conn) {this.conn = conn; 
 Public Connection Getconn () {return conn; 
 } 
}

The database operations class uses JDBC to connect to the database and encapsulates methods such as connecting to databases, querying, modifying, and closing resources.

3.2 Developing JavaBean business logic Components
Userbean.java

Package Com.baosight.bean; 
 
Import Com.baosight.util.GenerateUUID; /** * <p>title:userbean </p> * <p>description:todo </p> * <p>company: </p> * Author Yuan * @date 2016-5-22 pm 1:05:00*/public class UserBean {//Logon authentication public boolean valid (String Username,strin 
  G password) {Boolean isValid = false; 
  Dbacess db = new dbacess (); 
   if (Db.createconn ()) {String sql = "SELECT * from P_user where username= '" +username+ "' and password= '" +password+ ' "; 
   Db.query (SQL); 
   if (Db.next ()) {isValid = true; 
   } db.closers (); 
   Db.closestm (); 
  Db.closeconn (); 
 return isValid; 
  }//register Validation public boolean isexist (String username) {Boolean isValid = false; 
  Dbacess db = new dbacess (); 
   if (Db.createconn ()) {String sql = "SELECT * from P_user where username= '" +username+ ""; 
   Db.query (SQL); 
   if (Db.next ()) {isValid = true; 
   } db.closers (); 
   Db.closestm (); 
  Db.closeconn (); } RETurn isValid; 
  }//Registered user public boolean add (String username,string password,string email) {Boolean isValid = false; 
  Dbacess db = new dbacess (); if (Db.createconn ()) {String sql = INSERT INTO P_user (id,username,password,email) VALUES (' +generateuuid.next () + "', '" 
   +username+ "', '" "+password+", "" +email+ "; 
   IsValid = db.update (sql); 
   Db.closestm (); 
  Db.closeconn (); 
 return isValid; 
 } 
}

The above business logic JavaBean, defines the method of login authentication, registration authentication and new user, etc.

3.3 About generating unique IDs
The above need to insert ID when new user is added, this example uses UUID to generate unique ID

Generateuuid.java

Package com.baosight.util; 
 
Import java.util.Date; 
 
/** 
 * <p>title:generateuuid </p> 
 * <p>description:todo </p> 
 * <p>company: </p> 
 * @author Yuan 
 * @date 2016-5-22 pm 1:31:46*/public 
class Generateuuid { 
  private static date D ate = new Date (); 
private static StringBuilder buf = new StringBuilder (); 
  private static int seq = 0; 
  private static final int rotation = 99999; 
  public static synchronized long next () { 
  if (seq > rotation) seq = 0;  buf.delete (0, Buf.length ()); 
  Date.settime (System.currenttimemillis ()); 
  String str = String.Format ("%1$ty%1$tm%1$td%1$tk%1$tm%1$ts%2$05d", date, seq++); 
  return Long.parselong (str); 
  public static void Main (string[] args) {for 
   (int i=0;i<100;i++) { 
    System.out.println (next ()); 
   } 
} 

4. Page Writing
4.1 login Page
login.jsp

<%@ 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" >  

Page effects


4.2 Login Business Logic Processing page
login_action.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%> <%@ page import= "java.sql.*"%> 
Page import= "com.baosight.bean.*"%> <% String Path = Request.getcontextpath (); 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; 
 %> <% String username = request.getparameter ("username"); 
 String Password = request.getparameter ("password"); if (username==null| | "". Equals (Username.trim ()) | | password==null| | "". Equals (Password.trim ())) {//out.write ("User name or password cannot be empty!") 
  "); System.out.println ("User name or password cannot be empty!") 
  "); 
  Response.sendredirect ("login.jsp"); 
  Return 
 Request.getrequestdispatcher ("login.jsp"). Forward (request, response); 
 } UserBean UserBean = new UserBean (); 
 Boolean isValid = Userbean.valid (Username,password); if (isValid) {System.out.println (login successful!) 
  "); 
  Session.setattribute ("username", username); 
  Response.sendredirect ("welcome.jsp"); 
 Return }else{System.out.priNtln ("User name or password error, Login failed!") 
  "); 
  Response.sendredirect ("login.jsp"); 
 Return 
 }%>

The above JSP calls the JavaBean for business processing
Return to login page when user name or password is empty login.jsp

When the login is successful, save the user information to the session, and jump to the Welcome page welcome.jsp

Return to login page when login fails login.jsp

4.3 Login Success Welcome page
welcome.jsp

<%@ 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" >  

Page effects

4.4 Exit Login Business Processing page
loginout.jsp

<%@ 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" >  

Remove user information from session, jump to login page login.jsp

4.5 User Registration Page
register.jsp

<%@ 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" >  

Run effect

4.6 Registration Business Processing page

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ page import= "java.sql.*"%> 
Page import= "com.baosight.bean.*"%> <% String Path = Request.getcontextpath (); 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; 
 %> <% String username = request.getparameter ("username"); 
 String Password1 = Request.getparameter ("Password1"); 
 String Password2 = Request.getparameter ("Password2"); 
 String email = request.getparameter ("email"); if (username==null| | "". Equals (Username.trim ()) | | password1==null| | "". Equals (Password1.trim ()) | | password2==null| | "". Equals (Password2.trim ()) | |! Password1.equals (Password2)) {//out.write ("User name or password cannot be empty!") 
  "); System.out.println ("User name or password cannot be empty!") 
  "); 
  Response.sendredirect ("register.jsp"); 
  Return 
 Request.getrequestdispatcher ("login.jsp"). Forward (request, response); 
 } UserBean UserBean = new UserBean (); Boolean isexit = Userbean.isexist (USErname); 
  if (!isexit) {Userbean.add (username, password1, email); SYSTEM.OUT.PRINTLN ("Registration is successful, please login!") 
  "); 
  Response.sendredirect ("login.jsp"); 
 Return }else{System.out.println ("User name already exists!") 
  "); 
  Response.sendredirect ("register.jsp"); 
 Return 
 }%>

The above JSP calls the JavaBean for business processing

Returns the registration page when the user name or password is empty register.jsp

New user when registered username is not present in database

Jump to login page after new success login.jsp

When the registered user name is in the database, return to the registration page register.jsp

5. Summary

This example uses JavaBean to encapsulate database operations and business logic processing.

Above that is to use JavaBean to achieve a simple introduction of user login, but also need to constantly improve, I hope we learn to progress together!

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.