JAVA by pengxiuhui

VIEWS: 424 PAGES: 100

									JAVA
                               Content
„   Introduction of JAVA
„   Compile & Run program
„   Handling Exception
„   Connecting to Database
„   JAVA and Web Application
„   XML Parser
„   JAVA and Web Services
„   Jcreator LE Installation
                                         2
                       Introduction of Java
„ What is JAVA?
   ‟ Is a high level programming language developed by Sun Microsystems.
   ‟ Is an Object Oriented language similar to C++ which can operate on Internet
„ Object Oriented Programming
   ‟ Inheritance is a way to form new classes.
       „ derived classes, take over (or inherit) attributes and behavior of the pre-
          existing classes, which are referred to as base classes (or ancestor
          classes).
   ‟ Encapsulation is the information hiding
       „ to prevent user from modifying code
       „ Prevent procedures to be reveal
                  Introduction of Java
‟ Polymorphism is allowing a single definition to be used with different types
  of data.
    „ function definition can replace several type-specific ones, and a single
      polymorphic operator can act in expressions of various types.
‟ Abstract is the process of hiding the details and exposing only the essential
  features of a particular concept or object.
                       Introduction of Java
„ Advantage of JAVA
   ‟ Multiplatform
   ‟ Has full support on Object Oriented Programming
   ‟ Contain features Robust, handle Garbage Collection automatically and
     automatically Exception Handling
   ‟ Secure in evaluation by using Sandbox system.
   ‟ Multithread: to process many job at the same time.
                                      Class
„ A class is the blueprint from which individual objects are created.
„ The class body follows the class declaration and is contained within curly braces:
  { to begin the body and } to end the body.
„ The class body contains :
    ‟ constructor
    ‟ methods
    ‟ Variables (fields)




                                                                                   6
Class Bicycle




                7
                  Object

        MyBike




Bike


       YourBike




                           8
Example




          9
                              Class syntax
[<class_modifiers>] class <class_name>
                    [extends <subclass_name>]
                    [implements <interface1>,<interface2>,…]{
                    // method & instance variable
}
class MyClass extends MySuperClass implements YourInterface {
         //field, constructor, and method declarations
}

                                                                10
                             Class modifier
      Modifier                                  Description
     public (A)        Class may be accessed by anyone, anywhere member is
                       accessible anywhere the class is
    protected (A)      member is accessible within the defining package and
                       within subclasses
blank (A) ("friendly") may only be accessed within the package
     private (A)       member is only accessible to the class that defines it
        static         used to declare a toplevel class as opposed to an inner class
       abstract        cannot be instantiated, must be a superclass, used whenever
                       one or more methods are abstract
        final          Class cannot be inherited
                                                                                  11
                          Declaring Class
„ Modifiers such as public, private, and a number of others that you will
  encounter later.
„ The class name, with the initial letter capitalized by convention.
„ The name of the class's parent (superclass), if any, preceded by the
  keyword extends. A class can only extend (subclass) one parent.
„ A comma-separated list of interfaces implemented by the class, if any,
  preceded by the keyword implements. A class can implement more than
  one interface.
„ The class body, surrounded by braces, {}.                               12
Extends




          13
                   Declaring member variables
„ Member variables in a class †> fields.
   ‟ Instance Variables (Non-Static Fields)
   ‟ Class Variables (Static Fields)



„ Variables in a method or block of code †> local variables.



„ Variables in method declarations †> parameters.
                                                               14
„   [<field_modifiers>] <field_type> <field_name> [= <initial_value>];
„   Zero or more modifiers, such as public or private.
„   The field's type.
„   The field's name.




                                                                         15
                                  Fields Modifier
      Modifier                                          Description
     public (A)          Property may be accessed by anyone, anywhere
    protected (A)        may be accessed by methods within the same class or subclasses
blank (A) ("friendly")   may be accessed by methods within the same package only
     private (A)         may be accessed by methods within the same class only
        static           there is only one per class but still there could be more than one per
                         JVM
       volatile          Indicates that Java will read the variable from memory not from
                         individual caches assuring accuracy using concurrency. (not
                         implemented in all JVM's)
      transient          field should not be serialized
        final            makes the variable a constant
                                                                                                  16
                                 Naming Rules
„ Variable names are case-sensitive.
„ A variable's name can be any legal identifier † an unlimited-length sequence of
  Unicode letters and digits, beginning with a letter. Subsequent characters may be
  letters, digits, dollar signs, or underscore characters.
„ White space is not permitted.
„ The name must not be a keyword or reserved word.
„ If the name you choose consists of only one word, spell that word in all
  lowercase letters. If it consists of more than one word, capitalize the first letter of
  each subsequent word. Example : gearRatio and currentGear

                                                                                        17
„ If your variable stores a constant value, capitalizing every letter and
  separating subsequent words with the underscore character.
       static final int NUM_GEARS = 6
„ Reserved Word




                                                                            18
                            Defining Methods
[<method_modifier>] <return_type> <method_name> ([<params>]){
   //method body
}
„ Modifiers
„ The return type †the data type of the value returned by the method, or void if the
   method does not return a value.
„ The method name
„ The parameter list in parenthesis†a comma-delimited list of input parameters,
   preceded by their data types, enclosed by parentheses, (). If there are no
   parameters, you must use empty parentheses.                                     19
                         Method Modifier
      Modifier                                          Description
     public (A)          Method may be accessed by anyone, anywhere
    protected (A)        may be accessed by methods within the same class or (subclasses
                         anywhere)
blank (A) ("friendly")   may be accessed by methods within the same package only
     private (A)         may be accessed by methods within the same class only
        static           cannot be instantiated, are called by classname.method,can only
                         access static variables
       abstract          Method is defined but contains no implementation code
                         (implementation code is included in the subclass). If a method is
                         abstract then the entire class must be abstract.
    synchronized         acquire a lock on the class for static methods acquires a lock on the
                         instance for non-static classes
        final            Method cannot be overridden                                      20
                             Method Naming
„ Method names should be a verb in lowercase or a multi-word name that begins
  with a verb in lowercase, followed by adjectives, nouns.
„ In multi-word names, the first letter of each of the second and following words
  should be capitalized.
„ The rules for field names apply to method names




                                                                                    21
Overriding Method




                    22
                                 Constructor
„ A class contains constructors that are invoked to create objects from the class
  blueprint. Constructor declarations look like method declarations†except that
  they use the name of the class and have no return type.




„ Create a new Bicycle object called myBike, a constructor is called by the new
  operator


                                                                                    23
                                     Object
„ An object is a software bundle of related state and behavior. Software objects are
  often used to model the real-world objects that you find in everyday life.
„ An object stores its state in fields and exposes its behavior through methods.
  Methods operate on an object's internal state and serve as the primary mechanism
  for object-to-object communication. Hiding internal state and requiring all
  interaction to be performed through an object's methods is known as data
  encapsulation




                                                                                  24
                             Creating Objects
„ Declaration: The code set in bold are all variable declarations that associate a
  variable name with an object type.
  Point originOne;
„ Instantiation: The new keyword is a Java operator that creates the object.
  Point originOne = new Point(23, 94);
„ Initialization: The new operator is followed by a call to a constructor, which
  initializes the new object.



                                                                                     25
                          Using Objects
„ Referencing an Object's Fields
   ‟ objectReference.fieldName
„ Calling an Object's Methods
   ‟ objectReference.methodName(argumentList);
   ‟ objectReference.methodName();




                                                 26
                Example
„ BankAccount




                          27
                    ตัวอย่างจาวาโค้ด
„ HelloWorld.java
                        Workshop
„ http://wiki.nectec.or.th/setec/Knowledge/JavaDay1Workshops




                                                               29
                          Compiling a program
„ Java Compiler
   ‟ If the Java file you specify on the command line contains a reference to
      another Java class that’s defined by a java file in the same folder, the Java
      compiler automatically compiles that class too.
„ Command : javac ‟d . [program.java]
„ Compile many files :
   javac ‟d . [prog1.java] [prog2.java] [prog3.java]
„ Compile all files in folder : javac ‟d . *.java
„ Compile with specified classpath :
   javac ‟cp [lib1.jar];[prog1.class] ‟d . [prog.java]

                                                                                      30
Java Compiler Options




                        31
                       Running a Java program
„ Command : java [package.program1.class]
„ The class must be contained in a file with the same name as the class and the
  extension .class
„ It’s very case sensitive.




                                                                                  32
Java Options




               33
JCreator LE Installation




                           34
35
36
37
38
39
40
41
JavaBean
                              Definition
„ A JavaBean is a special type of Java class that you can use in several
  interesting ways to simplify program development.
„ It must have an empty constructor. That is, a constructor that
  accepts no parameters. If the class doesn’t have any constructors at all,
  it qualifies because the default constructor has no parameters. But if the
  class has at least one constructor that accepts one or more parameters,
  it must also have a constructor that has no parameters to qualify as a
  JavaBean.
                              Definition
„ It must have no public instance variables. All the instance variables
  defined by the class must be either private or protected.
„ It must provide methods named getProperty and setProperty to get and
  set the value of any properties the class provides, except for boolean
  properties that use isProperty to get the property value. The term
  property isn’t really an official Java term. In a nutshell, a property is
  any value of an object that can be retrieved by a get method (or an is
  method if the property is boolean) or set with a set method.
                               Bean features
„ Introspection Beans support introspection, which allows a builder tool to
  analyze how Beans work. Each Bean has a related Bean information class, which
  provides property, method, and event information about the Bean itself. Each
  Bean information class implements a BeanInfo interface, which explicitly lists
  the Bean features that are to be exposed to application builder tools.
„ Properties Properties control a Bean's appearance and behavior. Builder tools
  introspect on a Bean to discover its properties and to expose them for
  manipulation. As a result, you can change a Bean's property at design time.
„ Customization The exposed properties of a Bean can be customized at design
  time. Customization allows a user to alter the appearance and behavior of a Bean.
  Beans support customization by using property editors or by using special,      45

  sophisticated Bean customizers.
„ Events Beans use events to communicate with other Beans. Beans may fire
  events, which means the Bean sends an event to another Bean. When a Bean fires
  an event it is considered a source Bean. A Bean may receive an event, in which
  case it is considered a listener Bean. A listener Bean registers its interest in the
  event with the source Bean.
„ Persistence Beans use Java object serialization, implementing the
  java.io.Serializable interface, to save and restore state that may have changed as a
  result of customization.
„ Methods All JavaBean methods are identical to methods of other Java classes.
  Bean methods can be called by other Beans or via scripting languages. A
  JavaBean public method is exported by default.                                       46
Example
„ Package statement

„ Define class and make it implement java.io.Serializable

„ Declare two variables which hold name and age of a person




                                                              48
„ Create an empty argument constructor. Keep in mind that the only requirement to
  a JavaBean is an empty "argument" constructor

„ Writing getter and setter methods to access each private properties.




                                                                               49
                              Workshop1
„ Create your own bean.
   ‟ Person Bean
       „ Properties
            ‟   Name
            ‟   Age
            ‟   Address
            ‟   Phone
       „ Method
            ‟ Getter/setter
            ‟ Other

„ Use your own bean
                                          50
                      Handling Exceptions
„ An exception is an object that’s created when an error occurs in a Java
  program and Java can’t automatically fix the error. The exception
  object contains information about the type of error that occurred.




                                                                            51
                         Catching Exceptions
„ try {
         statements that can throw exceptions
   } catch (exception-type identifier) {
         statements executed when exception is thrown
   } finally{
         statements that are executed whether or not
         exceptions occur
  }
„ Catch all exceptions at once: catch(Exception e)

                                                        52
                                 Finally block
„ A finally block is a block that appears after all of the catch blocks for a statement.
  It’s executed whether or not any exceptions are thrown by the try block or caught
  by any catch blocks. Its purpose is to let you clean up any mess that might be left
  behind by the exception, such as open files or database connections




                                                                                      53
Displaying the Exception Message




„ Example
   }catch(Exception e){
      System.out.println(“Error : ”+e.toString());
   }
                                                     54
                  Handling Checked Exceptions
„ Catch the exception by placing the statement within a try statement that has a
  catch block for the exception.
„ Specify a throws clause on the method that contains the statement to indicate that
  your method doesn’t want to handle the exception, so it’s passing the exception
  up the line.




                                                                                   55
Example




          56
                        Swallowing exceptions
„ If you want to ignore the exception.
„ Catch the exception in the catch block of a try statement, but leave the body of
  the catch block empty.




                                                                                     57
                Throwing Your Own Exceptions
„ If you want to write methods that throw exceptions all on their own.
„ throw new exception-class();
„ The exception-class can be Exception or a class that’s derived from Exception.
  You may be create your own exception classes




                                                                                   58
Example




          59
Database




           60
                            Database
„ Data may be collected, manipulated and retrieved in various ways.
   ‟ File
   ‟ Database
„ Database Softwares
    ‟   MySQL
    ‟   MS SQL Server
    ‟   Oracle
    ‟   IBM DB2
    ‟   Sybase

                                                                      61
MySQL




        62
MySQL Installation




                     63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
Test




       81
                  SQL Command
„ Select Database  USE database_name;
„ Quit MySQL  QUIT;
„ Create table
  CREATE TABLE table_name (column_name column_type, …….., PRIMARY
  KEY(column_name,…..)) TYPE= table_type;
„ Drop table  DROP TABLE table_name;
„ Show all tables in database  SHOW TABLES;
„ Show table description  DESC table_name

                                                                82
            Retrieving and Manipulating Data
„ Retrieve Data
   SELECT column_name FROM table_name WHERE where_clause;
„ Insert Data
  INSERT INTO table_name (column_names) VALUES (values);
„ Update Data
  UPDATE table_name SET column_name = some_value WHERE
  where_clause;
„ Delete Data
   DELETE FROM table_name WHERE where_clause;               83
JAVA with Database




                     84
                              Introduction
„ We use MySQL Connector/J 5.0
„ It designed for connectivity to MySQL 4.1 and MySQL 5.0 servers
„ Distributed transaction (XA) support.




                                                                    85
                                           JDBC
„ Java Database Connectivity (JDBC) is an API (included in both J2SE and J2EE)
  that provides cross-DBMS connectivity to a wide range of SQL databases and
  access to other tabular data sources, such as spreadsheets or flat files.
„ We use JDBC-3.0 Type 4 driver, which means that is pure Java, implements
  version 3.0
„ JDBC types
    ‟   Type 1: JDBC-ODBC Bridge
    ‟   Type 2: Native-API/partly Java driver
    ‟   Type 3: Net-protocol/all-Java driver
    ‟   Type 4: Native-protocol/all-Java driver
                                                                             86
                   Type 1: JDBC-ODBC Bridge
„ JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase
  Connectivity) calls and sends them to the ODBC driver. As such, the ODBC
  driver, as well as, in many cases, the client database code, must be present on the
  client machine.




                                                                                    87
                  Type 1: JDBC-ODBC Bridge
Pros
„ The JDBC-ODBC Bridge allows access to almost any database, since the
   database's ODBC drivers are already available. Type 1 drivers may be useful for
   those companies that have an ODBC driver already installed on client machines.
Cons
„ The performance is degraded since the JDBC call goes through the bridge to the
   ODBC driver, then to the native database connectivity interface. The result
   comes back through the reverse process. Considering the performance issue, type
   1 drivers may not be suitable for large-scale applications.
„ The ODBC driver and native connectivity interface must already be installed on
   the client machine. Thus any advantage of using Java applets in an intranet
   environment is lost, since the deployment problems of traditional applications
   remain.
                                                                                 88
            Type 2: Native-API/partly Java driver
„ It converts JDBC calls into database-specific calls for databases such as SQL
  Server, Oracle, or Sybase. The type 2 driver communicates directly with the
  database server; therefore it requires that some binary code be present on the
  client machine.




                                                                                   89
            Type 2: Native-API/partly Java driver
Pros
„ Type 2 drivers typically offer significantly better performance than the JDBC-
   ODBC Bridge.
  Cons
„ The vendor database library needs to be loaded on each client machine.
  Consequently, type 2 drivers cannot be used for the Internet. Type 2 drivers show
  lower performance than type 3 and type 4 drivers.




                                                                                   90
              Type 3: Net-protocol/all-Java driver
„ It follows a three-tiered approach whereby the JDBC database requests are
  passed through the network to the middle-tier server. The middle-tier server then
  translates the request (directly or indirectly) to the database-specific native-
  connectivity interface to further the request to the database server. If the middle-
  tier server is written in Java, it can use a type 1 or type 2 JDBC driver to do this.




                                                                                      91
              Type 3: Net-protocol/all-Java driver
Pros
„ The net-protocol/all-Java driver is server-based, so there is no need for any
   vendor database library to be present on client machines. Further, there are many
   opportunities to optimize portability, performance, and scalability. Moreover, the
   net protocol can be designed to make the client JDBC driver very small and fast
   to load. Additionally, a type 3 driver typically provides support for features such
   as caching (connections, query results, and so on), load balancing, and advanced
   system administration such as logging and auditing.
Cons
„ Type 3 drivers require database-specific coding to be done in the middle tier.
   Additionally, traversing the recordset may take longer, since the data comes
   through the backend server.
                                                                                     92
           Type 4: Native-protocol/all-Java driver
„ It converts JDBC calls into the vendor-specific database management system
  (DBMS) protocol so that client applications can communicate directly with the
  database server. Level 4 drivers are completely implemented in Java to achieve
  platform independence and eliminate deployment administration issues.




                                                                                   93
           Type 4: Native-protocol/all-Java driver
Pros
„ Since type 4 JDBC drivers don't have to translate database requests to ODBC or a
   native connectivity interface or to pass the request on to another server,
   performance is typically quite good. Moreover, the native-protocol/all-Java driver
   boasts better performance than types 1 and 2. Also, there's no need to install
   special software on the client or server. Further, these drivers can be downloaded
   dynamically.
Cons
„ With type 4 drivers, the user needs a different driver for each database.



                                                                                   94
                                Installation
„ Download form www.mysql.com
„ Unzip file, use mysql-connector-java-5.0.5-bin.jar
„ How to use
   ‟ Set classpath
   ‟ Copy .jar to %JAVA_HOME%\jre\lib\ext




                                                       95
                          How to use in java
„ Driver : com.mysql.jdbc.Driver
„ URL :
  jdbc:mysql://[host:port],[host:port].../[database][?propertyName1][=propertyValu
  e1][&propertyName2][=propertyValue2]
„ Properties
   ‟ user
   ‟ password



                                                                                 96
                  How to connect Database
„ Load and register the JDBC driver classes (programming interface) for
  the database server that you intend to use.
„ Get a Connection object that represents a connection to the database
  server (analogous to logging onto the server).
„ Get one or more Statement objects for use in manipulating the
  database.
„ Use the Statement objects to manipulate the database.
„ Close the connection to the database.
                                                                     97
           Connecting to MySQL Using the DriverManager
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
      static{
               try {
                               Class.forName("com.mysql.jdbc.Driver").newInstance();
               } catch (Exception ex) {
                               // handle the error
               }
      }
      public MySQLConnection(){}
      public Connection connect(){
               Connection conn=null;
               try {
                               conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=monty&password=greatsqldb");
               } catch (SQLException ex) {
               }
               return conn;
      }
}
                                                                                                                                   98
                                      Using Statements to Execute SQL
Statement stmt = null;
ResultSet rs = null;
try {
         stmt = conn.createStatement();
         rs = stmt.executeQuery("select 1");
         if (rs.next()) {
                          System.out.println(“”+rs.getString(1));
         }
         // Now do something with the ResultSet ....
} finally {
         if (rs != null) {
                          try {
                                                rs.close();
                          } catch (SQLException sqlEx) { // ignore }
                          rs = null;
         }
         if (stmt != null) {
                          try {
                                                stmt.close();
                          } catch (SQLException sqlEx) { // ignore }
                          stmt = null;
         }
}                                                                       99
                         Workshop2
„ Create database in MySQL
„ Create Connection Bean
   ‟ Return Connection
„ Use Bean to
   ‟   Query
   ‟   Insert
   ‟   Update
   ‟   Delete
                                     100

								
To top