Prepare <br /> in the early stages of <br />, first of all, you must clearly have a general idea, what functions to achieve, to understand what aspects of the entire module to be used, and to discover your shortcomings from the process of doing. Most of the technical progress needs to be come out of practice.
Function : User registration function+system login function+generating verification code
Knowledge : window design, database design, JavaBean packaging attributes, JDBC implementation of the database connection, verification code (including color verification code) generation technology, and some such as using regular expression verification user registration information, randomly obtain characters to obtain characters String, control of the number of characters in text, etc.
Design module preview map:
Preview of color verification code:
Database used: MySQL
Database design
Create a database DB_DataBase01, which contains a table TB_USER to save users' registration data.
It contains 4 fields
id int (11)
Username varchar (15)
password varchar (20)
email varchar (45)
MySQL statement can be designed like this:
Create schema db_database01; use db_database01; Create Table TB_USER (ID int (11) not null auto_increment primary, username varchar (15) d varchar (20) not null, email varchar (45) not null); insert into tb_user Values (1, "lixiyu", "lixiyu", [email protected]);
Use lixiyu as a username.
Select statement to check the created form:
Write javaBean packaging user attributes
package com.lixiyu.model; Public Class User {Private int ID; // number Private String username; // User name private string password; // Password Private String email; // Email Public int Getid () {Return ID; } PUBLIC VOID SETID (int ID) {this.id = id;} Public String getuseernErname () {Return username;} Public void setusername (string username) {Thi s.username = username;} Public String Getpassword () {Return Password; } PUBLIC VOID SETPASSWORD (String Password) {This.password = Password;} Public String Getemail () {Return Email;} Public Void Seitemail (Strin g email) {this.email = email;}}
Write the JDBC tool class
Place the code related to the database operation in the DBCONFIG interface and the DBhelper class
DBconfig interface is used to save database, username and password information code:
package com.lixiyu.util; Public interface dbconfig {string databasename = "db_database01"; // The database name string username = "root"; // database user name String Ord = "lixiyu"; // Database password}
To simplify the development of JDBC, DBhelper used the Commons DBUTIL combination.
The DBHELPER class inherits the DBCONFIG interface. This class contains 4 methods:
(1) GetConnection () method: obtain database connection, use mysql data source to simplify programming to avoid abnormalities due to loading database drivers.
(2) Exist () method: Determine whether the input user name exists.
(3) Check () method: When the user enters the username and password, check whether the check () method is correct.
(4) Save () method: After the user enters legal registration information, save the information.
Detailed code:
package com.lixiyu.util; Import Java.SQL.CONNECTION; Import Java.sql.sqlexception; Import Java.util.arrays; Import Java.util.list; Import. apache.commons.dbutils.dbutils; Import org.apache .commons.dbutils.queryrunner; Import org.apache.commons.dbutils.ResultSethandler; Import Import org.apache.commons.dbutils.handlers.scalarhandler; Import org.apache.Commons . Lang.Stringescapeutils; Import com.lixiyu.model.user; Import com.mysql.jdbc.jdbc2.Optional.MSQLDATARCE; onfig { / * * Use mysql data source to obtain the database connection object * * @Return: MySQL Connecting objects, if you get a failure, return null */ public static connection getConnection () {MySQLDATASOURCE MDS = New MySQLDATASORCE (); // Create mysql data source MDS.SetDataBaseName ( databasename); // Set the database name mds.setuser (username); // Set the database user name mds.setpassword (password); // Set database password try {return mds.getConnection (); // get connection} Catch (sqlexception E) {e.printstacktrace ();} n null; // If you fail to get, return null} / * * to determine whether the user who specifies the user name is available. NER = NEW QueryRunner (); // Create the QueryRunner object string sql = "select id from tb_user when username = '" + username + "';"; // Define the query connNNECTION (); // Get connecting ResultSethandler <List < Object >> rsh = new columnlisthandler (); // Create the results set processing class Try {list <object> result = runner.query (conn, sql, rsh); ) {// If there is a data Return True in the list; // Return True} else {// If there is no data Return false in the list; // Return to false} {sqlexception E) {e.printstacktrace ();} FINALLY. {{ Dbutils.closequietly (conn); // Turn off the connection} Return false; // If an abnormality occurs, return false}/ * * to verify whether the user name and password are correctly use the Commons LANG component to avoid SQL injection * * @Return: Return to True, error Return to False */ Public Static Boolean Check (String Username, Char [] Password) {Username = StringScapeutils.escapesql (username); // The input user name to QueryRunner Runner = New Queryrunner ();/ / Create the Queryrunner object string SQL = "Select Password from TB_USER WHERERNAME = '" + Username + "';"; // Define the query statement connection (); // Plot ResultSethandler <Object> RSH = New SCALALANDLER ( ); // Create the results set processing class try {string result = (string) runner.query (conn, sql, rsh); // Get the query result char [] queryPassword = result.tocharray (); // The password is converted to the character array IF (ARRERAYS.Equals (password, querypassword)) {// If the password is the same, return True Arrays.fill (password, '0'); // The password arrays.fill (queryPasswork d, ' 0 '); // Clear the query password Return True;} else {// If the password is different, return false arrays.fill (password,' 0 '); '); // Clear the query password Return false;}} Catch (sqlexception E) {e.printstacktrace ();} Finally {dbutils.closequietly (conn); e; // If an abnormal return occurs FALSE} / * * Save the registered information entered by the user * * @Return: If the save is successfully returned to TRUE, the preservation failure returns the false * / public static boolean save (user user) {queryrunner runner = new questionrunner (); // Create Queryrunner object String SQL = "Insert Into TB_USER (Username, Password, Email) Values (?,?,?);"; // Define the query connn = getConnection (); // = {user.getusername (), user.getpassword (), user.Getemail ()}; // The parameters of the passing of the passing try {int Result = runner.Update (conn, sql, params); // Save user if (result> 0) {/////// / If the save is successfully returned to True Return True;} Else {// If the preservation fails, return false return false;}} Catch (sqlexception e) {e.printstacktrace ();} Finally { Equietly (conn); // Close the connection } Return false; // If an abnormality occurs, return false}}
System login
1.1 Window design
Use the BoxLayout layout to set the control arrangement method from top to bottom:
Copy code code as follows: ContentPane.setLayout (New BoxLayout (ContentPane, Boxlayout.page_axis));
The window uses controls, text domains, password domains, buttons and other controls to implement code:
Public Class Login Extends Jframe {Private Static Final Long SerialVersionuid = -4655235896173916415L; Private Jpanel Contentpane; nametextField; Private JpasswordField PasswordField; Private JTextField ValidatetextField; Private String Randomtext; Public Static Void Main (String AR gs []) {try {uimanager. setlookandfeel ("" com.sun.java.swing.plaf.nimbus.nimbuslookandfeel ");} Catch (Throwable E) {eventQueue.invokeler (NEW R) unnable () {public void run () {try { login frame = new login (); frame.setvisible (true);} Catch (Exception E) {e.printstacktrace ();}}); SetDefaultCloseoperation (JFRAME .Exit_on_close); ContentPane = new jpanel (); setContentPane (contentpane); contentpane.setLayout Jpanel usernamepanel = new jpanel (); contentpane.add (usernamepanel); jlabel usernameLable = new JLABEL ("/U7528/U6237/U540D/UFF1A"); Usernamelable.setfont (new FONT ("Microsoft Yahei", FONT.PLAIN, 15); Usernamepanel.add (usernamelable); username Textfield = new jtextField (); usernametextField .setfont (new FONT ("Microsoft Yahei", Font.Plain, 15); Usernamepanel.add (usernametextField); usernametextField.SetColumns (10); anl (); contentpane.add (passwordpanel); jlabel passwordLabel = New Jlabel ("/U5BC6 /U7801/Uff1a"); PasswordLabel.setfont to Wont (" Microsoft Yahei ", font.plain, 15); PasswordPanel.add swordfield = new jpasswordField (); passwordField.setColumns (10); PasswordField.setfont (new FONT ("Microsoft Yahei", FONT.PLAIN, 15); PassWordPanel.add (PasswordField); anl (); contentpane.add (valuepanel); Jlabel value = new jlabel ("/U9A8C/U8BC1/U7801/UFF1A"); Validatelabel.Setfont (new font ("Microsoft Yahei", font.plain, 15); ValidatePanel.add (Vali Datelabel); ValidatetextField = New JTextField (); ValidatetextField.setfont (new FONT ("Microsoft Yahei", FONT.PLAIN, 15); Validatepanel.add (ValidateTextField); ValidateTextField.SetColumns (5); Randomtttomtt Ext = RandomStringUtils.randomalPhanumeric (4); CaptChalabel Label = New CaptChalabel (Randomtext); // Random verification code label.setfont (new FONT ("Microsoft Yahei", FONT.PLAIN, 15)); ValidatePanel.add (label); ENTPANE.ADD (ButtonPanel); JBUTTON SUBMITBUTTON = New Jbutton ("Login"); SubmitButton.adDactionListener (New ActionListener () {@Overridepublic Void Void (ACTIONPERFORMED ctionevent e) {do_submitButton_ACTIONPERFORMED (e);}}); Microsoft Yahei ", font.plain, 15)); Buttonpanel.add (submitButton); jbutton Cancelbutton = New Jbutton (" Exit "); CancelButton.addActionListener (New ActionListener () {PU Bil Void ActionPerformed e);}); CancelButton.setfont (New Font ("Microsoft Yahei", FONT.PLAIN, 15)); Buttonpanel.add (CancelButton); Pack (); // Automatically adjust the window size setlocation (COM. lixiyu.util.swingutil.centrecontainer (GetSize ())); // Let the window be displayed in the middle
Display in the window:
Public Class Swingutil {/** According to the size of the container, the upper left corner coordinates are calculated. olkit.getDefaultToolkit (). GetScreensize () ; // Get the screen size int x = (screenize.width -size.width)/ 2; // Calculate the X -coordinate Int y = (screenSize.height -size.head)/ 2; // Calculate the upper left corner Y coordinate Return New Point (x, y); // Return to the upper left corner coordinates}}
1.2 Obtaining and drawing verification code
Public Class Captchalabel Extends Jlabel {Private Static Final Long SerialVersionuid = -963570191302793615L; PRIVATE String Text; // Ublic CaptChalabel (String Text) {this.text = text; setpreferredsize (New Dimension (60, 36); // Set the size of the label} @Overridepublic Void Paint (Graphics G) {Super. Paint (g); // Call the parent -class constructor G.Setfont (New FONT ("Microsoft Yahei", FONT. Play, 16); // Set font G.Drawstring (text, 5, 25); // Draw string}}}
*Color verification code:
Public Class Colorfulcaptchalabel Extends Jlabel {Private Static Final Long SerialVersionuid = -963570191302793615L; PRIVATE String Text; // The string of proved pictures private color [] colors = {color.black, color.blue, color.cyan, color .Dark_gray, color.gray, color.green, color.light_gray, color.magenta, color.orange, color.pink, color.red, color.yllow}; // Define the paint color array publ group publ IC ColorfulcaptChalabel (String Text) {this.text = text; setpreferredsize (New Dimension (60, 36)); // Set the size of the label} @OverridePubilic void (Graphics G) {Super. Paint (g); // Call The structure of the parent Methods G.Setfont (new font ("Microsoft Yahei", FONT.PLAIN, 16)); // Set font for (int i = 0; i <text.length (); i ++) {g.SetColor (color [colors [color Randomutils.nextint (colors.length)); g.Drawstring ("" + Text.chaarat (i), 5 + I * 13, 25); // Draw string}}}}}}}}
1.3 Non -empty school
if (username.isempty ()) {// Determine whether the user name is emptyPanepane.showmessageDialog (this, "user name cannot be empty!", "warning information", jobpane.warning_message); Return;} if (NE W String ( Password) .ISEMPTY ()) {// Determine whether the password is empty jobpane.showmessageDialog (this, "password cannot be empty!", "Warningpane.warning_message); RETURN;} if (valid ATE.ISEMPTY ())) {// Determine whether the verification code is emptyPanepane.showmessageDialog (this, "verification code cannot be empty!", "Warning information", jobpane.warning_message); RETURN;}
1.4 Legality verification
if (! Dbhelper.exists (username)) {// If the user name does not exist, it will prompt jobpane.showmessageDialog (this, "user name does not exist!", "warningpane.warning_message); return; } if ( ! Dbhelper.Check (username, password)) {// If the password is error, it is prompted by prompts. ;} if (! Validate.equals (RANDOMTEXT) {// If the school code is not matched, it is prompted to prompt jobpane.showmessagedialog (this, "verification code error!", "Warning information", jobparning_message); Return;}
1.5 Display the main window
EventQueue.invokelateer (new runnable () {@OverridePublic void run () {Mainframe Frame = New Mainframe (); // Create the main window Frame.SetVisible (True); // Set the main window to see} Catch (Exception e) {e.printstacktrace ();}}}); dispose (); // destroy the login window}
Design the main window (relatively simple this):
Public Mainframe () {SetdefaultCloseoperation (jframe.exit_on_close); // The operation of Setsize (450, 300) when you set the closing window button (450, 300); // ContentPane = New Jpanel (); // Create a panel Contentpane .setLayout (New Borderlayout (0, 0)); // Set the panel layout and use the boundary layout setcontentpane (contentpane); // Apply panel jlabel tiplabel = new jlabel ("Congratulations on your successful login system!"); EL .setfont (new FONT ("Microsoft Yahei", FONT.PLAIN, 40); // Set tag fonts Contentpane.add (TipLabel, BorderLayout.center); // Application label setlocation (Swingutil.CentreContainer (GETSI ZE ())) ); // Let the window stand in the middle of the window}
User registration
1.1 Window design
Public Class Register EXTENDS JFRAME {/****/Private Static Final Long Serizationuid = 2491294229716316338L; Private Jpanel Contentpane; FIELD UsernametextField; Private JpasswordField PasswordField1; Private JpasswordField PasswordField2; Private JtextField EmailTextField; Prive abel tiplabel = new jlabel ();/ /Display prompt information/*** launch the application.*/Public Static void main (string [] art) {try {uIMANAGER.SETLOOKANDfeel ("com.sun.java.plaf.nimbus.ni.ni mbuslookandfeel ");} catch (Throwable E) {E.printstacktrace ();} EventQueue.invokelo (new runnable () {@Overridepublic void run () {try {register frame = newer (); f rame.setvisible (true);} Catch (Exception E ) {e.printstacktrace ();}}});}/*** create the frame.*/public register () {settitle ("/u7528/u6ce8/u518c"); seoperation (jframe.exit_on_close); Contentpane = new jpanel (); setContentPane (contentpane); contentpane.setLayout (new boxLayout (contentpane, boxLayout.page_axis)); = new jpanel (); contactpane.add (usernamepanel); jlabel usernamelabel = new jlabel ("// u7528 /u6237 /u540d/Uff1a") ;Uernamelabel.setfont to. w jtextField (); UsernametextField.SetTooltiptext (" /U8BF7/U8F93/U51655 ~ 15/U4E2A/U7531/U5B57/U6570/U5B57/U4E0B/U7212/U7EBF/U7684/U7684/U7B57/U7B26/u7B26/ u4e32 "); abstractDocument doc = (abstractdocument) usernametextField.GetDocument (); DOC.SetDocumentFilter (New DocumentSizeFilter (15)); // Limit the length of the character in the text domain to 15doc.adddocumentListener (New DocumentSizelisizer, 15); User. nametextField.Setfont (New FONT ("Microsoft Yahei", Font.plain, 15)); Usernamepanel.add (usernametextField); usernametextField.setColumns (10); sswordpanel1); /U7801/uff1a"); PasswordLabel1.setfont toSet ("Microsoft Yahei", FONT.PLAIN, 15)); PasswordPanel1.add (PasswordField1 = newwordfield (PasswordFordField1 = newwordField ( ); ABSTRCTDOCUMENT) passwordField1.getdocument (); DOC.SetDocumentFilter (New DocumentSizeFilter (20)); // Limit the length of the character in the password to be 20doc.adddocumentListener (New Documeentsizelisizer, 20)); Passw Ordfield1.setfont (New FONT ("Microsoft Yahei", Font.plain, 15)); PasswordField1.setColumns (10); PasswordPanel1.add (PasswordField1); jpanel passwordpanel2 = new jpanel (); Contentpane.add (PassWordPanel 2); /U7801/uff1a"); PasswordLabel2.setfont toSet ("Microsoft Yahei", FONT.PLAIN, 15)); passwordpanel2.add (PasswordField2 = newwordField ); ABSTRCTDOCUMENT) PasswordField2.getdocument (); DOC.SetDocumentFilter (New DocumentSizeFilter (20)); // Limit the length of the character in the password to be 20doc.adddocumentListener (New Documeentsizelisizer, 20)); Passw Ordfield2.Setfont (New FONT ("Microsoft Yahei", Font.plain, 15)); PasswordField2.setColumns (10); PasswordPanel2.add (PasswordField2); jpanel emailpanel = new jpanel (); ContentPane.add (emailPanel); JL Abel Emaillabel = New Jlabel ("/U7535/U5B50/U90Ae /U7bb1/uff1a") ;emaillabel.setfont to; "Microsoft Yahei", FONT.PLAIN, 15)); emailpanel.add (emailLabel); emailTextField = new jtextField (); doc = (ab (ab v. stractDocume) emailtextField.getdocument (); DOC.SetDocumentFilter (New DocumentSizeFilter (45)); // Limit the length of the character in the text domain to 45doc.adddocumentListener (new documentSizelistener, 45); MailtextField.Setfont (New FONT ("Microsoft Yahei", Font.plain, 15)); emailpanel.add (emailtextField); emailtextField.setColumns (10); jpanel Buttonpanel = New Jpanel (); TTON SUBMITBUTTON = New Jbutton ("/U63D0/U4EA4") ; Submitbitton.AdDACTIONLISTENER (New ActionListener () {@OVERIDEPUBLIC VOID ActionPerFormed }); ButtonPanel.setLayout (New BoxLayout (Buttonpanel, BoxLayout.line_axis)); "Microsoft Yahei", font.plain, 15); Buttonpanel.add (Tiplabel); Component Glue = Box.createglue (); Buttonpanel.add (Glue); ,, Font.plain, 15)); ButtonPanel.add (submitButton); jbutton CancelButton = New Jbutton ("/U53D6/U6D88"); CancelButton.addAcityListener (New ActionListener () () {@OverridePublic Void ActionPerformed (ActionEvent E) {do_cancelButton_ACTIONPERFORMED (E );}}); CancelButton.setfont (new FONT ("Microsoft Yahei", FONT.PLAIN, 15); Buttonpanel.add (CancelButton); Pack (); // Automatically adjust the size of the window setlocation (SwingUtil.CentReCONTRECONTRECONTRECONTRECONTRECONTR ainer (Getsize ())); // Let the window display in the middle of the window}
1.2 Use DocumentFilter to limit the number of characters available in text
Public Class DocumentsizeFilter Extends DocumentFilter {Private Int MaxSize; // Get the maximum length of the text Public DocumeFilter (INT MAXSIZE) {This.maxSize = maxsize; // Get the maximum length entered by the user} @OverridePublic Void Insertstring (Filterbypass FB, Int Office, String String, AttributeSet Attr) Throws BadLocationException {if (fb.getdocume (). GetLength () + String.length ()) <= MaxSize) Large -length super.InSertstring (FB, Offset , string, attr); // Call the method of the parent class} else {Toolkit.getDefaultToolkit (). Beep (); // Effects the prompt sound}@ouverridepublic void replace (FilterBypass Fb, INTTTT Offset, int length, string text , AttributeSet Attrs) Throws BadLocationException {if (fb.getdocument (). Getlength () + Text.length () <= MaxSize) {// Super.replace (fb, offset , length, text, attrs); // Call the method of the parent class} else {Toolkit.GetDefaultToolkit (). Beep (); // Effective sound}}}}}}}
1.3 Use the DocumentListener interface to implement the display text control.
Public Class DocumentsizedSizelisizelisizelisizelisizelisize Elements DocumentListener {Private Jlabel TipLabel; Private Int MaxSize; Public DocumenTsizelisizer (Inton maxsize) {this.tiplabel = tipLabel; this.maxSize = maxsize;}@outerridepublic void Insertupdate (documentstevent e) {Settiptext (E) ;}@Ouverridepublic void removenate (DocumentEvent E) {settiptext (e);}@osuePublic voidupDate (DocumentEvent E) {SettiPtext ( e);} Private void SettiPtext (DocumentEvent E) {document doc = e.getdocument ();// / Obtain the document object tipLabel.setForeground (color.black); // Set font color if (doc.getlength ()> (maxsize * 4/5)) {// If the length of the input character is greater than the maximum length of 80%tipLabel. setforeground (color.red); // Use red display prompt information} else {tipLabel.setForeground (color.black); // Use black display prompt information} tipLabel.Settext ("prompt message:" + doc.GetLength () + "/" + maxsize);}}
1.4 Non -empty school
if (username.isempty ()) {// Determine whether the user name is emptyPanepane.showmessageDialog (this, "user name cannot be empty!", "warning information", jobpane.warning_message); Return;} if (NE W String ( Password1) .ISEMPTY ()) {// Determine whether the password is empty newspane.showmessageDialog (this, "password cannot be empty!", "Warningpane.warning_message); Return;} if (NEW S tring (password2). Isemption ()) {// Judging whether the confirmation password is emptyPanepane.showmessageDialog (this, "confirming the password cannot be empty!", "Warningpane.warning_message); pty ()) {{ // Determine whether the email is emptyPanepane.showmessageDialog (this, "Email cannot be empty!", "Warning information", jobpane.warning_message); Return;}
1.5 Use regular expression verification string (legitimacy verification)
// Wheat whether the user name is legal if (! Pattern.matches ("// w {5,15}", username) {jobpane.showmessagedialog (this, "Please enter the legal user name!", "Warning Information" , Jobpane.warning_message); Return;} // Check whether the password you input twice is the same if (! Arrays.equals (password1, password2)) {jobpane.showMessageDialog (this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this, this "Different passwords input!", "", "" " Warning information ", jobpane.warning_message); Return;} // check whether the email address is legitimate if (! Pattern.matches (" // w+@/w+/w+ ", email) {jobpine.showmessagedialo G (This, "Please enter the legal email!", "Warning information", jobpane.warning_message); Return;} // check whether the user name exists if (dbhelper.exists (username)) {jobpane.showmessagedia Log (this, "Username already existed", "Warning Information", jobpane.warning_message); Return;}
1.6 Save the registration information
User user = new user (); user.setusername (username); user.setpassword Ord1, '0'); The character array arrays.fill (password2, '0'); // The character array of the character with the password IF (dbhelper.save (user)) {jobpane.showmessageDialog (this "user registration!" ane .Information_message); Return;} else {jobpane.showmessageDialog (this, "user registration failed!", "Warningpane.warning_message); Return;}}}
At this point, a simple and complete login registration module is completed.
The above is all the contents of this article. I hope everyone can like it.