Login is the basic function of information system, this chapter will use Java to implement user login function, and reconstruct the login function with three layer structure. The login feature mainly concerns how Java interacts with the MySQL database.
0 environment
(1) jdk1.6+
(2) Editor: Eclipse
(3) database driver: Mysql-connector-java-5.1.24-bin.jar
(4) The reader has Java, database base
1 Demand Analysis
We need to use MySQL to build a database (demo) and create a user table (T_user) in the database, and we need a login interface.
When the user enters the user name and password in the login interface, click Sign In, the program should find the matching user in the user table, if present, in the console output "login ..." statement, if not present, prompt error message.
2 Setting Up test data
To create a new database demo in MySQL, create a new user table T_user in the demo with the structure as shown.
Insert a test data as shown in.
3 Coding
Write the Login interface code, the login interface is responsible for monitoring whether the "Login" button is pressed, if pressed, connect to the demo database, and find a record matching the user name and password entered, if the search succeeds, print the "login ..." statement in the console. Otherwise, a prompt error message is printed in the console.
Code Listing 1:logindig.java
Public class logindig extends JFrame implements ActionListener{ / * * Define Login Interface Controls */ //define user static tags PrivateJLabel Lb_name;//define password static label PrivateJLabel LB_PSW;//define User text box PrivateJTextField Txt_name;//Define Password text box PrivateJPasswordField TXT_PSW;//Define Login button PrivateJButton Btn_login;//construct method, initialize the control, add the control to the frame Public Logindig() {//Create ControlsLb_name =NewJLabel ("User:"); Txt_name =NewJTextField (Ten); LB_PSW =NewJLabel ("Password:"); TXT_PSW =NewJPasswordField (Ten); Btn_login =NewJButton ("Login");//Register button event, execute Actionperformed Method when button is clickedBtn_login.addactionlistener ( This);//Set table layout structure, 3 rows 2 columns This. setlayout (NewGridLayout (3,2)); This. Add (Lb_name); This. Add (Txt_name); This. Add (LB_PSW); This. Add (TXT_PSW); This. Add (Btn_login);//Display frame This. setvisible (true); This. Pack (); }@Override Public void actionperformed(ActionEvent arg0) {//Get the user name and password enteredString name = Txt_name.gettext (); String password = txt_psw.gettext ();Try{//load MySQL driverClass.forName ("Com.mysql.jdbc.Driver");//Create a database connection //Database-related propertiesString URL ="Jdbc:mysql://localhost/demo"; String user ="Root"; String psw=""; Connection conn = drivermanager.getconnection (URL, user, PSW);//Create an statement object that executes the SQL statementStatement stmt = Conn.createstatement ();//Execute SQL statement, return query resultString sql ="SELECT * from t_user WHERE name = '"+ name +"' and password = '"+ Password +"'"; ResultSet rs = stmt.executequery (SQL);//If presence exists in table and input user and password match user if(Rs.next ()) {System.out.println ("Sign in ..."); }Else{System.out.println ("User or password error!" "); } }Catch(ClassNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(SQLException e) {//TODO auto-generated catch blockE.printstacktrace (); } }}
The test class is responsible for creating the login interface.
Code Listing 2:test.java
publicclass test { publicstaticvoidmain(String[] args) { new LoginDig(); }}
To run the program, the login interface is shown below.
Enter the non-existent user or the wrong password, enter the correct user and password, and you will see the appropriate prompt in the console.
4 interface difficult to withstand
In Listing 1 above, you can see that the Logindig class is responsible for the three functions of "UI (interface Display)", "Business Processing (Assembly of SQL statements, processing of database access results)", "Database interaction (connecting database, accessing data)". Its logical relationship is as shown.
In particular, database access that pushes messy code, makes people drowsy, in addition to writing this Code of the program apes have the mood to see.
The above three kinds of unrelated functions through the login interface is closely linked together, "that is, programmers must understand the interface art, but also know the business process, and database knowledge is very strong". We want to separate three different features in the interface: interface, business processing, and database interaction, so that the interface layer is only responsible for the interface display, the business layer specializes in business-related matters, and the database layer specifically handles database interactions. The following steps will decouple the three functions from the login interface.
5 Decoupling the database layer
First of all the hard-to-chew database code decoupling, we need to create a new database helper class DBHelper, which is responsible for all database-related operations, and provide an interface (method) for the interface layer (login interface) call, the relationship as shown.
According to the layered requirements, to divide the program into the interface layer, the data operation layer, the initial relief logindig trouble, let it only responsible for interface display and business processing, discard that annoying database interaction code.
The code that is responsible for database operation in Logindig is extracted, and the database operation class DBHelper is written.
Code Listing 3:dbhelper.java
Public class dbhelper { //Database-related properties PrivateString URL ="Jdbc:mysql://localhost/demo";PrivateString user ="Root";PrivateString pwd ="";//Get database connection PublicConnectionGetconn()throwsexception{Connection Conn;//load MySQL driverClass.forName ("Com.mysql.jdbc.Driver");//Create a database connectionconn = drivermanager.getconnection (URL, user, pwd);//Return connection returnConn }//user lookup based on username and password, if present returns True, otherwise false PublicBooleanFinduser(string name, string password)throwsexception{String sql ="SELECT * from t_user WHERE name = '"+ name +"' and password = '"+ Password +"'";//Create connectionConnection conn = Getconn ();//Create Execute SQL statement statement ObjectStatement stmt = Conn.createstatement ();//Get result set based on SQL statementResultSet rs = stmt.executequery (SQL);//If the user is present, returns True if(Rs.next ()) {return true; }Else{return false; } }}
The DBHelper class is responsible for connecting to the database and providing a basic operational method of the database (creating a connection, locating the user) for the login interface object invocation. At this point, the login interface code is shown in Listing 4.
Code Listing 4:logindig.java
Public class logindig extends JFrame implements ActionListener{ / * * Define Login Interface Controls */ //define user static tags PrivateJLabel Lb_name;//define password static label PrivateJLabel LB_PSW;//define User text box PrivateJTextField Txt_name;//Define Password text box PrivateJPasswordField TXT_PSW;//Define Login button PrivateJButton Btn_login;//construct method, initialize the control, add the control to the frame Public Logindig() {//Create ControlsLb_name =NewJLabel ("User:"); Txt_name =NewJTextField (Ten); LB_PSW =NewJLabel ("Password:"); TXT_PSW =NewJPasswordField (Ten); Btn_login =NewJButton ("Login");//Register button event, execute Actionperformed Method when button is clickedBtn_login.addactionlistener ( This);//Set table layout structure, 3 rows 2 columns This. setlayout (NewGridLayout (3,2)); This. Add (Lb_name); This. Add (Txt_name); This. Add (LB_PSW); This. Add (TXT_PSW); This. Add (Btn_login);//Display frame This. setvisible (true); This. Pack (); }@Override Public void actionperformed(ActionEvent arg0) {//Get the user name and password enteredString name = Txt_name.gettext (); String password = txt_psw.gettext ();//CREATE Database helper classDBHelper db =NewDBHelper ();//Call the interface Finduser provided by the database Assistant and pass the user name and password as parameters Try{if(Db.finduser (name, password)) {System.out.println ("Login ..."); }Else{System.out.println ("The user does not exist or the password is wrong!" "); } }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); } }}
At the login screen, when the login button is clicked, the user name and password are obtained, the database layer method is called and the corresponding business process is processed according to the returned results.
At present the login interface code is much more handsome, it is only responsible for the interface display and business processing, as for the database related processing has been lost to the DBHelper object responsible. Equivalent to completing the login function one person becomes two people, one of whom is dedicated to interacting with the database.
6 Decoupling the business layer
At the interface level, we want it to be only responsible for the interface display, and the business process (login business) should be handled by the user business Class (UserService). So the login function is done by three people, each responsible for their own good things, and errors or positioning is in that layer, narrowing the wrong range. Complete the three-layer decoupling structure as shown in.
Extract the code from the login interface that is responsible for logging into the business, and write a user business processing class, as shown in Listing 5.
Code Listing 5:userservice.java
Public classUserService {//responsible for handling login business Public void Login(string name, string password) {//Call the database layer, process loginDBHelper db =NewDBHelper ();//Call the interface Finduser provided by the database Assistant and pass the user name and password as parameters Try{if(Db.finduser (name, password)) {System. out. println ("Login ..."); }Else{System. out. println ("The user does not exist or the password is wrong!" "); } }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); } }}
At this point the login interface class is shown in code listing 6.
Code Listing 6:logindig.java
Public class logindig extends JFrame implements ActionListener{ / * * Define Login Interface Controls */ //define user static tags PrivateJLabel Lb_name;//define password static label PrivateJLabel LB_PSW;//define User text box PrivateJTextField Txt_name;//Define Password text box PrivateJPasswordField TXT_PSW;//Define Login button PrivateJButton Btn_login;//construct method, initialize the control, add the control to the frame Public Logindig() {//Create ControlsLb_name =NewJLabel ("User:"); Txt_name =NewJTextField (Ten); LB_PSW =NewJLabel ("Password:"); TXT_PSW =NewJPasswordField (Ten); Btn_login =NewJButton ("Login");//Register button event, execute Actionperformed Method when button is clickedBtn_login.addactionlistener ( This);//Set table layout structure, 3 rows 2 columns This. setlayout (NewGridLayout (3,2)); This. Add (Lb_name); This. Add (Txt_name); This. Add (LB_PSW); This. Add (TXT_PSW); This. Add (Btn_login);//Display frame This. setvisible (true); This. Pack (); }@Override Public void actionperformed(ActionEvent arg0) {//Get the user name and password enteredString name = Txt_name.gettext (); String password = txt_psw.gettext ();//Call the business layerUserService UserService =NewUserService (); Userservice.login (name, password); }}
Using Hierarchical implementation Login