Introduction to JDBC
Introduction to JDBC
ANUDIP FOUNDATION
LESSON-1 Java Enterprise Edition
Introduction to JDBC
Theory:240mins Pratical:120mins
1
LESSON-1 Java Enterprise Edition
Introduction to JDBC
Introduction to JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with
the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect
with the database. There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
We have discussed the above four drivers in the next chapter.
We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API,
we can save, update, delete and fetch data from the database. It is like Open Database Connectivity
(ODBC) provided by Microsoft.
2
LESSON-1 Java Enterprise Edition
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on
the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC
API. A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API are given below:
o DriverManager class
o Blob class
o Clob class
o Types class
Why Should We Use JDBC
Before JDBC, ODBC API was the database API to connect and execute the query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured).
That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
Connection interface
A Connection is the session between java application and database. The Connection interface is a
factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used
to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods
for transaction management like commit(), rollback() etc.
3
LESSON-1 Java Enterprise Edition
Statement interface
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT
query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it
may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may
return multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized
query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter
methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
4
LESSON-1 Java Enterprise Edition
Method Description
5
LESSON-1 Java Enterprise Edition
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
6
LESSON-1 Java Enterprise Edition
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before
the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well
as we can make this object as updatable by:
1. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
1) public boolean next(): is used to move the cursor to the one row next
from the current position.
3) public boolean first(): is used to move the cursor to the first row in
result set object.
4) public boolean last(): is used to move the cursor to the last row in
result set object.
7
LESSON-1 Java Enterprise Edition
Self learning with online links and explanation by Trainer with Demos
1. https://docs.oracle.com/javase/tutorial/jdbc/overview/index.html
2. https://www.javatpoint.com/ResultSet-interface
3. https://www.geeksforgeeks.org/introduction-to-jdbc/
4. https://www.tutorialspoint.com/jdbc/jdbc-introduction.htm
5. J2EE Design Patterns
6. Core J2EE Patterns: Best Practices and Design Strategies
7. http://www.corej2eepatterns.com
8
LESSON-1 Java Enterprise Edition
o Factory Method Pattern allows the sub-classes to choose the type of objects to create.
o It promotes the loose-coupling by eliminating the need to bind application-specific classes into
the code. That means the code interacts solely with the resultant interface or abstract class, so
that it will work with any classes that implement that interface or that extends that abstract
class.
o We are going to create a Plan abstract class and concrete classes that extends the Plan abstract
class. A factory class GetPlanFactory is defined as a next step.
o GenerateBill class will use GetPlanFactory to get a Plan object. It will pass information
(DOMESTICPLAN / COMMERCIALPLAN / INSTITUTIONALPLAN) to GetPalnFactory to get the type
of object it needs.
9
LESSON-1 Java Enterprise Edition
10
LESSON-1 Java Enterprise Edition
Step 3: Create a GetPlanFactory to generate object of concrete classes based on given information..
1. class GetPlanFactory{
2.
3. //use getPlan method to get object of type Plan
4. public Plan getPlan(String planType){
5. if(planType == null){
6. return null;
7. }
8. if(planType.equalsIgnoreCase("DOMESTICPLAN")) {
9. return new DomesticPlan();
10. }
11. else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){
12. return new CommercialPlan();
13. }
14. else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {
15. return new InstitutionalPlan();
16. }
17. return null;
18. }
19. }//end of GetPlanFactory class.
Step 4: Generate Bill by using the GetPlanFactory to get the object of concrete classes by passing an
information such as type of plan DOMESTICPLAN or COMMERCIALPLAN or INSTITUTIONALPLAN.
1. import java.io.*;
2. class GenerateBill{
3. public static void main(String args[])throws IOException{
4. GetPlanFactory planFactory = new GetPlanFactory();
5.
6. System.out.print("Enter the name of plan for which the bill will be generated: ");
7. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
8.
9. String planName=br.readLine();
10. System.out.print("Enter the number of units for bill will be calculated: ");
11. int units=Integer.parseInt(br.readLine());
12.
13. Plan p = planFactory.getPlan(planName);
14. //call getRate() method and calculateBill()method of DomesticPaln.
15.
16. System.out.print("Bill amount for "+planName+" of "+units+" units is: ");
17. p.getRate();
18. p.calculateBill(units);
19. }
20. }//end of GenerateBill class.
Output
11
LESSON-1 Java Enterprise Edition
o Abstract Factory Pattern isolates the client code from concrete (implementation) classes.
o It eases the exchanging of object families.
o It promotes consistency among objects.
o When the system needs to be independent of how its object are created, composed, and
represented.
o When the family of related objects has to be used together, then this constraint needs to be
enforced.
o When you want to provide a library of objects that does not show implementations and only
reveals interfaces.
o When the system needs to be configured with one of a multiple family of objects.
12
LESSON-1 Java Enterprise Edition
13
LESSON-1 Java Enterprise Edition
9. }
1. class ICICI implements Bank{
2. private final String BNAME;
3. ICICI(){
4. BNAME="ICICI BANK";
5. }
6. public String getBankName() {
7. return BNAME;
8. }
9. }
1. class SBI implements Bank{
2. private final String BNAME;
3. public SBI(){
4. BNAME="SBI BANK";
5. }
6. public String getBankName(){
7. return BNAME;
8. }
9. }
Step 3: Create the Loan abstract class.
1. abstract class Loan{
2. protected double rate;
3. abstract void getInterestRate(double rate);
4. public void calculateLoanPayment(double loanamount, int years)
5. {
6. /*
7. to calculate the monthly loan payment i.e. EMI
8.
9. rate=annual interest rate/12*100;
10. n=number of monthly installments;
11. 1year=12 months.
12. so, n=years*12;
13.
14. */
15.
16. double EMI;
17. int n;
18.
19. n=years*12;
20. rate=rate/1200;
21. EMI=((rate*Math.pow((1+rate),n))/((Math.pow((1+rate),n))-1))*loanamount;
22.
23. System.out.println("your monthly EMI is "+ EMI +" for the amount"+loanamount+" you have bo
rrowed");
24. }
25. }// end of the Loan abstract class.
Step 4: Create concrete classes that extend the Loan abstract class..
1. class HomeLoan extends Loan{
2. public void getInterestRate(double r){
3. rate=r;
4. }
14
LESSON-1 Java Enterprise Edition
15
LESSON-1 Java Enterprise Edition
12.
13. String loanName=br.readLine();
14. AbstractFactory bankFactory = FactoryCreator.getFactory("Bank");
15. Bank b=bankFactory.getBank(bankName);
16.
17. System.out.print("\n");
18. System.out.print("Enter the interest rate for "+b.getBankName()+ ": ");
19.
20. double rate=Double.parseDouble(br.readLine());
21. System.out.print("\n");
22. System.out.print("Enter the loan amount you want to take: ");
23.
24. double loanAmount=Double.parseDouble(br.readLine());
25. System.out.print("\n");
26. System.out.print("Enter the number of years to pay your entire loan amount: ");
27. int years=Integer.parseInt(br.readLine());
28.
29. System.out.print("\n");
30. System.out.println("you are taking the loan from "+ b.getBankName());
16
LESSON-1 Java Enterprise Edition
31.
32. AbstractFactory loanFactory = FactoryCreator.getFactory("Loan");
33. Loan l=loanFactory.getLoan(loanName);
34. l.getInterestRate(rate);
35. l.calculateLoanPayment(loanAmount,years);
36. }
37. }//End of the AbstractFactoryPatternExample
Output
o Saves memory because object is not created at each request. Only single instance is reused
again and again.
17
LESSON-1 Java Enterprise Edition
To create the singleton class, we need to have static member of class, private constructor and static
factory method.
o Static member: It gets memory only once because of static, itcontains the instance of the
Singleton class.
o Private constructor: It will prevent to instantiate the Singleton class from outside the class.
o Static factory method: This provides the global point of access to the Singleton object and
returns the instance to the caller.
18
LESSON-1 Java Enterprise Edition
6. return obj;
7. }
8.
9. public void doSomething(){
10. //write your code
11. }
12. }
If singleton class is loaded by two classloaders, two instance of singleton class will be
created, one for each classloader.
19
LESSON-1 Java Enterprise Edition
Assumption: you have created a table userdata that has three fields uid, uname and upassword in
mysql database. Database name is ashwinirajput, username is root, password is ashwini.
File: JDBCSingleton.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
20
LESSON-1 Java Enterprise Edition
3. import java.io.InputStreamReader;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.PreparedStatement;
7. import java.sql.ResultSet;
8. import java.sql.SQLException;
9.
10. class JDBCSingleton {
11. //Step 1
12. // create a JDBCSingleton class.
13. //static member holds only one instance of the JDBCSingleton class.
14.
15. private static JDBCSingleton jdbc;
16.
17. //JDBCSingleton prevents the instantiation from any other class.
18. private JDBCSingleton() { }
19.
20. //Now we are providing gloabal point of access.
21. public static JDBCSingleton getInstance() {
22. if (jdbc==null)
23. {
24. jdbc=new JDBCSingleton();
25. }
26. return jdbc;
27. }
28.
29. // to get the connection from methods like insert, view etc.
30. private static Connection getConnection()throws ClassNotFoundException, SQLException
31. {
32.
33. Connection con=null;
34. Class.forName("com.mysql.jdbc.Driver");
35. con= DriverManager.getConnection("jdbc:mysql://localhost:3306/ashwanirajput", "roo
t", "ashwani");
36. return con;
37.
38. }
39.
40. //to insert the record into the database
41. public int insert(String name, String pass) throws SQLException
42. {
43. Connection c=null;
44.
45. PreparedStatement ps=null;
46.
47. int recordCounter=0;
48.
49. try {
50.
51. c=this.getConnection();
52. ps=c.prepareStatement("insert into userdata(uname,upassword)values(?,?)");
21
LESSON-1 Java Enterprise Edition
22
LESSON-1 Java Enterprise Edition
103. try {
104. c=this.getConnection();
105. ps=c.prepareStatement(" update userdata set upassword=? where uname
='"+name+"' ");
106. ps.setString(1, password);
107. recordCounter=ps.executeUpdate();
108. } catch (Exception e) { e.printStackTrace(); } finally{
109.
110. if (ps!=null){
111. ps.close();
112. }if(c!=null){
113. c.close();
114. }
115. }
116. return recordCounter;
117. }
118.
119. // to delete the data from the database
120. public int delete(int userid) throws SQLException{
121. Connection c=null;
122. PreparedStatement ps=null;
123. int recordCounter=0;
124. try {
125. c=this.getConnection();
126. ps=c.prepareStatement(" delete from userdata where uid='"+userid+"' ")
;
127. recordCounter=ps.executeUpdate();
128. } catch (Exception e) { e.printStackTrace(); }
129. finally{
130. if (ps!=null){
131. ps.close();
132. }if(c!=null){
133. c.close();
134. }
135. }
136. return recordCounter;
137. }
138. }// End of JDBCSingleton class
File: JDBCSingletonDemo.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.PreparedStatement;
7. import java.sql.ResultSet;
8. import java.sql.SQLException;
9. class JDBCSingletonDemo{
10. static int count=1;
11. static int choice;
12. public static void main(String[] args) throws IOException {
23
LESSON-1 Java Enterprise Edition
13.
14. JDBCSingleton jdbc= JDBCSingleton.getInstance();
15.
16.
17. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
18. do{
19. System.out.println("DATABASE OPERATIONS");
20. System.out.println(" --------------------- ");
21. System.out.println(" 1. Insertion ");
22. System.out.println(" 2. View ");
23. System.out.println(" 3. Delete ");
24. System.out.println(" 4. Update ");
25. System.out.println(" 5. Exit ");
26.
27. System.out.print("\n");
28. System.out.print("Please enter the choice what you want to perform in the database: ");
29.
30. choice=Integer.parseInt(br.readLine());
31. switch(choice) {
32.
33. case 1:{
34. System.out.print("Enter the username you want to insert data into the database: "
);
35. String username=br.readLine();
36. System.out.print("Enter the password you want to insert data into the database: "
);
37. String password=br.readLine();
38.
39. try {
40. int i= jdbc.insert(username, password);
41. if (i>0) {
42. System.out.println((count++) + " Data has been inserted successfully");
43. }else{
44. System.out.println("Data has not been inserted ");
45. }
46.
47. } catch (Exception e) {
48. System.out.println(e);
49. }
50.
51. System.out.println("Press Enter key to continue...");
52. System.in.read();
53.
54. }//End of case 1
55. break;
56. case 2:{
57. System.out.print("Enter the username : ");
58. String username=br.readLine();
59.
60. try {
61. jdbc.view(username);
24
LESSON-1 Java Enterprise Edition
25
LESSON-1 Java Enterprise Edition
113. }
114.
115. } while (choice!=4);
116. }
117. }
Output
26
LESSON-1 Java Enterprise Edition
27
LESSON-1 Java Enterprise Edition
28
LESSON-1 Java Enterprise Edition
29
LESSON-1 Java Enterprise Edition
4.
5. }//End of Prototype interface.
File: EmployeeRecord.java
1. class EmployeeRecord implements Prototype{
2.
3. private int id;
4. private String name, designation;
5. private double salary;
6. private String address;
7.
8. public EmployeeRecord(){
9. System.out.println(" Employee Records of Oracle Corporation ");
10. System.out.println("---------------------------------------------");
11. System.out.println("Eid"+"\t"+"Ename"+"\t"+"Edesignation"+"\t"+"Esalary"+"\t\t"+"Ea
ddress");
12.
13. }
14.
15. public EmployeeRecord(int id, String name, String designation, double salary, String address) {
16.
17. this();
18. this.id = id;
19. this.name = name;
20. this.designation = designation;
21. this.salary = salary;
22. this.address = address;
23. }
24.
25. public void showRecord(){
26.
27. System.out.println(id+"\t"+name+"\t"+designation+"\t"+salary+"\t"+address);
28. }
29.
30. @Override
31. public Prototype getClone() {
32.
33. return new EmployeeRecord(id,name,designation,salary,address);
34. }
35. }//End of EmployeeRecord class.
File: PrototypeDemo.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4.
5. class PrototypeDemo{
6. public static void main(String[] args) throws IOException {
7.
8. BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
9. System.out.print("Enter Employee Id: ");
10. int eid=Integer.parseInt(br.readLine());
30
LESSON-1 Java Enterprise Edition
11. System.out.print("\n");
12.
13. System.out.print("Enter Employee Name: ");
14. String ename=br.readLine();
15. System.out.print("\n");
16.
17. System.out.print("Enter Employee Designation: ");
18. String edesignation=br.readLine();
19. System.out.print("\n");
20.
21. System.out.print("Enter Employee Address: ");
22. String eaddress=br.readLine();
23. System.out.print("\n");
24.
25. System.out.print("Enter Employee Salary: ");
26. double esalary= Double.parseDouble(br.readLine());
27. System.out.print("\n");
28.
29. EmployeeRecord e1=new EmployeeRecord(eid,ename,edesignation,esalary,eaddress);
30.
31. e1.showRecord();
32. System.out.println("\n");
33. EmployeeRecord e2=(EmployeeRecord) e1.getClone();
34. e2.showRecord();
35. }
36. }//End of the ProtoypeDemo class.
Output
31
LESSON-1 Java Enterprise Edition
32
LESSON-1 Java Enterprise Edition
§ Decorator Pattern
§ Facade Pattern
Decorator Pattern
1. Decorator Design Pattern
2. Advantage of Decorator DP
3. Usage of Decorator DP
4. UML of Decorator DP
5. Example of Decorator DP
A Decorator Pattern says that just "attach a flexible additional responsibilities to an object
dynamically".
In other words, The Decorator Pattern uses composition instead of inheritance to extend the
functionality of an object at runtime.
The Decorator Pattern is also known as Wrapper.
It is used:
33
LESSON-1 Java Enterprise Edition
o When you want to transparently and dynamically add responsibilities to objects without affecting
other objects.
o When you want to add responsibilities to an object that you may want to change in future.
o Extending functionality by sub-classing is no longer practical.
34
LESSON-1 Java Enterprise Edition
7. return 50.0;
8. }
9. }
Step 3:Create a FoodDecorator abstract class that will implements the Food interface and override it's
all methods and it has the ability to decorate some more foods.
File: FoodDecorator.java
1. public abstract class FoodDecorator implements Food{
2. private Food newFood;
3. public FoodDecorator(Food newFood) {
4. this.newFood=newFood;
5. }
6. @Override
7. public String prepareFood(){
8. return newFood.prepareFood();
9. }
10. public double foodPrice(){
11. return newFood.foodPrice();
12. }
13. }
Step 4:Create a NonVegFood concrete class that will extend the FoodDecorator class and override
it's all methods.
File: NonVegFood.java
1. public class NonVegFood extends FoodDecorator{
2. public NonVegFood(Food newFood) {
3. super(newFood);
4. }
5. public String prepareFood(){
6. return super.prepareFood() +" With Roasted Chiken and Chiken Curry ";
7. }
8. public double foodPrice() {
9. return super.foodPrice()+150.0;
10. }
11. }
Step 5:Create a ChineeseFood concrete class that will extend the FoodDecorator class and override
it's all methods.
File: ChineeseFood.java
1. public class ChineeseFood extends FoodDecorator{
2. public ChineeseFood(Food newFood) {
3. super(newFood);
4. }
5. public String prepareFood(){
6. return super.prepareFood() +" With Fried Rice and Manchurian ";
7. }
8. public double foodPrice() {
9. return super.foodPrice()+65.0;
10. }
11. }
Step 6:Create a DecoratorPatternCustomer class that will use Food interface to use which type of
food customer wants means (Decorates).
File: DecoratorPatternCustomer.java
1. import java.io.BufferedReader;
35
LESSON-1 Java Enterprise Edition
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. public class DecoratorPatternCustomer {
5. private static int choice;
6. public static void main(String args[]) throws NumberFormatException, IOException {
7. do{
8. System.out.print("========= Food Menu ============ \n");
9. System.out.print(" 1. Vegetarian Food. \n");
10. System.out.print(" 2. Non-Vegetarian Food.\n");
11. System.out.print(" 3. Chineese Food. \n");
12. System.out.print(" 4. Exit \n");
13. System.out.print("Enter your choice: ");
14. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
15. choice=Integer.parseInt(br.readLine());
16. switch (choice) {
17. case 1:{
18. VegFood vf=new VegFood();
19. System.out.println(vf.prepareFood());
20. System.out.println( vf.foodPrice());
21. }
22. break;
23.
24. case 2:{
25. Food f1=new NonVegFood((Food) new VegFood());
26. System.out.println(f1.prepareFood());
27. System.out.println( f1.foodPrice());
28. }
29. break;
30. case 3:{
31. Food f2=new ChineeseFood((Food) new VegFood());
32. System.out.println(f2.prepareFood());
33. System.out.println( f2.foodPrice());
34. }
35. break;
36.
37. default:{
38. System.out.println("Other than these no food available");
39. }
40. return;
41. }//end of switch
42.
43. }while(choice!=4);
44. }
45. }
Output
36
LESSON-1 Java Enterprise Edition
5. 4. Exit
6. Enter your choice: 1
7. Veg Food
8. 50.0
9. ========= Food Menu ============
10. 1. Vegetarian Food.
11. 2. Non-Vegetarian Food.
12. 3. Chineese Food.
13. 4. Exit
14. Enter your choice: 2
15. Veg Food With Roasted Chiken and Chiken Curry
16. 200.0
17. ========= Food Menu ============
18. 1. Vegetarian Food.
19. 2. Non-Vegetarian Food.
20. 3. Chineese Food.
21. 4. Exit
22. Enter your choice: 3
23. Veg Food With Fried Rice and Manchurian
24. 115.0
25. ========= Food Menu ============
26. 1. Vegetarian Food.
27. 2. Non-Vegetarian Food.
28. 3. Chineese Food.
29. 4. Exit
30. Enter your choice: 4
31. Other than these no food available
Next →← Prev
Facade Pattern
1. Facade Design Pattern
2. Advantage of Facade DP
3. Usage of Facade DP
4. UML of Facade DP
5. Example of Facade DP
A Facade Pattern says that just "just provide a unified and simplified interface to a set of
interfaces in a subsystem, therefore it hides the complexities of the subsystem from the
client".
In other words, Facade Pattern describes a higher-level interface that makes the sub-system easier
to use.
Practically, every Abstract Factory is a type of Facade.
37
LESSON-1 Java Enterprise Edition
It is used:
o When you want to provide simple interface to a complex sub-system.
o When several dependencies exist between clients and the implementation classes of an
abstraction.
Step 2
38
LESSON-1 Java Enterprise Edition
9. }
10. }
Step 3
Step 4
Step 5
39
LESSON-1 Java Enterprise Edition
14. }
15. public void samsungSale(){
16. samsung.modelNo();
17. samsung.price();
18. }
19. public void blackberrySale(){
20. blackberry.modelNo();
21. blackberry.price();
22. }
23. }
Step 6
Now, Creating a client that can purchase the mobiles from MobileShop through ShopKeeper.
File: FacadePatternClient.java
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4.
5. public class FacadePatternClient {
6. private static int choice;
7. public static void main(String args[]) throws NumberFormatException, IOException{
8. do{
9. System.out.print("========= Mobile Shop ============ \n");
10. System.out.print(" 1. IPHONE. \n");
11. System.out.print(" 2. SAMSUNG. \n");
12. System.out.print(" 3. BLACKBERRY. \n");
13. System.out.print(" 4. Exit. \n");
14. System.out.print("Enter your choice: ");
15.
16. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
17. choice=Integer.parseInt(br.readLine());
18. ShopKeeper sk=new ShopKeeper();
19.
20. switch (choice) {
21. case 1:
22. {
23. sk.iphoneSale();
24. }
25. break;
26. case 2:
27. {
28. sk.samsungSale();
29. }
30. break;
31. case 3:
32. {
33. sk.blackberrySale();
34. }
35. break;
36. default:
40
LESSON-1 Java Enterprise Edition
37. {
38. System.out.println("Nothing You purchased");
39. }
40. return;
41. }
42.
43. }while(choice!=4);
44. }
45. }
Output
41
LESSON-1 Java Enterprise Edition
It is used:
o When more than one object can handle a request and the handler is unknown.
o When the group of objects that can handle the request must be specified in dynamic way.
42
LESSON-1 Java Enterprise Edition
43
LESSON-1 Java Enterprise Edition
Step 2
Step 3
Step 4
Step 5
44
LESSON-1 Java Enterprise Edition
Output
1. bilityClient
2. CONSOLE LOGGER INFO: Enter the sequence of values
3. CONSOLE LOGGER INFO: An error is occured now
4. ERROR LOGGER INFO: An error is occured now
5. CONSOLE LOGGER INFO: This was the error now debugging is compeled
6. ERROR LOGGER INFO: This was the error now debugging is compeled
7. DEBUG LOGGER INFO: This was the error now debugging is compeled
Iterator Pattern
1. Iterator Design Pattern
2. Advantage of Iterator DP
3. Usage of Iterator DP
4. UML of Iterator DP
5. Example of Iterator DP
According to GoF, Iterator Pattern is used "to access the elements of an aggregate object
sequentially without exposing its underlying implementation".
The Iterator pattern is also known as Cursor.
In collection framework, we are now using Iterator that is preferred over Enumeration.
It is used:
45
LESSON-1 Java Enterprise Edition
o When you want to access a collection of objects without exposing its internal representation.
o When there are multiple traversals of objects need to be supported in the collection.
Step 2
46
LESSON-1 Java Enterprise Edition
Step 3
Step 4
47
LESSON-1 Java Enterprise Edition
Output
Usage:
o When you want centralization, common processing across requests, such as logging information
about each request, compressing an outgoing response or checking the data encoding scheme of
each request.
o When you want pre and post processing the components which are loosely coupled with core
request-handling services to facilitate which are not suitable for addition and removal.
Benefits:
48
LESSON-1 Java Enterprise Edition
Step 1
Create a Login.html web page.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="US-ASCII">
5. <title>Login Page</title>
6. </head>
7. <body>
8.
9. <form action="LoginServlet" method="post">
10.
11. Username: <input type="text" name="username">
12. <br><br>
13. Password: <input type="password" name="password">
14. <br><br>
15. <input type="submit" value="Login">
16.
17. </form>
18. </body>
Step 2
Create a LoginServlet class.
1. package sessions;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5.
6. import javax.servlet.RequestDispatcher;
49
LESSON-1 Java Enterprise Edition
7. import javax.servlet.ServletException;
8. import javax.servlet.annotation.WebServlet;
9. import javax.servlet.http.Cookie;
10. import javax.servlet.http.HttpServlet;
11. import javax.servlet.http.HttpServletRequest;
12. import javax.servlet.http.HttpServletResponse;
13. import javax.servlet.http.HttpSession;
14. **
15. * Servlet implementation class LoginServlet
16. */
17. @WebServlet("/LoginServlet")
18. public class LoginServlet extends HttpServlet {
19. private static final long serialVersionUID = 1L;
20. private final String user = "admin";
21. private final String password = "admin@1234";
22.
23. public LoginServlet() {
24. super();
25. }
26. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Servl
etException, IOException {
27.
28. // get request parameters for username and passwd
29. String username = request.getParameter("username");
30. String passwd = request.getParameter("password");
31.
32. if(user.equals(username) && password.equals(passwd)){
33. HttpSession session = request.getSession();
34. session.setAttribute("user", "ashwani");
35.
36. //setting session to expire in 1 hour
37. session.setMaxInactiveInterval(60*60);
38.
39. Cookie userName = new Cookie("user", user);
40. userName.setMaxAge(60*60);
41. response.addCookie(userName);
42. response.sendRedirect("LoginSuccess.jsp");
43. }else{
44. RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login.html");
45. PrintWriter out= response.getWriter();
46. out.println("<font color=red>Either user name or password is wrong.</font>");
47. rd.include(request, response);
48. }
49. }
50. }//End of the LoginServlet class.
Step 3
Create a LoginSuccess.jsp page.
1. <%@ page language="java" contentType="text/html; charset=US-ASCII"
2. pageEncoding="US-ASCII"%>
3. <!DOCTYPE html PUBLIC "-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
50
LESSON-1 Java Enterprise Edition
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
7. <title>Login Success Page</title>
8. </head>
9. <body>
10. <%
11. //allow access only if session exists
12. String user = (String) session.getAttribute("user");
13. String userName = null;
14. String sessionID = null;
15. Cookie[] cookies = request.getCookies();
16. if(cookies !=null){
17. for(Cookie cookie : cookies){
18. if(cookie.getName().equals("user")) userName = cookie.getValue();
19. if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
20. }
21. }
22. %>
23. <h3>Hi <%=userName %>, Login successful.Your Session ID=<%=sessionID %></h3>
24. <br>
25. User=<%=user %>
26. <br>
27. <a href="CheckoutPage.jsp">Checkout Page</a><br>
28. <form action="LogoutServlet" method="post">
29. <input type="submit" value="Logout" >
30. </form>
31. </body>
32. </html>
Step 4
Create an AdminPage.jsp page.
1. <%@ page language="java" contentType="text/html; charset=US-ASCII"
2. pageEncoding="US-ASCII"%>
3. <!DOCTYPE html PUBLIC "-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
7. <title>Login Success Page</title>
8. </head>
9. <body>
10. <%
11. String userName = null;
12. String sessionID = null;
13. Cookie[] cookies = request.getCookies();
14. if(cookies !=null){
15. for(Cookie cookie : cookies){
16. if(cookie.getName().equals("user")) userName = cookie.getValue();
17. }
18. }
19. %>
51
LESSON-1 Java Enterprise Edition
20. <h3>Hi <%=userName %>, These services are only for you to take action.</h3>
21. <br>
22. <form action="LogoutServlet" method="post">
23. <input type="submit" value="Logout" >
24. </form>
25. </body>
26. </html>
Step 5
Create an LogoutServlet class.
1. package sessions;
2.
3. import java.io.IOException;
4.
5. import javax.servlet.ServletException;
6. import javax.servlet.annotation.WebServlet;
7. import javax.servlet.http.Cookie;
8. import javax.servlet.http.HttpServlet;
9. import javax.servlet.http.HttpServletRequest;
10. import javax.servlet.http.HttpServletResponse;
11. import javax.servlet.http.HttpSession;
12.
13. /**
14. * Servlet implementation class LogoutServlet
15. */
16. @WebServlet("/LogoutServlet")
17. public class LogoutServlet extends HttpServlet {
18. private static final long serialVersionUID = 1L;
19.
20. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Se
rvletException, IOException {
21. response.setContentType("text/html");
22. Cookie[] cookies = request.getCookies();
23. if(cookies != null){
24. for(Cookie cookie : cookies){
25. if(cookie.getName().equals("JSESSIONID")){
26. System.out.println("JSESSIONID="+cookie.getValue());
27. break;
28. }
29. }
30. }
31. //invalidate the session if exists
32. HttpSession session = request.getSession(false);
33. System.out.println("User="+session.getAttribute("user"));
34. if(session != null){
35. session.invalidate();
36. }
37. response.sendRedirect("Login.html");
38. }
39.
40. }//End of the LogoutServlet class
Step 6
52
LESSON-1 Java Enterprise Edition
53
LESSON-1 Java Enterprise Edition
54
LESSON-1 Java Enterprise Edition
55
LESSON-1 Java Enterprise Edition
56
LESSON-1 Java Enterprise Edition
Next →← Prev
Front Controller Pattern
A Front Controller Pattern says that if you want to provide the centralized request handling
mechanism so that all the requests will be handled by a single handler". This handler can do the
authentication or authorization or logging or tracking of request and then pass the requests to
corresponding handlers.
Usage:
57
LESSON-1 Java Enterprise Edition
Benefits:
o It reduces the duplication of code in JSP pages, especially in those cases where several
resources require the same processing.
o It maintains and controls a web application more effectively.
o A web application of two-tier architecture, the recommended approach is front controller to
deal with user requests.
Step 1
Create a Login.html web page.
1. <html>
2. <head>
3. <title>
4. Login page
5. </title>
6. </head>
7. <body style="color:green;">
8. <h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
9. color:#00FF00;>
58
LESSON-1 Java Enterprise Edition
59
LESSON-1 Java Enterprise Edition
60. form.pwd1.focus();
61. return false;
62. }
63. } else {
64. alert("Error: Please check that you've entered and confirmed your password!");
65. form.pwd1.focus();
66. return false;
67. }
68. return true;
69. }
70.
71. </script>
72. </body>
73. </html>
Step 2
Create a FrontControllerServlet.java class which is a servlet and it may be a JSP page also.
1. package controller;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5.
6. import javax.servlet.RequestDispatcher;
7. import javax.servlet.ServletException;
8. import javax.servlet.annotation.WebServlet;
9. import javax.servlet.http.HttpServlet;
10. import javax.servlet.http.HttpServletRequest;
11. import javax.servlet.http.HttpServletResponse;
12.
13. /**
14. * Servlet implementation class FrontControllerServlet
15. */
16. @WebServlet("/FrontControllerServlet")
17. public class FrontControllerServlet extends HttpServlet {
18.
19. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
20.
21. response.setContentType("text/html");
22. PrintWriter out = response.getWriter();
23.
24. String username=request.getParameter("username");
25. String password=request.getParameter("pwd2");
26.
27. if (password.equals("Ashwani1987")) {
28.
29. RequestDispatcher rd=request.getRequestDispatcher("/Success.jsp");
30. rd.forward(request, response);
31. } else {
32.
33. RequestDispatcher rd=request.getRequestDispatcher("/Error.jsp");
34. rd.forward(request, response);
60
LESSON-1 Java Enterprise Edition
35. }
36.
37. }
38.
39. }
Step 3
Create a Success.jsp page.
1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Welcome Page</title>
8. </head>
9. <body style="background-color: gray;">
10.
11. <% String name=request.getParameter("username"); %>
12.
13. <b>Welcome,</b> <% out.print(name); %>
14.
15. </body>
16. </html>
Step 4
Create a Error.jsp page.
1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Insert title here</title>
8. </head>
9. <body style="background-color: olive;">
10.
11. <b>You are have entered wrong username or password!!</b><br>
12.
13. <a href="Login.html">Back To Home Page</a>
14. </body>
15. </html>
Step 5
Create a web.xml file.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.
com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
3. <display-name>Front Controller Example</display-name>
4. <welcome-file-list>
5. <welcome-file>Login.html</welcome-file>
61
LESSON-1 Java Enterprise Edition
6. </welcome-file-list>
7. </web-app>
Output:
62
LESSON-1 Java Enterprise Edition
63
LESSON-1 Java Enterprise Edition
Session Beans
64
LESSON-1 Java Enterprise Edition
Session beans encapsulate the business processes and rules logic. For example, a session bean could
calculate taxes for a billing invoice. When there are complex business rules that change frequently (for
example, due to new business practices or new government regulations), an application typically uses
more session beans than entity beans, and session beans may need continual revision.
Session beans are likely to call a full range of JDBC interfaces, as well as other EJB components.
Applications perform better when session beans are stateless, although session beans can be stateful. A
stateful session bean is needed when a user-specific state, such as a shopping cart, must be
maintained on the server.
Entity Beans
Entity beans represent persistent objects, such as a database row. Entity beans are likely to call a full
range of JDBC interfaces. However, entity beans typically do not call other EJB components. The entity
bean developer’s role is to design an object-oriented view of an organization’s business data. Creating
this object-oriented view often means mapping database tables into entity beans. For example, the
developer might translate a customer table, invoice table, and order table into corresponding customer,
invoice, and order objects.
An entity bean developer works with session bean and servlet developers to ensure that the application
provides fast, scalable access to persistent business data.
There are two types of entity bean persistence:
Container managed persistence (CMP) - The EJB container is responsible for maintaining the
interactions between the business logic and the database.
Bean managed persistence (BMP) - The developer is responsible for writing the code that
controls interaction with the database.
Message-Driven Beans
Message-driven beans are persistent objects that are likely to call a full range of JDBC interfaces, much
like entity beans. However, message-driven beans have no local or remote interfaces as do other EJB
components, and they differ from entity beans in how they are accessed.
A message-driven bean is a message listener that can reliably consume messages from a queue or a
durable subscription. The messages may be sent by any J2EE component—from an application client,
another EJB component, or a Web component—or from an application or a system that does not use
J2EE technology.
For example, an inventory entity bean may send a message to a stock ordering message-driven bean
when the amount of an item is below a set lower limit.
The Data Access Layer
In the data access layer, JDBC (Java database connectivity) is used to connect to databases, make
queries, and return query results, and custom connectors work with the Sun Java System Application
Server to enable communication with legacy EIS systems, such as IBM’s CICS.
Developers are likely to integrate access to the following systems using J2EE CA (connector
architecture):
Enterprise resource management systems
Mainframe systems
Third-party security systems
For more information about JDBC, see the Sun Java System Application Server Developer’s Guide to
J2EE Services and APIs.
For more information about connectors, see the Sun Java System J2EE CA Service Provider
Implementation Administrator’s Guide and the corresponding release notes.
65
LESSON-1 Java Enterprise Edition
This section lists guidelines to consider when designing and developing an Sun Java System Application
Server application, and is merely a summary. For more details, you may want to consult Core J2EE
Patterns: Best Practices and Design Strategies by Deepak Alur, John Crupi, and Dan Malks.
The guidelines are grouped into the following goals:
Presenting Data with Servlets and JSPs
Creating Reusable Application Code
Modularizing Applications
Presenting Data with Servlets and JSPs
Servlets are often used for presentation logic and serve as central dispatchers of user input and data
presentation. JSPs are used to dynamically generate the presentation layout. Both servlets and JSPs
can be used to conditionally generate different pages.
If the page layout is its main feature and there is minimal processing involved to generate the page, it
may be easier to use a JSP for the interaction.
For example, after an online bookstore application authenticates a user, it provides a boilerplate portal
front page for the user to choose one of several tasks, including a book search, purchase selected
items, and so on. Since this portal conducts very little processing, it can be implemented as a JSP.
Think of JSPs and servlets as opposite sides of the same coin. Each can perform all the tasks of the
other, but each is designed to excel at one task at the expense of the other. The strength of servlets is
in processing and adaptability. However, performing HTML output from them involves many
cumbersome println statements. Conversely, JSPs excel at layout tasks because they are simply HTML
files and can be edited with HTML editors, though performing complex computational or processing
tasks with them can be awkward. You can use JSPs and servlets together to get the benefits of both.
For more information on servlets and JSPs, see the Sun Java System Application Server Developer’s
Guide to Web Applications.
Creating Reusable Application Code
Aside from using good object-oriented design principles, there are several things to consider when
developing an application to maximize reusability, including the following tips:
Use relative paths and URLs so links remain valid if the code tree moves.
Minimize Java in JSPs; instead, put Java in servlets and helper classes. JSP designers can revise
JSPs without being Java experts.
Use property files or global classes to store hard-coded strings such as the data source names,
tables, columns, JNDI objects, or other application properties.
Use session beans, rather than servlets and JSPs, to store business rules that are domain-
specific or likely to change often, such as input validation.
Use entity beans for persistent objects; using entity beans allows management of multiple beans
per user.
For maximum flexibility, use Java interfaces rather than Java classes.
Use J2EE CA to access legacy data.
Modularizing Applications
The major factors to keep in mind when designing your J2EE Applications are:
Functional Isolation
Reusable Code
Prepackaged Components
Shared Framework Classes
Security Issues
For more information about assembling modules and applications, see Chapter 4, “Assembling and
Deploying J2EE Applications.”
66
LESSON-1 Java Enterprise Edition
Functional Isolation
Each component should do one thing and one thing only. For example, in a payroll system, one EJB
component should access the 401k accounts while a separate bean accesses the salary database. This
functional isolation of tasks leads to the physical isolation of business logic into two separate beans. If
separate development teams create these beans, each team should develop its own EJB JAR package.
Scenario 1
Assume that the user interface development team works with both of the bean development teams. In
this case, the UI development team should assemble its servlets, JSPs, and static files into one WAR
file. For example:
payroll system EAR file = payroll EJB jar
+ 401k EJB JAR
+ 1 common war from the UI team
This isolation of functionality within an EAR file does not mean that components cannot interact with
each other. The beans (in separate EJB JAR files) can call business methods from each other.
Scenario 2
Assume that each bean development team has its own UI development team. If this is the case, then
each web development team should assemble its servlets, JSPs, and static files into separate WAR files.
For example:
payroll system EAR file = payroll EJB jar
+ 401k EJB JAR
+ 1 payroll UI team's war + 1 401k UI team's war
With this setup, the components in each WAR file can access components from the other WAR file.
Assembly Formulas
Some general formulas should be followed when assembling modules and applications. The following
table outlines assembly formulas.
Table 1-1 Assembly Formulas
Type of Development Group Teams in Group Modularizing Scheme
Small workgroup 1 web team + 1 EJB team 1 EAR = 1 EJB + 1 WAR
Enterprise workgroup 2 EJB teams + 1 web team + 1 component 1 EAR = 2 EJB + 1 WAR
+ 1 individual component
Reusable Code
Reusable components are the primary reason for assembling and deploying individual modules rather
than applications. If the code developed by one team of developers is a reusable component that may
be accessed by several applications (different EAR files), then that code should be deployed as an
individual module. For more information, see Chapter 4, “Assembling and Deploying J2EE Applications.”
Prepackaged Components
If you do not want to create your application from scratch, you can use prepackaged components.
Today's leading J2EE component vendors offer many prepackaged components that provide a whole
host of services. Their goal is to provide up to 60% of the standard components needed for an
application. With Sun Java System Application Server, you can easily assemble applications that make
use of these readily available components.
67
LESSON-1 Java Enterprise Edition
Sometimes several applications need to access a single modular library. In such cases, including the
library in each J2EE application is not a good idea for these reasons:
Library size: Most framework libraries are large, so including them in an application increases
the size of the assembled application.
Different versions: Because a separate classloader loads each application, several copies of
the framework classes exist during runtime.
For tips on how to set up a library so multiple applications can share it.
Security Issues
You should not allow unauthorized runtime access to classes, EJB components, and other resources. A
component should only contain classes that are permitted to access other resources included in the
component.
Problem
Forces
Solution
Implementation
Consequences
Applicability
References
Problem
Forces
68
LESSON-1 Java Enterprise Edition
(This section describes Lists the reasons and motivations that affect the problem and the solution. The
list of forces highlights the reasons why one might choose to use the pattern and provides a
justification for using the pattern)
You want to access the business-tier components from your presentation-tier components and
clients, such as devices, web services, and rich clients.
You want to minimize coupling between clients and the business services, thus hiding the
underlying implementation details of the service, such as lookup and access.
You want to avoid unnecessary invocation of remote services.
You want to translate network exceptions into application or user exceptions.
You want to hide the details of service creation, reconfiguration, and invocation retries from the
clients.
Solution
(Here solution section describes the solution approach briefly and the solution elements in detail)
Use a Business Delegate to encapsulate access to a business service. The Business Delegate hides the
implementation details of the business service, such as lookup and access mechanisms.
Structure
Let's use UML class diagram to show the basic structure of the solution and the UML Sequence diagram
in this section present the dynamic mechanisms of the solution.
Class Diagram
69
LESSON-1 Java Enterprise Edition
Sequence Diagram
BusinessDelegate - The BusinessDelegate’s role is to provide control and protection for the business
service.
ServiceLocator - The ServiceLocator encapsulates the implementation details of locating a
BusinessService component.
BusinessService - The BusinessService is a business-tier component, such as an enterprise bean, that
is being accessed by the client.
Client - Client can be JSP or Servlet or UI code
Implementation
(This section includes source code implementations and code listings for the patterns)
Let's refer the above class diagram and write source code to define Business Delegate Pattern.
Let's create source code step by step with reference to the class diagram.
Step 1: Create BusinessService Interface.
Interface for Business service implementations like JMSService and EJBService.
70
LESSON-1 Java Enterprise Edition
/**
* @param serviceType
* Type of service instance to be returned.
* @return Service instance.
*/
public BusinessService getBusinessService(ServiceType serviceType) {
if (serviceType.equals(ServiceType.EJB)) {
return ejbService;
} else if (serviceType.equals(ServiceType.JMS)) {
71
LESSON-1 Java Enterprise Edition
return jmsService;
} else {
return emailService;
}
}
Step 5: Create Client. The client utilizes BusinessDelegate to call the business tier.
72
LESSON-1 Java Enterprise Edition
Step 6 : Use BusinessDelegate and Client classes to demonstrate Business Delegate pattern.
In this example, the client utilizes a business delegate to execute a task. The Business Delegate then
selects the appropriate service and makes the service call.
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
businessDelegate.setLookupService(businessLookup);
businessDelegate.setServiceType(ServiceType.EJB);
businessDelegate.setServiceType(ServiceType.JMS);
client.doTask();
businessDelegate.setServiceType(ServiceType.EMAIL);
client.doTask();
}
}
Applicability
73
LESSON-1 Java Enterprise Edition
Use a Transfer Object Assembler to build an application model as a composite Transfer Object.
The Transfer Object Assembler aggregates multiple Transfer Objects from various business components
and services and returns it to the client.
This pattern is divided into a number of sections for simplicity like a problem, forces, solution, class
diagram, sequence diagram etc.
Table of contents
Problem
Forces
Solution
Implementation
Consequences
Applicability
References
Problem
Forces
(This section describes Lists the reasons and motivations that affect the problem and the solution. The
list of forces highlights the reasons why one might choose to use the pattern and provides a
justification for using the pattern)
You want to encapsulate business logic in a centralized manner and prevent implementing it in
the client.
You want to minimize the network calls to remote objects when building a data representation of
the business-tier object model.
You want to create a complex model to hand over to the client for presentation purposes.
You want the clients to be independent of the complexity of model implementation, and you
want to reduce coupling between the client and the business components.
74
LESSON-1 Java Enterprise Edition
Solution
(Here solution section describes the solution approach briefly and the solution elements in detail)
Use a Transfer Object Assembler to build an application model as a composite Transfer Object. The
Transfer Object Assembler aggregates multiple Transfer Objects from various business components and
services and returns it to the client.
Structure
Let's use UML class diagram to show the basic structure of the solution and the UML Sequence diagram
in this section present the dynamic mechanisms of the solution.
Below is the class diagram representing the relationships for the Transfer Object Assembler Pattern.
75
LESSON-1 Java Enterprise Edition
Class diagram
Sequence Diagram
Client - Client invokes the TransferObjectAssembler to obtain the application model data. The Client
can be a component of the presentation tier or can be a Session Façade that provides the remote
access layer for the clients accessing the TransferObjectAssembler.
76
LESSON-1 Java Enterprise Edition
Implementation
(This section includes source code implementations and code listings for the patterns).
Implementing the Transfer Object Assembler
Consider a project management application where a number of business-tier components define the
complex model. Suppose a client wants to obtain the model
data composed of data from various business objects, such as:
Project information from the Project component
Project manager information from the ProjectManager component
List of project tasks from the Project component
Resource information from the Resource component.
Step 1: Create Composite Transfer Object Class
A Transfer Object Assembler pattern can be implemented to assemble this composite transfer object.
77
LESSON-1 Java Enterprise Edition
78
LESSON-1 Java Enterprise Edition
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getAssignedResourceId() {
return assignedResourceId;
}
public void setAssignedResourceId(String assignedResourceId) {
this.assignedResourceId = assignedResourceId;
}
}
public class TaskResourceTO {
private String projectId;
private String taskId;
private String name;
private String description;
private Date startDate;
private Date endDate;
private TaskResourceTO assignedResource;
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
79
LESSON-1 Java Enterprise Edition
this.description = description;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public TaskResourceTO getAssignedResource() {
return assignedResource;
}
public void setAssignedResource(TaskResourceTO assignedResource) {
this.assignedResource = assignedResource;
}
}
public class ProjectManagerTO {
}
public class ProjectTO {
80
LESSON-1 Java Enterprise Edition
81
LESSON-1 Java Enterprise Edition
Consequences
Problem
Context
Data Access Object, Service Activator, Domain Store, Web Service Broker.
Solution
Use a Data Access Object to abstract and encapsulate all access to the persistent store. The Data Access
Object manages the connection with the data source to obtain and store data. The DAO completely hides
the data source implementation details from its clients. Because the interface exposed by the DAO to
clients does not change when the underlying data source implementation changes, this allows you to
change a DAO implementation without changing the DAO client’s implementation.
82
LESSON-1 Java Enterprise Edition
Client
The Client is an object that requires access to the data source to obtain and store data. The Client can
be a Business Object, a Session Façade, an Application Services, a Value List Handler, a Transfer Object
Assembler, or any other helper object that needs access to persistent data.
DataAccessObject
The DataAccessObject is the primary role object of this pattern. The DataAccessObject abstracts the
underlying data access implementation for the Client to enable transparent access to the data source.
The DataAccessObject implements create (insert), find (load), update (store), and delete operations.
DataSource
The DataSource represents a data source implementation. A DataSource could be a database, such as an
RDBMS, OODBMS, XML repository, flat file system, and so on. A DataSource can also be another system
(legacy/mainframe), service (B2B service or credit card bureau), or some kind of repository (LDAP).
ResultSet
The ResultSet represents the results of a query execution. For an RDMBS DataSource, when an application
is using JDBC API, this role is fulfilled by an instance of the java.sql.ResultSet.
Data
The Data represents a transfer object used as a data carrier. The DataAccessObject can use a Transfer
Object to return data to the client. The DataAccessObject could also receive the data from the client as a
Transfer Object to update the data in the data source.
Implementation Strategies
83