Learning History of Java (i)

Source: Internet
Author: User

have been thinking about writing something special, so that people who are interested in learning programming can really learn some dry food, today to write at random.

Everyone on the Internet to find the most of the demo estimate is the login function of the demo, why do you prefer to take the login to do the demo? Because the core of the industry application class is to allow users to interact with the data, for a senior DBA, his interaction with the data can be directly related to the database, and for small white users, it requires a very friendly UI to interact with the data. Then you need a variety of programming language tools to implement this process. And we develop an application-class software, mainly to the needs of the business to fully understand the development, such as the development of a financial software, if you do not understand the financial, talk about what to develop. and the login function is the most contact, do not have to explain the function of the business, so as the demo is the most appropriate explanation of nature. The following is the Java learning to explain the login demo, from the beginning of the Helloword model has evolved to the SSM framework model, the demonstration process interspersed with the various learning stages involved in the basic knowledge points.

Here the programming tool uses eclipse, first building a common Java project, writing our first program

Package com.xdw;/** * @author Xiadewang * January 14, 2018 */public class Logintest {    /**     * @param args */    Publi c static void Main (string[] args) {        //TODO auto-generated method stub        System.out.println ("Welcome to login");    }        }

It's simple, isn't it helloword? The Main method is the entry method for the program.

OK below for the above procedure step by step expansion, think of login is the user name and password to judge, then modify the code as follows:

    public static void Main (string[] args) {        //TODO auto-generated method stub//        System.out.println ("Welcome to login"); c13/>string username = "XDW", password= "123456";        if (username== "XDW" && password== "123456") {            System.out.println ("XDW user login succeeded");            } else {            System.out.println ("Login Failed");            }    }

This introduces the declaration, definition and assignment of variables of Java basics, variable types, annotations, comparison operators, if. else logical statement. These foundations are no longer wordy.

After this rewrite, found that only the user XDW login to judge, if each change a user name or password, you have to change the entire code above, then this time on the function (in Java called method) appearance.

The user name and password are used as the parameters of the method, and the result is judged as the return value. The code is as follows

 Package com.xdw;/** * @author Xiadewang * January 13, 2018 */public class Logintest {public static void main (string[] Ar GS) {//TODO auto-generated method stub//System.out.println ("Welcome to login");/* String username = "Xdw", pas        Sword= "123456";            if (username== "XDW" && password== "123456") {System.out.println ("XDW user login succeeded");            }else {System.out.println ("Login Failed");        }*/logintest login=new logintest ();        if (Login.checklogin ("Xdw", "123")) {System.out.println ("login Successful");        }else {System.out.println ("Login Failed");        } if (Login.checklogin ("xxx", "1234")) {System.out.println ("login Successful");        }else {System.out.println ("Login Failed"); }} public Boolean checklogin (String username,string password) {if (username== "XDW" && password=        = "123") {return true;        } else {return false; }            }}

Above the first main function inside the logical judgment encapsulated in the Checklogin function, because there is no UI interface, we will print printing as the actual business processing, the face of Checklogin method is to do the purely logical processing,

Specific business we're still doing it in the main method, so we'll set the return value of the Checklogin method to Boolean instead of void. At this point a little logic with the taste of business separation.

By the way how to define the method, the first is the modifier (public or private and protected, this knowledge point is mainly to understand their scope, not clear the classmate hurriedly to review), and then the return type (if it is void, then in the function body does not need to return, Others need retrun. ), followed by the function name (the naming convention is usually the first lowercase, the hump named), the following is the formal parameter (the naming specification is also the first letter lowercase, hump named).

So now that the method is well defined, how do we call it in main? First the main method is static, and the method we are defining now is non-static, in the same class, the static method is not directly invoke the other non-static methods in the class, you need to first new one of the object of that class, and then through the object to make the method call , as shown in the code. Another way is to change the Checklogin method to a Staic method, then the new is not used in main, call the method directly. Look at the code below.

Package com.xdw;/** * @author Xiadewang * January 13, 2018 */public class Logintest {public static void main (string[] args) { TODO auto-generated method stub//System.out.println ("Welcome to login");/* String username = "XDW", password        = "123456";            if (username== "XDW" && password== "123456") {System.out.println ("XDW user login succeeded");            }else {System.out.println ("Login Failed");            }*/if (Checklogin ()) {System.out.println ("visitor login");        } logintest login=new logintest ();        if (Login.checklogin ("Xdw", "123")) {System.out.println ("login Successful");        }else {System.out.println ("Login Failed");        } if (Login.checklogin ("xxx", "1234")) {System.out.println ("login Successful");        }else {System.out.println ("Login Failed"); }} public Boolean checklogin (String username,string password) {if (username== "XDW" && password=       = "123") {return true; } else {return false;    }} public static Boolean Checklogin () {return true; }}

As you can see in Main, Checklogin () is called directly, and this function does not pass the username and password, it is equivalent to the visitor mode login, and a knowledge point overload is introduced here. What is overloading? The overloaded two elements are the same function name, the parameters are different (the parameter is different refers to the number of arguments, or the type of the parameter is different, not the name of the parameter, the name of the formal parameter can be arbitrarily named). What is the role of overloading? It is entirely possible to re-fetch individual names for the Checklogin method above. It's a drop, take another name. There is no problem, the main function of overloading is to increase the readability of the program, we read the API document in a lot of time through the name of the function will probably know what it is for. When we call, we do not need to remember so many method names, but know the function of the method can directly give him to pass different parameters, the compiler will clearly know which method we call.

Write here, all of our user data is written in the code of the fictitious data, the actual business, the user data will certainly not be written in the code, then it is time to go to the database. In the actual development, the user data are stored in the database, at this time to determine the user login simple logic, we pass the user name and password parameters to the Checklogin method, and then the method to query the database, see if the user name and password match, if the match is a successful login, and vice versa. How do I connect to a database in Java? In this case, JDBC is needed, and here's an example of MySQL, which gives a brief explanation of the JDBC operation flow.

We add the following method to the previous code CHECKLOGINBYJDBC, and we can no longer use the name Checklogin, because the formal parameters are the same.

Package Com.xdw;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.preparedstatement;import Java.sql.resultset;import java.sql.sqlexception;/** * @author Xiadewang * January 13, 2018 */public class Logintest {private    Connection Connection=null;    Private ResultSet Resultset=null;         public static void Main (string[] args) {//TODO auto-generated method stub//System.out.println ("Welcome to login");/*        String username = "XDW", password= "123456";            if (username== "XDW" && password== "123456") {System.out.println ("XDW user login succeeded");            }else {System.out.println ("Login Failed");            }*/if (Checklogin ()) {System.out.println ("visitor login");        } logintest login=new logintest ();        if (Login.checklogin ("Xdw", "123")) {System.out.println ("login Successful");        }else {System.out.println ("Login Failed");  } if (Login.checklogin ("xxx", "1234")) {System.out.println ("login Successful");      }else {System.out.println ("Login Failed");        } if (Login.checkloginbyjdbc ("Xdw", "123456")) {System.out.println ("XDW successfully through JDBC");        }else {System.out.println ("Login Failed"); }} public Boolean checklogin (String username,string password) {if (username== "XDW" && password=        = "123") {return true;        } else {return false;    }} public static Boolean Checklogin () {return true;            public boolean checkloginbyjdbc (String username,string password) {try {//Get database connection driven by reflection            Class.forName ("Com.mysql.jdbc.Driver"); try {//Get Database Connection object Connection=drivermanager.getconnection ("Jdbc:mysql://127.0.0.1/jsplogintes                T "," root "," root "); Build the SQL statement that represents the parameter that needs to be bound String sql= "SELECT * from user where username=?                and password=? ";              Get PreparedStatement Object  PreparedStatement preparedstatement=connection.preparestatement (SQL);                Binding Parameters Preparedstatement.setstring (1, username);                Preparedstatement.setstring (2, password);                Execute the SQL statement, here is the query statement, so call executeQuery return result set resultset=preparedstatement.executequery ();                    After getting the result set, the operation of the database is finished, followed by the result set to process our business logic if (Resultset.next ()) {//result set is not empty, it can indicate that the user exists, that is, the login succeeds                    Resultset.close ();                    Connection.close ();                return true; }} catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace            (); }} catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ()        ;            } return false; }}

The data table is structured as follows

The operation flow of the JDBC is also written more clearly, the later is divert, the JDBC operation is very simple, the important skill is still to play on the SQL cattle.

The reusability of the code here is too poor, when not writing a method, all to write a bunch of JDBC connection and close operation is obviously unrealistic, so we need to encapsulate them into a tool class, such as the following DBHelper

Package Com.xdw;import java.sql.Connection;  Import Java.sql.DriverManager;  Import java.sql.PreparedStatement;  Import java.sql.SQLException; /** * @author Xiadewang * January 13, 2018 */public class DBHelper {public static final String URL = "jdbc:mysql://127.0.0.      1/jsplogintest ";      public static final String name = "Com.mysql.jdbc.Driver";      public static final String user = "root";        public static final String password = "root";      public Connection conn = null;        public PreparedStatement PST = NULL; Public dbhelper (String sql) {try {class.forname (name);//Specify connection Type conn = DRIVERMANAGER.G Etconnection (URL, user, password);//get connection PST = conn.preparestatement (SQL);//Prepare to execute statement} catch (exceptio          n e) {e.printstacktrace ();              }} public void Close () {try {this.conn.close ();          This.pst.close (); } catch (SQLException e) {e.printstAcktrace ();   }      }  }

Then rewrite the Checkloginbyjdbc method, as follows

public boolean CHECKLOGINBYJDBC (string username, string password) {        try {            string] sql = "SELECT * from user where u Sername=? and password=? "; /SQL statement            dbhelper DB1 = new DBHelper (SQL);//Create DBHelper Object            db1.pst.setString (1, username);            Db1.pst.setString (2, password);            ResultSet ret = Db1.pst.executeQuery ();//execute statement, get result set            if (Ret.next ()) {                return true;            }            Ret.close ();            Db1.close ();//close Connection                    } catch (SQLException e) {            //TODO auto-generated catch block            e.printstacktrace (); c16/>}        return false;    }

The first stage to come here, we are all using a process-oriented approach to achieve this function, directly want to implement the login function, in the main entrance of the processing business to start coding, the following introduction of the concept of the interface, from the design level to talk about how to implement the login function, that is, interface-oriented programming

Learning History of Java (i)

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.