Java Course Design---implementation login (2)

Source: Internet
Author: User

The previous design of the login interface has been completed, click the Confirm button to get the username and password entered, the following will demonstrate the implementation of real login (input value and database alignment)

1, Design "login Service"

Usually we are based on business relations, to the corresponding operators to provide various external services, the following create an administrator service class Adminservice

Adminservice.java (define service, method implementation supplement below)

Package com.demo.service;/* * Project name:  *  * filename called: Adminservice.java * File Creator: Daxiang *  * @author Daxiang * @versio N  * @time  June 13, 2018 PM 10:04:15 * @copyright Daxiang */public class Adminservice {/** * Login service *  * @param ID * @ param pwd * @return 1, Success 2, user name error 3, password error */public int login (string id, string pwd) {return 0;} /** * Change Password service *  * @param ID * @param pwd * @param newpwd * @return False Modify failed True Modify */public Boolean changepwd (stri Ng ID, string pwd, String newpwd) {return false;}}
2. Provide database query operation for login service

In the first section for the administrator to provide two services 1, login 2, change the password, but did not implement the specific process, the following to complete the process of logging into the service.

Two steps are required to determine if a user can log on successfully

(1) Query the database for the user based on the user name entered

(2) If the user exists than the password entered is the same as the password stored in the database

Next look at the traditional query method (a complete query)

Package Com.java.mysql;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.ResultSet;import Java.sql.sqlexception;import java.sql.statement;/** * <p> * Title:db.java * </p> * * @author Daxiang * @vers Ion 1.0 created: May 22, 2018 morning 8:00:22 */public class DB {public static void main (string[] args) {Connection con;//declaration connectio N Object String driver = "com.mysql.jdbc.Driver";//driver name string url = "Jdbc:mysql://localhost:3306/db_student";// The URL points to the database name you want to access db_studentstring user = "root";//the user name for MySQL configuration is string password = "123";//MySQL configuration password try {class.forname ( driver);//load Driver con = drivermanager.getconnection (url, user, password);//Use the getconnection () method to connect to the MySQL database!! if (!con.isclosed ()) System.out.println ("Successfully connected MySQL database");//2. Create statement class object to execute SQL statement!! Statement Statement = Con.createstatement ();//SQL statement to execute string sql = "SELECT * from admin";//3.ResultSet class, used to store obtained result set!! ResultSet rs = statement.executequery (SQL); System.out.println ("-----------------"); System.out.println ("Execution resultsas follows: "); System.out.println ("-----------------"); SYSTEM.OUT.PRINTLN ("id" + "\ T" + "admin" + "\ T" + "password"); System.out.println ("-----------------");//Traverse query result set while (Rs.next ()) {String id = rs.getstring (1);//Get first column data String Username = rs.getstring (2); Gets the second column of data string pwd= rs.getstring (3); Get the third column of data System.out.println (id + "\ t" + username + "\ T" + pwd);//output result}rs.close (); Con.close ();} catch (ClassNotFoundException e) {System.out.println ("Unable to load driver"), E.printstacktrace ();//database-driven class exception handling} catch ( SQLException e) {e.printstacktrace ();//database connection failed exception handling} catch (Exception e) {e.printstacktrace ();}}}

The above completes the query to the Admin table in the Db_student database, and gets the result

But this does not implement code reuse, when other entities need to query or other operations, but also need to repeat the connection process, so we encapsulate the common operation, the basic database "Add, delete, check, change" package into a class inside

Dbutil.java (Database Operations Tool Class)

Package Com.demo.util;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.ResultSet;import Java.sql.sqlexception;import java.sql.statement;/* * Project Name: * * filename called: Dbutil.java * File Creator: Daxiang * * @author Daxiang * @version * @time June 13, 2018 PM 7:56:46 * @copyright Daxiang */public class Dbutil {//Define Connection object private Connection Connection ;//Define Action object Private Statement statement;/** * * @throws Exception */public dbutil () throws Exception {this.connection = GetC On (); this.statement = Connection.createstatement ();} /** * Get Database connection * * @return database connection Connection * @throws Exception */public Connection Getcon () throws Exception {//Description Appconst Some parameters have been stored as static constants in the Ants Class Class.forName (appconstants.jdbc_driver); Connection con = drivermanager.getconnection (Appconstants.jdbc_url,appconstants.jdbc_username, AppConstants.JDBC_ PASSWORD); return con;}  /** * Close Database connection * * @param con * @throws SQLException */public void Closecon (Connection con) throws SQLException {if (con! = NULL) {Con.close ();}} /** * Gift,Delete, change * * @param SQL * @return * @throws SQLException */public boolean execute (String sql) throws SQLException {return stat Ement.execute (SQL);}  /** * Query * * @param SQL * @return * @throws SQLException */public ResultSet query (String sql) throws SQLException {return Statement.executequery (SQL);}}

Appconstants. Java (constant parameter class)

Package com.demo.util;/* * Project name:  *  * filename called: Appconstants.java * File Creator: Daxiang * * @author Daxiang * @version  * @time  June 13, 2018 PM 7:57:10 * @copyright Daxiang */public class Appconstants {//jdbcpublic static final String Jdbc_ur L = "Jdbc:mysql://127.0.0.1:3306/db_student?useunicode=true&characterencodeing=utf-8";p ublic static final String jdbc_username = "root";p ublic static final string Jdbc_password = "123";p ublic static final String jdbc_driver = "C Om.mysql.jdbc.Driver ";}

So that we can simplify the code in the service class, see

Create a new admin entity database operation class and use the Dbutil tool to implement the query

Admindao.java
Package Com.demo.dao;import java.sql.resultset;import com.demo.model.admin;import com.demo.util.dbutil;/* * Project name:  *  * filename is called: Admindao.java * File Creator: Daxiang *  * Modified record: * Modified person  Modified Date  Remarks * * * *  @author Daxiang * @version  * @time  June 13, 2018 PM 10:25:06 * @copyright Daxiang */public class Admindao {public Admin query (String u Sername) throws Exception {//Instantiate operation class Dbutil dbutil = new Dbutil ();//query statement, because username is a string, you need username= ' "+ username+" ' "to spell String sql = "SELECT * from admin where username= '" + username+ "'";//Execute query ResultSet rs = dbutil.query (sql);//create null ADMI N Object Admin admin = null;//Determine if there is a result, and loop while (Rs.next ()) {//new object is assigned to Adminadmin = new admin ();//Assign value to object Admin.setid (Rs.geti NT ("id")); Admin.setusername (rs.getstring ("username")); Admin.setpassword (rs.getstring ("password"));} Return query results return admin;}}

  

Complete the login service in Adminservice below

  

Package Com.demo.service;import Com.demo.dao.admindao;import com.demo.model.admin;/* * Project name:  *  * File name: Adminservice.java * File Creator: Daxiang *  * @author Daxiang * @version  * @time  June 13, 2018 PM 10:04:15 * @copyr ight Daxiang */public class Adminservice {/** * Login service *  * @param ID * @param pwd * @return 1, Success 2, username error 3, password error * @throw s Exception */public int Login (string username, string pwd) throws Exception {//New Admin Database Operation object Admindao Admindao = new ADM Indao ();//1, according to the user name entered to query the database whether the user admin admin = admindao.query (username);//Determine whether the queried user exists if (admin! = NULL) {//2, If the password entered is the same as the password stored in the database if (Admin.getpassword (). Equals (pwd)) {//Returns a successful code return 1;} Returns the code with the wrong password return 3;} Returns the code of the user name error return 2;} /** * Change Password service *  * @param ID * @param pwd * @param newpwd * @return False Modify failed True Modify */public Boolean changepwd (stri Ng ID, string pwd, String newpwd) {return false;}}

Modify the processing in LoginView

Button.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {try {// Get admin Action Service Adminservice adminservice = new Adminservice ();//Handle login int i = Adminservice.login (Textfield.gettext (), New String (Passwordfield.getpassword ()));//Display various results switch (i) {case 1:joptionpane.showmessagedialog (NULL, "Login succeeded");// Release the screen resource Dispose ();//Open the main interface new MainView (); Break;case 2:joptionpane.showmessagedialog (null, "User name is wrong! "); Break;case 3:joptionpane.showmessagedialog (null," Password is wrong! "); break;default:break;}} catch (Exception E1) {e1.printstacktrace ();}}});

User name Error

Password error

Login successful

  

Java Course Design---implementation login (2)

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.