Docsity

JavaBeans and XML Persistence: Encapsulation and Long-Term Persistence with JSP and XML, Lecture notes of Javascript programming

Toggle sidebar
bg1
Week 7 & 8
JDBC Introduction
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database.
JDBC helps you to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query
The following simple code fragment gives a simple example of these three steps:
public void connectToAndQueryDatabase(String username, String password) {
Connection con = DriverManager.getConnection(
"jdbc:myDriver:myDatabase",
username,
password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
}
This short code fragment instantiates a DriverManager object to connect to a database driver and
log into the database, instantiates a Statement object that carries your SQL language query to the
database; instantiates a ResultSet object that retrieves the results of your query, and executes a
simple while loop, which retrieves and displays those results. It's that simple.
JDBC Product Components
JDBC includes four components:
1. The JDBC API — The JDBC™ API provides programmatic access to relational data
from the Java™ programming language. Using the JDBC API, applications can execute SQL
statements, retrieve results, and propagate changes back to an underlying data source. The JDBC
API can also interact with multiple data sources in a distributed, heterogeneous environment.
The JDBC API is part of the Java platform, which includes the Java™ Standard Edition (Java™
SE ) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two
packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE
platforms.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33

Partial preview of the text

Download JavaBeans and XML Persistence: Encapsulation and Long-Term Persistence with JSP and XML and more Lecture notes Javascript programming in PDF only on Docsity!

Week 7 & 8

JDBC Introduction

The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC helps you to write Java applications that manage these three programming activities:

  1. Connect to a data source, like a database
  2. Send queries and update statements to the database
  3. Retrieve and process the results received from the database in answer to your query The following simple code fragment gives a simple example of these three steps: public void connectToAndQueryDatabase(String username, String password) { Connection con = DriverManager.getConnection( "jdbc:myDriver:myDatabase", username, password); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1"); while (rs.next()) { int x = rs.getInt("a"); String s = rs.getString("b"); float f = rs.getFloat("c"); } } This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It's that simple. JDBC Product Components JDBC includes four components:
  4. The JDBC API — The JDBC™ API provides programmatic access to relational data from the Java™ programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment. The JDBC API is part of the Java platform, which includes the Java™ Standard Edition (Java™ SE ) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.
  1. JDBC Driver Manager — The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple. The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a connection with a data source. You can use either connecting mechanism, but using a DataSource object is recommended whenever possible.
  2. JDBC Test Suite — The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.
  3. JDBC-ODBC Bridge — The Java Software bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC driver is most appropriate on a corporate network where client installations are not a major problem, or for application server code written in Java in a three-tier architecture. This Trail uses the first two of these these four JDBC components to connect to a database and then build a java program that uses SQL commands to communicate with a test Relational Database. The last two components are used in specialized environments to test web applications, or to communicate with ODBC-aware DBMSs. JDBC Architecture Two-tier and Three-tier Processing Models The JDBC API supports both two-tier and three-tier processing models for database access. Figure 1: Two-tier Architecture for Data Access. In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet. In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.
  • performance upgraded than JDBC-ODBC bridge driver. Disadvantage:
  • The Native driver needs to be installed on the each client machine.
  • The Vendor client library needs to be installed on client machine. 3) Network Protocol driver The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. Advantage:
  • No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc. Disadvantages:
  • Network support is required on client machine.
  • Requires database-specific coding to be done in the middle tier.
  • Maintenance of Network Protocol driver becomes costly because it requires database- specific coding to be done in the middle tier. 4) Thin drive The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language. Advantage:
  • Better performance than all other drivers.
  • No software is required at client side or server side. Disadvantage:
  • Drivers depends on the Database. 5 Steps to connect to the database in java
  1. 5 Steps to connect to the database in java
  2. Register the driver class
  3. Create the connection object
  4. Create the Statement object
  5. Execute the query
  6. Close the connection object There are 5 steps to connect any java application with the database in java using JDBC. They are as follows:
  • Register the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection 1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class. Syntax of forName() method

  1. public static void forName(String className)throws ClassNotFoundException Example to register the OracleDriver class
  2. Class.forName("oracle.jdbc.driver.OracleDriver"); 2) Create the connection object The getConnection() method of DriverManager class is used to establish connection with the database. Syntax of getConnection() method
    1. public static Connection getConnection(String url)throws SQLException
    1. public static Connection getConnection(String url,String name,String password)
  3. throws SQLException Example to establish connection with the Oracle database
  4. Connection con=DriverManager.getConnection(
  5. "jdbc:oracle:thin:@localhost:1521:xe","system","password"); 3) Create the Statement object The createStatement() method of Connection interface is used to create statement. The object of statement is responsible to execute queries with the database. Syntax of createStatement() method
  6. public Statement createStatement()throws SQLException Example to create the statement object
  7. Statement stmt=con.createStatement(); 4) Execute the query The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table. Syntax of executeQuery() method
  8. public ResultSet executeQuery(String sql)throws SQLException Example to execute query
  9. ResultSet rs=stmt.executeQuery("select * from emp");
  10. while(rs.next()){
  11. System.out.println(rs.getInt(1)+" "+rs.getString(2));
  12. } 5) Close the connection object By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection. Syntax of close() method
  13. public void close()throws SQLException Example to close connection
  14. con.close();

The above example will fetch all the records of emp table. To connect java application with the Oracle database ojdbc14.jar file is required to be loaded. download the jar file ojdbc14.jar Two ways to load the jar file:

  1. paste the ojdbc14.jar file in jre/lib/ext folder
  2. set classpath
  1. paste the ojdbc14.jar file in JRE/lib/ext folder: Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
  2. set classpath: There are two ways to set the classpath:
  • temporary
  • permanent How to set the temporary classpath: Firstly, search the ojdbc14.jar file then open command prompt and write:
  1. C:>set classpath=c:\folder\ojdbc14.jar;.; How to set the permanent classpath: Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as C:\oraclexe\app oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.; To see the slides of seting parmanent path click here Example to connect to the mysql database in java For connecting java application with the mysql database, you need to follow 5 steps to perform database connectivity. In this example we are using MySql as the database. So we need to know following informations for the mysql database:
  2. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
  3. Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name. We may use any database, in such case, you need to replace the sonoo with your database name.
  4. Username: The default username for the mysql database is root.
  5. Password: Password is given by the user at the time of installing the mysql database. In this example, we are going to use root as the password. Let's first create a table in the mysql database, but before creating table, we need to create database first.
  6. create database sonoo;
  7. use sonoo;
  1. create table emp(id int(10),name varchar(40),age int(3)); Example to Connect Java Application with mysql database In this example, sonoo is the database name, root is the username and password.
  2. import java.sql.*;
  3. class MysqlCon{
  4. public static void main(String args[]){
  5. try{
  6. Class.forName("com.mysql.jdbc.Driver");
  7. Connection con=DriverManager.getConnection(
  8. "jdbc:mysql://localhost:3306/sonoo","root","root");
  9. //here sonoo is database name, root is username and password
  10. Statement stmt=con.createStatement();
  11. ResultSet rs=stmt.executeQuery("select * from emp");
  12. while(rs.next())
  13. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
  14. con.close();
  15. }catch(Exception e){ System.out.println(e);}
  16. }
  17. } download this example The above example will fetch all the records of emp table. To connect java application with the mysql database mysqlconnector.jar file is required to be loaded. download the jar file mysql-connector.jar Two ways to load the jar file:
  18. paste the mysqlconnector.jar file in jre/lib/ext folder
  19. set classpath
  1. paste the mysqlconnector.jar file in JRE/lib/ext folder: Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
  2. set classpath: There are two ways to set the classpath:
  • temporary
  • permanent How to set the temporary classpath open command prompt and write:
  1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.; How to set the permanent classpath Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;
  1. private String accountNumber = null;
  2. private String totalAmount = null;
  3. private String accountHolderName = null;
  4. private int accountHolderAge = 0;
  5. private String accountHolderAddress = null;
  6. public String getAccountNumber() {
  7. return accountNumber;
  8. }
  9. public void setAccountNumber(String accountNumber) {
  10. this.accountNumber = accountNumber;
  11. }
  12. public String getTotalAmount() {
  13. return totalAmount;
  14. }
  15. public void setTotalAmount(String totalAmount) {
  16. this.totalAmount = totalAmount;
  17. }
  18. public String getAccountHolderName() {
  19. return accountHolderName;
  20. }
  21. public void setAccountHolderName(String accountHolderName) {
  22. this.accountHolderName = accountHolderName;
  23. }
  24. public int getAccountHolderAge() {
  25. return accountHolderAge;
  26. }
  27. public void setAccountHolderAge(int accountHolderAge) {
  28. this.accountHolderAge = accountHolderAge;
  29. }
  30. public String getAccountHolderAddress() {
  31. return accountHolderAddress;
  32. }
  33. public void setAccountHolderAddress(String accountHolderAddress) {
  34. this.accountHolderAddress = accountHolderAddress;
  35. }
  36. } Advantages of JavaBeans

Following are some advantages of JavaBeans:

  • Reusability in different environments.
  • Used to create applet, servlet, application or other components.
  • JavaBeans are dynamic, can be customized.
  • Can be deployed in network systems JSP Attributes and Usage of jsp:useBean action tag
  1. id: is used to identify the bean in the specified scope.
  2. scope: represents the scope of the bean. It may be page, request, session or application. The default scope is page. o page: specifies that you can use this bean within the JSP page. The default scope is page. o request: specifies that you can use this bean from any JSP page that processes the same request. It has wider scope than page. o session: specifies that you can use this bean from any JSP page in the same session whether processes the same request or not. It has wider scope than request. o application: specifies that you can use this bean from any JSP page in the same application. It has wider scope than session.
  3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must have no-arg or no constructor and must not be abstract.
  4. type: provides the bean a data type if the bean already exists in the scope. It is mainly used with class or beanName attribute. If you use it without class or beanName, no bean is instantiated.
  5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method. Calculator.java (a simple Bean class)
  6. package new;
  7. public class Calculator{
  8. public int cube(int n){return nnn;}
  9. } index.jsp file
  10. <%
  11. int m=obj.cube(5);
  12. out.print("cube of 5 is "+m);
  13. %> jsp:setProperty and jsp:getProperty action tags
  14. jsp:setProperty and jsp:getProperty action tags
  1. Name:
  2. Password:
  3. Email:

process.jsp

  1. Record:
  2. User.java
  3. package org.sssit;
  4. public class User {
  5. private String name,password,email;
  6. //setters and getters
  7. } Reusing Bean in Multiple Jsp Pages Let's see the simple example that prints the data of bean object in two jsp pages. index.jsp Same as above. User.java Same as above. process.jsp
  8. Record:
  9. Visit Page second.jsp
  1. Record:
  2. Using variable value in setProperty tag In some case, you may get some value from the database that is to be set in the bean object, in such case, you need to use expression tag. For example: process.jsp
  3. <%
  4. String name="arjun";
  5. %>
  6. Record:
  7. Week 10 Long Term Persistence Long-term persistence is a model that enables beans to be saved in XML format. Information on the XML format and on how to implement long-term persistence for non-beans can be found in XML Schema and Using XMLEncoder. Encoder and Decoder The XMLEncoder class is assigned to write output files for textual representation of Serializable objects. The following code fragment is an example of writing a Java bean and its properties in XML format: XMLEncoder encoder = new XMLEncoder( new BufferedOutputStream( new FileOutputStream("Beanarchive.xml"))); encoder.writeObject(object); encoder.close(); The XMLDecoder class reads an XML document that was created with XMLEncoder: XMLDecoder decoder = new XMLDecoder( new BufferedInputStream( new FileInputStream("Beanarchive.xml"))); Object object = decoder.readObject(); decoder.close(); What's in XML?

true

Bean Customization Customization provides a means for modifying the appearance and behavior of a bean within an application builder so it meets your specific needs. There are several levels of customization available for a bean developer to allow other developers to get maximum benefit from a bean's potential functionality.

The following links are useful for learning about property editors and customizers:

  • PropertyEditor interface
  • PropertyEditorSupport class
  • PropertyEditorManager class
  • Customizer interface
  • BeanInfo interface

A bean's appearance and behavior can be customized at design time within beans-compliant builder tools. There are two ways to customize a bean:

  • By using a property editor. Each bean property has its own property editor. The NetBeans GUI Builder usually displays a bean's property editors in the Properties window. The property editor that is associated with a particular property type edits that property type.
  • By using customizers. Customizers give you complete GUI control over bean customization. Customizers are used where property editors are not practical or applicable. Unlike a property editor, which is associated with a property, a customizer is associated with a bean. Property Editors A property editor is a tool for customizing a particular property type. Property editors are activated in the Properties window. This window determines a property's type, searches for a relevant property editor, and displays the property's current value in a relevant way. Property editors must implement the PropertyEditor interface, which provides methods to specify how a property should be displayed in a property sheet. The following figure represents the Properties window containing myBean1 properties: You begin the process of editing these properties by clicking the property entry. Clicking most of these entries will bring up separate panels. For example, to set up the foreground or background use selection boxes with choices of colors, or press the "..." button to work with a standard ColorEditor window. Clicking on the toolTipText property opens a StringEditor window.

The support class PropertyEditorSupport provides a default implementation of the PropertyEditor interface. By subclassing your property editor from PropertyEditorSupport, you can simply override the methods you need. To display the current property value "sample" within the Properties window, you need to override isPaintable to return true. You then must override paintValue to paint the current property value in a rectangle in the property sheet. Here's how ColorEditor implements paintValue: public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) { Color oldColor = gfx.getColor(); gfx.setColor(Color.black); gfx.drawRect(box.x, box.y, box.width-3, box.height-3); gfx.setColor(color); gfx.fillRect(box.x+1, box.y+1, box.width-4, box.height-4); gfx.setColor(oldColor); } To support the custom property editor, override two more methods. Override supportsCustomEditor to return true, and then override getCustomEditor to return a custom editor instance. ColorEditor.getCustomEditor returns this. In addition, the PropertyEditorSupport class maintains a PropertyChangeListener list, and fires property change event notifications to those listeners when a bound property is changed. How Property Editors are Associated with Properties Property editors are discovered and associated with a given property in the following ways:

  • Explicit association by way of a BeanInfo object. The editor of the title's property is set with the following line of code:
  • pd.setPropertyEditorClass(TitleEditor.class);
  • Explicit registration by way of the java.beans.PropertyEditorManager.registerEditor method. This method takes two arguments: the bean class type, and the editor class to be associated with that type.
  • Name search. If a class has no explicitly associated property editor, then the PropertyEditorManager searches for that class's property editor in the following ways: o Appending "Editor" to the fully qualified class name. For example, for the my.package.ComplexNumber class, the property editor manager would search for the my.package.ComplexNumberEditor class. o Appending "Editor" to the class name and searching a class path. Customizers You have learned that builder tools provide support for you to create your own property editors. What other needs should visual builders meet for complex, industrial-strength beans? Often it is undesirable to have all the properties of a bean revealed on a single (sometimes huge) property sheet. What if one single root choice about the type of the bean rendered half the properties irrelevant? The JavaBeans specification provides for user-defined customizers, through which
  1. It reads (unmarshals) the return value or exception, and
  2. It finally, returns the value to the caller. Skeleton The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed through it. When the skeleton receives the incoming request, it does the following tasks:
  3. It reads the parameter for the remote method
  4. It invokes the method on the actual remote object, and
  5. It writes and transmits (marshals) the result to the caller. In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons. Understanding requirements for the distributed applications If any application performs these tasks, it can be distributed application. .
  6. The application need to locate the remote method
  7. It need to provide the communication with the remote objects, and
  8. The application need to load the class definitions for the objects. The RMI application have all these features, so it is called the distributed application. The is given the 6 steps to write the RMI program.
  9. Create the remote interface
  10. Provide the implementation of the remote interface
  11. Compile the implementation class and create the stub and skeleton objects using the rmic tool
  12. Start the registry service by rmiregistry tool
  13. Create and start the remote application
  14. Create and start the client application RMI Example In this example, we have followed all the 6 steps to create and run the rmi application. The client application need only two files, remote interface and client application. In the rmi application, both client and server interacts with the remote interface. The client application invokes methods on the proxy object, RMI sends the request to the remote JVM. The return value is sent back to the proxy object and then to the client application.
  1. create the remote interface For creating the remote interface, extend the Remote interface and declare the RemoteException with all the methods of the remote interface. Here, we are creating a remote interface that extends the Remote interface. There is only one method named add() and it declares RemoteException.
  1. import java.rmi.*;
  1. public interface Adder extends Remote{
  2. public int add(int x,int y)throws RemoteException;
  3. }
  1. Provide the implementation of the remote interface Now provide the implementation of the remote interface. For providing the implementation of the Remote interface, we need to
  • Either extend the UnicastRemoteObject class,
  • or use the exportObject() method of the UnicastRemoteObject class In case, you extend the UnicastRemoteObject class, you must define a constructor that declares RemoteException.
  1. import java.rmi.*;
  2. import java.rmi.server.*;
  3. public class AdderRemote extends UnicastRemoteObject implements Adder{
  4. AdderRemote()throws RemoteException{
  5. super();
  6. }
  7. public int add(int x,int y){return x+y;}
  8. }
  1. create the stub and skeleton objects using the rmic tool. Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the RMI compiler and creates stub and skeleton objects.
  1. rmic AdderRemote
  1. Start the registry service by the rmiregistry tool Now start the registry service by using the rmiregistry tool. If you don't specify the port number, it uses a default port number. In this example, we are using the port number 5000.
  1. rmiregistry 5000
  1. Create and run the server application Now rmi services need to be hosted in a server process. The Naming class provides methods to get and store the remote object. The Naming class provides 5 methods. public static java.rmi.Remote lookup(java.lang.String) throws java.rmi.NotBoundException, java.net.MalformedURLException, java.rmi.RemoteException; It returns the reference of the remote object. public static void bind(java.lang.String, java.rmi.Remote) throws java.rmi.AlreadyBoundException, java.net.MalformedURLException, java.rmi.RemoteException; It binds the remote object with the given name.