At the end of this chapter, you will be able to understand
While well-designed algorithms improve the efficiency of programs, the data structures will allow a programmer to use the underlying hardware and supporting language features to enhance the throughput of the programmers. J2SE 5.0 and later versions have provided collection framework that provides several interfaces such as Set<T>, List<T>, Queue<T>, and Map<k,s>. This chapter introduces you to these concepts so that you can deliver programs by efficiently using collections rather than developing programs yourself, thereby enhancing productivity.
In industry, databases are used extensively because of ease with which they provide answers to queries without resorting to elaborate programming through a software called sql query. The most popular databases in the industry are Oracle, MySql (open source by MySql.com), and, of course, MS Access that is within easy reach through all prevalent MS Office. This chapter shows you ways to handle these databases through Java programs by using drivers such as JDBC, JDBC-ODBC, and MySql connectivity tools. Servlets are important implementation in Java to handle client server programs. Servlets extend the functionality of web servers to any user on the net just like applets extend the functionality of the web browser. Java Beans is designed for reusability. In this chapter, you will learn the procedures to deploy java beans.
This chapter will put you through various skills that are required to become highly productive and make you ready to take up a job in the industry or enhance your skills. We teach you the methodologies through step-by-step procedures and programs and reflect these steps thereby making learning permanent and easy.
How do we store a group of objects in an array? J2SE 5.0 has provided a collection framework. Collection framework provides an API that makes programming using data structures easy and thereby enhances the productivity of the programmer. This is somewhat similar to the container of C++ but has quite a number of differences. Collection framework is implemented in java.util package. The concept is make a collection object, store group of objects in collection object. The collection framework of Java is shown in Figure 24.1
Figure 24.1 Collection class of java util
Collection class provides several interfaces such as Collection, Map, and Iterator. These are shown in Figure 24.2.
Figure 24.2 Interfaces provided by java collection
The Collection Framework classes and interfaces have been derived from meta class Object provided by Java. The hierarchy of classes of Collection framework is shown in Figure 24.3.
Figure 24.3 Class hierarchy of collection framework classes
Interfaces and their implementing class are shown in Table 24.1.
Table 24.1 Collection class interfaces and implementing classes
Interface | Implementing Class | Description |
---|---|---|
List | ArrayList | Implementation based on resizable array |
List | LinkedList | Implementation based on linked list |
Set | HashSet | Implementation based on Hash table |
Set | TreeSet | Implementation based on balanced binary tree |
Map | HashMap | Implementation based on Hash table |
Map | TreeMap | Implementation based on balanced binary tree |
The Collection Interface is the main interface from which the List and Set Interfaces are derived. It specifies the methods that are common to all Collections. The methods defined in the Collection Interface and their descriptions are listed in Table 24.2.
Table 24.2 Collection Interface and their descriptions
Method | Remark |
---|---|
boolean add(Object o) | Add a new object |
boolean addAll(Collection c) | Usage: t.addAll(c) Mimics union operation. Result: Collection t contains all the objects in both t and c |
void clear() | Remove All elements in the collection |
boolean contains(Object o) | Checks if object is present in collection |
boolean containsAll(Collection c) | Usage: t.containsAll(c) Mimics subset operation Result: returns true if Collection c is subset collection t |
boolean isEmpty() | Returns true if collection is empty |
Iterator iterator() | Used to traverse the collection |
boolean remove(Object o) | Remove object from collection |
boolean removeAll(Collection c) | Usage: t.removeAll(c) Result: All objects in Collection t which are also contained in collection c are removed |
boolean retainAll(Collection c) | Usage: t.retainAll(c) Mimics intersection operation. Result: Collection t has objects common to both t and t |
int size() | Number of objects in the collection |
Object[] toArray() Object[] toArray(Object[] a)) |
The array operations allow the contents of a Collection to be translated into an array |
Important features of Set interface are as follows:
We demonstrate some basic set operations in Example 24.1 using the HashSet implementation of the Set interface.
Example 24.1: Program to Demonstrate Basic Set Operations
1. import java.util.Set; 2. import java.util.HashSet; 3. public class SetDemo { 4. public static void main(String[] args) { 5. Set<String> PoolA=new HashSet<String>(); 6. PoolA.add(“India”); 7. PoolA.add(“Australia”); 8. PoolA.add(“South Africa”); 9. System.out.println(“PoolA: “ +PoolA); 10. Set<String> PoolB=new HashSet<String>(); 11. PoolB.add(“England”); 12. PoolB.add(“India”); 13. PoolB.add(“New Zealand”); 14. System.out.println(“PoolB: “ +PoolB); 15. 16. PoolA.retainAll(PoolB); 17. System.out.println(“Intersection Operation PoolA: “ +PoolA); 18. PoolA.addAll(PoolB); 19. System.out.println(“Union Operation PoolA: “ +PoolA); 20. System.out.println(“Subset Operation: “ 21. +PoolA.containsAll(PoolB)); 22. } 23. } 24. /* Output 25. PoolA: [Australia, South Africa, India] 26. PoolB: [England, New Zealand, India] 27. Intersection Opeartion PoolA: [India] 28. Union Operation PoolA: [England, New Zealand, India] 29. Subset Operation: true 30. */
Lines Nos. 1 & 2: | import Set and HashSet defined in the java.util package. Line 5 defines a set of strings called PoolA. |
Lines Nos. 6, 7 & 8: | show how to populate the Set PoolA using the add method. |
Line No. 9: | demonstrates how we can print the elements to PoolA on the console. |
Lines Nos. 11–15: | create a new Set PoolB and populate them with elements. |
Line No. 17: | demonstrates the intersection operation between sets, Line 19 union operations and Lines 21–22 the subset operations. |
Iterator allows us to iterate over a collection such as Set. The iterator interface is defined in java.util.Iterator. The interface defines three methods as seen below:
public interface Iterator {
public boolean hasNext();
public object next();
public void remove();
}
The hasNext( ) method returns true is the iteration has more elements. The next( ) method returns the next element in the collection and the remove( ) method is used to remove the last element returned by the iterator. Example 24.2 demonstrates usage of an iterator on a Set
Example 24.2: Program to Demonstrate Usage of Iterator
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class SetDemo {
public static void main(String[] args) {
Set<String> set=new HashSet<String>();
set.add(“Gautam”);
set.add(“Ramesh”);
set.add(“Anand”);
System.out.println(“HashSet Output”);
for(Iterator it = set.iterator(); it.hasNext(); ){
System.out.println(“String: “ + it.next());
}
}
}
/*Output
HashSet Output String: Gautam String: Ramesh String: Anand */
Line No. 12: | shows how to obtain an iterator for the Set using the iterator( ) methods. We use the hasNext( ) method as the breaking condition for the loop as shown in Line 12. To get the value of the element we use the next( ) method as shown in Line 13. |
Important features of List interface are as follows:
Table 24.3 describes the additional methods defined by the List interface
Table 24.3 Additional methods defined by List Interface
Method | Remark |
---|---|
E get(int index) | Returns element at given index |
E set(int index, E element) | Replace value at given index with new element |
boolean add(E element) | Adds element at the end of the list |
void add(int index, E element) | Adds element at the given index |
E remove(int index) | Removes element at the given index |
int indexOf(Object o) | Returns index of object o in the list |
int lastIndexOf(Object o) | Returns index of last found occurrence of Object o |
ListIterator<E> listIterator() | List Iterator extends the iterator it has ability to traverse the list in both directions, modify the list and provide positional information such as current index |
List<E> subList(int from, int to) | Returns a view of the list between indices from (inclusive) and to (excluded). Changes done in the sublist are reflected in the main list |
We demonstrate some of the important methods of the List Interface and also usage of the List Iterator in Example 24.3:
Example 24.3: Program to Demonstrate Usage of List Interface and List Iterator
1. import java.util.ArrayList;
2. import java.util.LinkedList;
3. import java.util.ListIterator;
4. public class ListDemo {
5. public static void main(String[] args) {
6. ArrayList<String> AList = new ArrayList<String>();
7. LinkedList<String> LList = new LinkedList<String>();
8. AList.add(new String(“Ramesh”));
9. AList.add(new String(“Anand”));
10. AList.add(new String(“Gautam”));
11. System.out.println(“ArrayList: “ +AList);
12. DemoArrayList(AList);
13. LList.add(new String(“Ramesh”));
14. LList.addFirst(new String(“Anand”));
15. LList.addLast(new String(“Gautam”));
16. System.out.println(“LinkedList: “ +LList);
17. System.out.print(”Reversed LinkedList: ”);
18. ListIterator<String> it = LList.listIterator(LList.size());
19. while(it.hasPrevious())
20. System.out.println(it.previous());
21. }
22. private static void DemoArrayList(ArrayList<String> list){
23. String s = new String(”Gautam“);
24. System.out.println(”index: ” +list.indexOf(s));
25. list.remove(s);
26. System.out.println(”ArrayList: ” +list);
27. list.set(0, ”Thunder“);
28. System.out.println(”ArrayList: ” +list);
29. }
30. }
31. /* Output
32. ArrayList: [Ramesh, Anand, Gautam]
33. index: 2
34. ArrayList: [Ramesh, Anand]
35. ArrayList: [Thunder, Anand]
36. LinkedList: [Anand, Ramesh, Gautam]
37. Reversed LinkedList: Gautam Ramesh Anand
38. */
We instantiate two lists one is of the type ArrayList(AList) and the other is of the type LinkedList(LList) in Lines 6 and 7. Both the Lists hold Strings. Lines 9, 10, and 11 demonstrate how to add elements to an ArrayList. The function DemoArrayList( ) further demonstrates some of the important methods of the List Interface. Lines 15, 16, and 17 show the methods that can be used to add elements to a LinkedList as seen in addition to the add method LinkedList provides the addFirst( ) and addLast( ) methods which enable us to add elements to the starting and ending of the list easily. Line 21 shows how to create a List iterator and set to the last element in the list by passing the LList.size( ) parameter during instantiation. Lines 22 and 23 show how to iterate backwards.
Java platform provides a number of useful algorithms. The algorithms are implemented as static methods in the Collections class. Many of the algorithms can be used only with Lists while some can be used with all the Collections. The algorithms are polymorphic in nature, i.e., the same method can be used on different implementations of a Collection interface. The algorithms can be used by importing the java.util.Collections class. In Table 24.4, we list some of the most widely used algorithms present in the collection class.
Table 24.4 Collection algorithms description
Algorithm | Remark |
---|---|
sort | Sorts the input list using an optimized merge sort algorithm. Worst case time complexity is nlog(n). |
binarySearch | The binarySearch algorithm searches for a specified element in a List. The input list must be sorted before using the binaryserach algorithm |
shuffle | Shuffles the order of elements in the list |
reverse | Reverses the order of elements in a List |
fill | Fills the List with the specified value. |
copy | Copies elements in a source list to a destination list. The size of the destination list must be equal or greater than the source list. |
swap | Swaps the elements at the specified positions in a List |
addAll | Adds all the specified elements to a Collection. Generally elements are appended to the end of the Collection |
frequency | Returns the number of instances of a specified element in a collection |
disjoint | Used to determine if two collections have no elements in common |
We demonstrate the usage of some the algorithms in Example 24.4.
Example 24.4: Program to Demonstrate Usage of Collection Algorithms
1. import java.util.Collections;
2. import java.util.ArrayList;
3. public class ListAlgorithmDemo {
4. public static void main(String[] args) {
5. ArrayList<Integer> IList = new ArrayList<Integer>();
6. ArrayList<String> SList = new ArrayList<String>();
7. IList.add(new Integer(7));
8. IList.add(new Integer(5));
9. IList.add(new Integer(9));
10. Collections.sort(IList);
11. System.out.println(“Ascending Order: “ +IList);
12. System.out.println(“Index of Integer 9 in sorted list: “
13. +Collections.binarySearch(IList, 9));
14. Collections.reverse(IList);
15. System.out.println(“Descending Order: “ +IList);
16. Collections.shuffle(IList);
17. System.out.println(“Shuffled List: “ +IList);
18. System.out.println(“Min: “ +Collections.min(IList));
19. System.out.println(“Max: “ +Collections.max(IList));
20. SList.add(new String(“Ramesh”));
21. SList.add(new String(“Anand”));
22. SList.add(new String(“Gautam”));
23. Collections.sort(SList);
24. System.out.println(“Ascending Order: “ +SList);
25. }
26. }
27. /* Output
28. Ascending Order: [5, 7, 9]
29. Index of Integer 9 in sorted list: 2
30. Descending Order: [9, 7, 5]
31. Shuffled List: [5, 9, 7]
32. Min: 5
33. Max: 9
34. Ascending Order: [Anand, Gautam, Ramesh]
35. */
Line Nos. 5 & 6: | create two List objects: one of Integer type and the other of String type. |
Lines Nos. 8, 9, & 10: | populate the Integer list. |
Line No. 12: | demonstrates how to apply sort algorithm on Integer list. |
Lines Nos. 14 & 15: | demonstrate binarysearch. Please note that binarysearch works only on sorted lists so we call it only after sorting the integer list. |
Lines Nos. 16 & 18: | demonstrate usage of shuffle and reverse algorithms. |
Lines Nos. 23–28: | sort algorithm on string list. |
Important features of Map interface are as follows:
Table 24.5 describes the methods defined in the Map interface.
Table 24.5 Map Interface description
Method | Remark |
---|---|
V put(K key, V value) | Create a new map for key and value |
V get(Object key) | Returns the value associated with key |
V remove(Object key) | Removes the mapping for key |
boolean containsKey(Object key) | Checks if collection contains a mapping for key |
boolean containsValue(Object value) | Checks if collection contains a mapping to value |
int size() | Returns the number of key–value pairs present in the collection |
boolean isEmpty() | Returns true if collection is empty |
void clear() | Clears all the mappings in the collection |
Set<K> keySet() | The method returns a Set which contains all the keys in the Map |
Collection<V> values() | The method returns a Collection which contains all the values in the Map. The method returns Collection and not a Set as values can be duplicate whereas Keys are unique |
Set<Map.Entry<K,V>> entrySet() | The method returns a Set which is populated with Map. Entry objects, key–value pairs can be obtained simultaneously by using methods defined in Map. Entry objects |
It is not possible to attach an iterator directly to a Map. So in order to iterate over a Map, the Map interface provides methods which allow the Map to be viewed as a Collection. Example 24.5 demonstrates two such methods: keySet() and values(). Please note that Map stores only object references so it is not possible to use primitive data types like double or int. Instead we can use wrapper class such as Integer or Double.
1. import java.util.Collection;
2. import java.util.Map;
3. import java.util.HashMap;
4. import java.util.Iterator;
5. import java.util.Set;
6. public class MapDemo{
7. public static void main(String[] args){
8. Map<Object,String> map=new HashMap<Object,String>();
9. map.put(new Integer(120400), “Ramesh”);
10. map.put(new Integer(120401), “Anand”);
11. map.put(new Integer(120402), “Gautam”);
12. System.out.println(“Printing Keys: “);
13. Set s = map.keySet();
14. for(Iterator itr = s.iterator();itr.hasNext();)
15. System.out.println(itr.next());
16. System.out.println(“Printing Values: “);
17. Collection c = map.values();
18. for(Iterator itr = c.iterator();itr.hasNext();)
19. System.out.println(itr.next());
20. }
21. }
22. /* Output
23. Printing Keys: 120401 120400 120402
24. Printing Values: Anand Ramesh Gautam
25. */
Line No. 8: | instantiates a Map object with Keys defined as Objects and Values defined as Strings. The Map uses the HashMap implementation. |
Line Nos. 9, 10, & 11: | populate the Map with an Integer object and String. |
Line No. 14: | demonstrates how to use the keyset( ) method to get a Collection view of the keys. We use the Set Interface as Set cannot have duplicates like keys. Similarly, Line 19 shows how to get a collection view of Values. |
Sometimes, we would like to modify the value associated with a key during iteration. Map interface provides a method entrySet() and a nested interface called Map.Entry to accomplish this. The method entrySet () returns a collection view of all the key–value pairs present in the Map. The nested interface Map.Entry is defined as follows:
public interface Entry {
K getKey(); V getValue(); V setValue(V value);}
As seen from the above, the interface provides methods through which we can access and modify the Value associated with a key. Example 24.6 demonstrated how to use method entrySet() and Map.Entry to iterate and access values associated with keys.
1. import java.util.Map;
2. import java.util.HashMap;
3. import java.util.Set;
4. import java.util.Iterator;
5. public class MapDemo {
6. public static void main(String[] args) {
7. Map<Object,String> map=new HashMap<Object,String>();
8. map.put(new Integer(120400), “Ramesh”);
9. map.put(new Integer(120401), “Anand”);
10. map.put(new Integer(120402), “Gautam”);
11. Set s=map.entrySet();
12. for(Iterator it=s.iterator();it.hasNext();){
13. Map.Entry m =(Map.Entry)it.next();
14. int rollno=(Integer)m.getKey();
15. String name=(String)m.getValue();
16. System.out.println(“Roll No:”+ rollno + “ Name:” +name );
17. }
18. }
19. }
20. /* Output
21. Roll No:120401 Name:Anand
22. Roll No:120400 Name:Ramesh
23. Roll No:120402 Name:Gautam
24. */
Line No. 12: | creates a Set s that contains all the key–value pairs contained in the map. We associate an iterator to the Set in Line 13. Line 14 demonstrates how to create a Map.Entry object. Lines 15 and 16 show how to get the key and value using the Map.Entry methods. The for loop used in the program can be simplified using a for each loop as follows: |
for (Map.Entry< Object, String > e : map.entrySet()){
System.out.println(“Roll No:”+ e.getKey() + “ Name:” +e.getValue());
}
When using the above for loop line 12 Set s=map.entrySet() is also not required.
In order to connect to a database you will need Drivers. Firstly, as you will be requesting connection from Java program, you will need JDBC Manager to act as interface between Java components such as Applet or Application and Drivers.
Then to work with databases such as Oracle, MS Access, and MySQL which are third party database you will need drivers such as ODBC (Open Database Connectivity) which takes calls supplied by JDBC and converts them into formats suitable for proprietary databases such as MS Access and Oracle 10g, etc. This means that Database and ODBC must be available in your machine. ODBC is shipped along with Windows OS. JDBC is a part of JDK which we have installed. Finally, MySQL also provides a connector mysql-connector-java-5.1.3 and mysql-5.1.51-win32.msi. First download these databases as per your choice and install them. Paths are to be set by you in case it has not prompted you during installation. Procedure for setting path is provided in Section 16.6.2. Figure 24.4 describes this arrangement. Applet and application are from client side and Database is from the server side. The server side also can reside in the same machine for testing in which case its called local host.
Figure 24.4 JDBC framework
Type 1: JDBC-ODBC Driver: Receives JDBC calls and hands over to ODBC driver. ODBC hands over these calls to manufacturers to library. This type is most widely used since ODBC drivers are available for almost all databases. This connector is a general connector and applicable to a wide variety of databases.
Type 2: Same as Type 1 but connector connects to a specific database. Hence, it is a specific connector. These are not popular since they are vendor specific.
Type 3: This is a net-based Data Connector in which JDBC converts the calls into middle tier server calls and, based on the actual server, the middle tier calls are converted to specific server. Obviously, as there is an additional conversion, this type is a slow connector.
Type 4: This is a pure Java driver that converts to vendor-specific database directly. It is machine independent since it is a pure Java product but the disadvantage is that you will need vendor-specific drivers.
MS Access is the most popular and easily available database available along with MS office package. Students have easy access to MS Access and can gain knowledge of the process involved and easily migrate to Oracle and MySql. The application we will select is to create a database with fields idNum, Name, and Dept and Salary of Employees. Once the database is created, we will use Sql query to access the records and display the result. There are three distinct phases for retrieving data from MS Access Database using JDBC-ODBC Bridge. They are:
Phase 1: Create MS Access database Table called oopsemp
Step 0: Start --- MicroSoft Office---- MS Access- create a new file-Blank Database enter filename to save as oops.mdbcreate in The Directory you are working. For example c:oopsjavaworkspaceoopstech2comoopschap24
Step 1: Choose option 3 i.e. create table by entering data
Step 2: Right click on field and select rename column and change field names to id, name, dept, salary. Then enter data in the relevant fields
Step 3: File save as oopsemp24.mdb ok. Click no for entering primary key
Step 4: Create Data Source Navigator DSN for JDBC ODBC connectivity Start settings control panel Administrative ToolsData Sources(ODBC)MS Access DataBasesAdd
Step 5: Select the database for which we want to create DSN
Step 6: Enter data Source Name as oopsemp and description oopstech company employees. Press ok.
Step 7: Select the file form your directory, i.e., oops.mdb and press ok
Step 8: The control will return to ODBC Microsoft Access screen at Step 6. Press ok
Step 9: The control will return to ODBC Data Source Administrator screen at Step 4 - press ok.
DSN has been created. Now we are ready for phase 3, i.e., write a Java program.
Phase 3: Write Java Program
We will show the methodology in steps
Step 0: import java.sql.*;
Step 1: Load and register the Driver by using Class.forName()
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Step 2: Establish connection to a database
Connection con = DriverManager.getConnection
(“jdbc:odbc:oopsemp”,””,””);
oopsemp is the data source name we have selected while creating access table. User Name and Pass word field are empty strings.
Step 3: Create a statement : Statement stmt = con.createStatement();
Step 4: Execute the statement : ResultSet rs = stmt.executeQuery (“select * from oopsemp24”);
Step 5: Work on ResultSet
while (( rs.next()))
{ System.out.print(rs.getInt(reccount)+” “);
System.out.print(rs.getString(reccount+1)+ “ “);
System.out.print(rs.getString(reccount+2)+” “);
System.out.println(rs.getFloat(reccount+3)+” “);
}
In our next example, we will put all the above steps into practice.
Example 24.7: AccessJDBCODBC.java A Program to Access Database File and Display the Fields
1. package com.oops.chap24;
2. import java.sql.*;
3. public class AccessJDBCODBC {
4. public static void main(String[] args) throws SQLException {
5. int reccount=1;
6. //Register the Driver
7. try{
8. Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
9. }catch ( Exception e ){System.out.println(“Unable to load Driver”);}
10. Connection con = DriverManager.getConnection(“jdbc:odbc:oopsemp”,””,””);
11. //create sql statement
12. Statement stmt = con.createStatement();
13. ResultSet rs = stmt.executeQuery(“select * from oopsemp24”);
14. System.out.println(“
id name Dept Salary”);
15. while (( rs.next()))
16. {System.out.print(rs.getInt(reccount)+” “);
17. System.out.print(rs.getString(reccount+1)+ “ “);
18. System.out.print(rs.getString(reccount+2)+” “);
19. System.out.println(rs.getFloat(reccount+3)+” “);
20. }
21. }
22. }
Output: id name Salary
id name Dept Salary
50595 Ramesh laptops 24000.0
50596 Usha internet 22000.0
50597 Anand automobile 80000.0
50598 gautam cellphones 75000.0
The reason for choosing MySql is free and open source being provided by MySql.com. For running the JDBC connectivity using MySql, you will need mysql-5.1.51-win32.msi and mysql-connector-java-5.1.13. These are software for using mysql and connecting to databases through Java programs. Let us say that you have installed them in Directory d:Directory sql. The path is automatically set by installer. In this case also, we would follow a two-step strategy:
Phase 1: Create the mysql database File
Step 1:To create database file : Start programs- MySql Server 5.1 >MySql command line client <enter> Enter password mysql command prompt appears.
mysql> show databases; command shows databases available
To see what tables are available in oopsemp2:
mysql> use oopsemp2; Database changed
mysql> show tables;
+--------------------+
| Tables_in_oopsemp2 |
+--------------------+
| oopsemp2 |
| oopsemp3 |
+--------------------+
2 rows in set (0.06 sec)
To create a table called: oopsemp4 :
mysql> create table oopsemp4 ( id int,name char(10),dept char(10),salary float);
uery OK, 0 rows affected (0.17 sec)
To verify the field created: mysql> desc oopsemp4;
+--------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | char(10) | YES | | NULL | |
| dept | char(10) | YES | | NULL | |
| salary | float | YES | | NULL | |
+--------+----------+------+-----+---------+-------+
To enter data in to table oopsemp4
mysql> insert into oopsemp4 values (50595,”Ramesh”,”laptops”,20000.00);
Query OK, 1 row affected (0.09 sec). Enter further records as required.
To see the records we have just entered:
mysql> select * from oopsemp4;
+-------+------------+---------------+----------+
| id | name | dept | salary |
+-------+--------+-------------------+----------+
| 50595 | Ramesh | Laptops | 20,000 |
| 50596 | Usha | Internet | 20,000 |
| 50597 | Anand | Automobiles | 80,000 |
| 50597 | Gautam | Cell phones | 80,000 |
+-------+--------+------------+--------+
4 rows in set (0.05 sec)
To set a query: to see id and names of employees whose salary is more than 20000.00
mysql> select name from oopsemp4 where salary >20000.00;
+----------+
| name |
+----------+
| Anand |
| Gautam|
+--------+
You have seen that we set queries and got the answers. Now will write a java program to connect to database and get the same answers.
Phase 2: Use JDBC connector and access the MySql database
Example 24.8: connect.java A Program to Access MySql Database File and Display
1. package com.oops.chap24;
2. import java.sql.*;
3. public class Connect{
4. public static void main(String args[]){
5. try{
6. String userName = “”;
7. String password = “”;
8. String url = “jdbc:mysql://localhost/oopsemp2”; //database name
9. Class.forName (“com.mysql.jdbc.Driver”).newInstance ();
10. Connection conn=DriverManager.getConnection (url, userName, password);
11. System.out.println (“Database connection established”);
12. Statement st = conn.createStatement();
13. ResultSet rs=st.executeQuery(“select * from oopsemp3”);// table name
14. System.out.println(“
output from table :oopsemp3…”);
15. System.out.print(“--------------------------
”);
16. System.out.println(“| Sur Name | Last Name |”);
17. System.out.println(“--------------------------”);
18. while(rs.next())
19. {
20. String username=rs.getString(1);
21. String password2=rs.getString(2);
22. System.out.print(“
| “+username);
23. System.out.print(“ | “+password2);
24. System.out.print(“ | “);
25. } // while
26. System.out.println(“
--------------------------”);
27. //Handle oopsemp4 table
28. rs=st.executeQuery(“select id,name from oopsemp4 where salary>20000.0”);// table name
29. System.out.println(“
id & name for salary>20000.00 from table :oopsemp4…”);
30. System.out.print(“--------------------------
”);
31. System.out.println(“|Employee id no | Name |”);
32. System.out.println(“--------------------------”);
33. while(rs.next())
34. {int userid=rs.getInt(1);
35. String name =rs.getString(2);
36. System.out.print(“
| “+userid);
37. System.out.print(“ | “+name);
38. System.out.print(“ | “);
39. } // end of while
40. System.out.println(“
--------------------------”);
41. } catch(Exception ex){ex.printStackTrace();}
42. } //main
43. } // class
Output : Database connection established
output from table :oopsemp3…
--------------------------
| Sur Name | Last Name |
--------------------------
| ramesh | vasappanavara |
| Usha | vasappanavara |
| Anand | vasappanavara |
| Gautam | vasappanavara |
--------------------------
id & name for salary>20000.00 from table :oopsemp4…
--------------------------
|Employee id no | Name |
--------------------------
| 50597 | Anand |
| 50597 | Gautam |
--------------------------
There are three distinct phases for retrieving data from Oracle database using JDBC-ODBC Bridge. They are:
Phase 1: Create Oracle database file
We are assuming that you have Oracle installed in your computer system and SQL>prompt is available. We will show only in command prompt usage, while web-based approach is also allowed by Oracle 10 and later versions. All Oracle databases file in Oracle 10g and later will have User name: system and password: oracle. Other older oracle versions use username: scott and password: tiger. Get SQL prompt on the screen.
SQL> connect system; Enter password:oracle<enter> Connected. SQL>
SQL> select * from cat ; will list out all tables in system
-----------------------------------------
PRODUCT_USER_PROFILE SYNONYM
HELP TABLE
OOPSEMP5 TABLE
179 rows selected.
SQL>
SQL> SQL> create table oopsemp6( idNum int, name varchar2(10),dept varchar2(10),salary float);
Table created.
OOPSEMP6 TABLE
OOPSEMP5 TABLE
180 rows selected.
SQL> desc oopsemp6; will show the field in table oopsemp6
Name Null? Type
--------------------------------------------------------------
IDNUM NUMBER(38)
NAME VARCHAR2(10)
DEPT VARCHAR2(10)
SALARY FLOAT(126)
SQL> insert into oopsemp6 values(&idNum,’&name’,’&dept’,&salary);
Enter value for idnum: 50595
Enter value for name: Ramesh
Enter value for dept: laptops
Enter value for salary: 20000.00
old 1: insert into oopsemp6 values(&idNum,’&name’,’&dept’,&salary)
new 1: insert into oopsemp6 values(50595,’Ramesh’,’laptops’,20000.00)
1 row created.
We can create further records.
SQL > SELECT * FROM OOPSEMP6; will show you the data we have entered
IDNUM NAME DEPT SALARY
----------------------------------------
50595 Ramesh laptops 20000
50596 Usha Internet 22000
Now we are ready to proceed to Phase 2
Phase 2: Create a Data Source Name (DSN)
Step 1: Create Data Source Navigator DSN for JDBC ODBC connectivity
Start- settings - control panel Administrative ToolsData Sources(ODBC)-Add
Step 2: Select the database for which we want to create DSN-Press Finish.
Step 3: Enter data Source Name as oopsempdsn and description oops employees. Description system and Press ok.
Step 4: The control will return to ODBC Data Source Administrator screen at Step 1 you can see oopsempdsn1 listed press ok.
DSN has been created. Now we are ready for phase 3, i.e., write a Java program.
Phase 3: Write Java Application to access the Oracle database
Example 24.9: AccessOracle.java A program to Access Oracle Database
1. package com.oops.chap24;
2. import java.sql.*;
3. public class accessoracle{
4. public static void main(String args[]){
5. try{
6. String userName = “system”;
7. String password = “oracle”;
8. String url = “jdbc:odbc:oopsempdsn”; //database name
9. Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
10. Connection conn=DriverManager.getConnection (url,userName,password);
11. System.out.println (“Database connection established”);
12. Statement st = conn.createStatement();
13. //Handle oopsemp5 table
14. ResultSet rs=st.executeQuery(“select idNo ,name from oopsemp5 where
15. salary>20000.0”);// table name
16. System.out.println(“
idNo & name for salary>20000.00 from table :oopsemp5…”);
17. System.out.print(“--------------------------
”);
18. System.out.println(“|Employee id no | Name |”);
19. System.out.println(“--------------------------”);
20. while(rs.next())
21. { int userid=rs.getInt(1);
22. String name =rs.getString(2);
23. System.out.print(“
| “+userid);
24. System.out.print(“ | “+name);
25. System.out.print(“ | “);
26. } // end of while
27. System.out.println(“
--------------------------”);
28. } catch(Exception ex){ex.printStackTrace();}
29. } //main
30. } // class
Output : Database connection established
idNo & name for salary>20000.00 from table :oopsemp5…
------------------------------
|Employee id no | Name |
-------------------------------
| 50596 | Usha |
| 50597 | Anand |
| 50599 | Gautam |
-------------------------------
Example 24.10: Inserting Records into a Database
1. package com.oops.chap24;
2. import java.sql.*;
3. public class InsertDB{
4. public static void main(String args[]){
5. try{String userName = “system”;
6. String password = “oracle”;
7. String url = “jdbc:odbc:oopsempdsn”; //database name
8. Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
9. Connection conn = DriverManager.getConnection (url, userName, password);
10. System.out.println (“Database connection established”);
11. Statement st = conn.createStatement();
12. //Handle oopsemp5 table
13. System.out.println(“
Inserting a record in to database”);
14. st.executeUpdate(“insert into oopsemp5 values(50600,’Prahlad’,’Toys’,40000.00)”);
15. ResultSet rs=st.executeQuery(“select idNo ,name from oopsemp5”);// table name
16. System.out.println(“
idNo & name from table :oopsemp5…”);
17. System.out.print(“--------------------------
”);
18. System.out.println(“|Employee id no | Name |”);
19. System.out.println(“--------------------------”);
20. while(rs.next())
21. {int userid=rs.getInt(1);
22. String name =rs.getString(2);
23. System.out.print(“
| “+userid);
24. System.out.print(“ | “+name);
25. System.out.print(“ | “);
26. } // end of while
27. System.out.println(“
--------------------------”);
28. } catch(Exception ex){ex.printStackTrace();}
29. } //main
30. } // class
Output : Database connection established
Inserting a record in to database
idNo & name from table :oopsemp5…
--------------------------
|Employee id no | Name |
--------------------------
| 550595 | ramesh |
| 50596 | Usha |
| 50597 | Anand |
| 50599 | Gautam |
| 50600 | Prahlad |
--------------------------
Example 24.11: Updating a Field in a Records in a Database
package com.oops.chap24;
import java.sql.*;
public class UpdateDB{
public static void main(String args[]){
try{
String userName = “system”;
String password = “oracle”;
String url = “jdbc:odbc:oopsempdsn”; //database name
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection conn = DriverManager.getConnection (url, userName, password);
System.out.println (“Database connection established”);
Statement st = conn.createStatement();
//Handle oopsemp5 table
System.out.println(“
Updating a record in to database”);
st.executeUpdate(“update oopsemp5 set salary = 35000 where idNo=50595”);
ResultSet rs=st.executeQuery(“select idNo ,name, salary from oopsemp5”);// table name
System.out.println(“
idNo&name&salary from table :oopsemp5…”);
System.out.print(“----------------------------------------
”);
System.out.println(“|Employee id no | Name | Salary |”);
System.out.println(“--------------------------------------”);
while(rs.next())
{int userid=rs.getInt(1);
String name =rs.getString(2);
float sal = rs.getFloat(3);
System.out.print(“
| “+userid);
System.out.print(“ | “+name);
System.out.print(“ | “+ sal);
} // end of while
System.out.println(“
--------------------------”);
} catch(Exception ex){ex.printStackTrace();}
} //main
} // class
Output: Database connection established
Updating a record in to database
idNo & name from table :oopsemp5…
----------------------------------------
|Emp idno | Name | Salary |
----------------------------------------
| 50595 | ramesh | 35000.0 |
| 50596 | Usha | 22000.0 |
| 50597 | Anand | 80000.0 |
| 50599 | Gautam | 85000.0 |
| 50600 | Prahlad | 40000.0 |
---------------------------------------
Example 24.12: Deletion Database Record
package com.oops.chap24;
import java.sql.*;
public class DeleteDB{
public static void main(String args[]){
try{String userName = “system”;
String password = “oracle”;
String url = “jdbc:odbc:oopsempdsn”; //database name
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection conn = DriverManager.getConnection (url, userName, password);
System.out.println (“Database connection established”);
Statement st = conn.createStatement();
//Handle oopsemp5 table
System.out.println(“
Deleting records to database”);
st.executeUpdate(“delete oopsemp5 where idNo=50600”);
} catch(Exception ex){ex.printStackTrace();}
}
}
You can use module presented at Ex1 to view the database records. You can observe that records with idNo=50600 have been deleted.
We have used Statement Object: Statement st = conn.createStatement(); where conn is an object : Connection conn = DriverManager.getConnection (url, userName, password);
Finally we have used st : st.executeUpdate(“delete oopsemp5 where idNo=50600”);
Statement carries out parsing every time statement gets executed. So far there are no repetitions of statements. What is if there is loop in which a statement gets executed several times thus wasting compiler time.
PreparedStatement, on the other hand, is a pre-parsed and compiled statement that needs not be compiled every time a statement gets executed. Thus, it is beneficial to use PreparedStatement if multiple executions are expected.
//Handle oopsemp5 table
PreparedStatement st = conn.prepareStatement (“update oopsemp5 set salary=? where idNo=?”);
System.out.println(“
Updating a record in to database”);
st.setFloat(1,50000.00f); // applies to first ? mark
st.setInt(2,50595); // applies to second ?
st.executeUpdate(“update oopsemp5 set salary = 35000 where idNo=50595”);
Example 24.13: PreparedDB.java A Program to Show the Usage of PreparedStatement
1. package com.oops.chap24;
2. import java.sql.*;
3. public class PreparedDB{
4. public static void main(String args[]){
5. try{
6. a. String userName = “system”;
7. String password = “oracle”;
8. String url = “jdbc:odbc:oopsempdsn”; //database name
9. Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
10. Connection conn = DriverManager.getConnection (url, userName, password);
11. System.out.println (“Database connection established”);
12. //Handle oopsemp5 table
13. System.out.println(“Updating a record in to database”);
14. PreparedStatement st = conn.prepareStatement(“update oopsemp5 set salary = ? where idNo = ?”);
15. st.setFloat(1,50000); // applies to first ? mark
16. st.setInt(2,50595); // applies to second ?
17. st.executeUpdate();
18. Statement st1 = conn.createStatement();
19. ResultSet rs=st1.executeQuery(“select idNo ,name ,salary from oopsemp5”);// table name
20. System.out.println(“idNo & name & salary :oopsemp5…”);
21. System.out.print(“------------------------------------
”);
22. System.out.println(“|Employee id no | Name |Salary |”);
23. System.out.println(“------------------------------------”);
24. while(rs.next())
25. {
26. int userid=rs.getInt(1);
27. String name =rs.getString(2);
28. float sal = rs.getFloat(3);
29. System.out.print(“
| “+userid);
30. System.out.print(“ | “+name);
31. System.out.print(“ | “+ sal);
32. } // end of while
33. System.out.println(“
--------------------------”);
34. } catch(Exception ex){ex.printStackTrace();}
35. } //main
36. } // class
Output: Database connection established
Updating a record in to database
idNo & name & salary from table :oopsemp5…
----------------------------------------
|Employee id no | Name | Salary |
--------------------------------------
| 50595 | ramesh | 50000.0
| 50596 | Usha | 22000.0
| 50597 | Anand | 80000.0
| 50599 | Gautam | 85000.0
Callable statements are statements in a Java program that call a stored procedures and functions. Stored procedures are a set of statements executed on database and the result is sent to calling Java program.
Step 0: We have to create a stored procedure say sutti.sql. Go to sql prompt and enter
SQL> select * from oopsemp7;
IDNO NAME SALARY
------------------------------
50595 Ramesh 20,000
50596 Usha 22,000
Step 1: Enter at SQL Prompt
SQL> create or replace procedure sutti( no in int, pay out float) as sal float;
2 begin
3 select salary into sal from oopsemp7 where idno=no;
4 pay:=sal+10000;
5 end;
6 / press enter
Procedure created.
SQL>
Alternatively, you can open notebook anywhere, enter the program, and save it as sutti.sql. The contents can be :
create or replace procedure sutti1(no in int, pay out float) as sal float;
begin
select salary into sal from oopsemp5 where idNo=no;
pay := sal + 10000; // observe it is :=
end;
/ // after pasting code in SQL prompt press enter
Copy the content of file using copy and paste it on to SQL> prompt line. It will appear as
SQL> create or replace procedure sutti1
2 (no in int, pay out float) as sal float;
3 begin
4 select salary into sal from oopsemp5 where idNo=no;
5 pay := sal + 10000;
6 end;
7 /
Press Enter. You will see procedure created message on the sql prompt screen. You are ready.
Example 24.14: StoredDB.java A Program to Show the Usage of CallableStatement
package com.oops.chap24;
import java.sql.*;
public class StoredDB{
public static void main(String args[]){
try{String userName = “system”;
String password = “oracle”;
String url = “jdbc:odbc:oopsempdsn”; //database name
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection conn = DriverManager.getConnection (url, userName, password);
System.out.println (“Database connection established”);
//Handle oopsemp5 table
System.out.println(“Using a callable statement”);
CallableStatement st2 = conn.prepareCall(“{ call sutti(?,?)}”);
st2.setInt(1,50596); // applies to first ? mark
//Register the output as float data type
st2.registerOutParameter(2,Types.FLOAT);
st2.execute();
float incrPay = st2.getFloat(2);
System.out.println(“
enhanced pay “ + incrPay);
conn.close();
} catch(Exception ex){ex.printStackTrace();}
} //main
} // class
Output : Database connection established
Using a callable statement
enhanced pay 32000.0
How to update fields in a record of database?
In the above example , the stored procedure did not update the record; instead it returned up dated salary to calling procedure. What should we do in case we need to update the database. Ex 4 at the end of the chapter gives the program.
We are aware that applets are dynamic and that they reside embedded on to web browser and can extend the functionality of the web browser across the Internet. Servlets like applets are small server side programs that reside on the web servers and extend the web servers functionality across the Internet. Hence, the name Servlets. As an example, consider a server is hosting an application for centralized inventory control system for its multi-country multi-location branches. The company provides information about Inventory on real time through web pages to all its branch offices. The information must reflect the latest position of the stock in the database. Servlets offer best possible means to extend the web server to client and in addition provide advantages such as platform independency, ability to interact with applets, databases and sockets, etc.
What environment we need to put Servlets to work?
To host a servlet you need a server. The best server widely used in industry is Tomcat Apache Server. This software can be downloaded :Jakarta.apache.org and can be downloaded to: C:Program Files Apache Soft FoundationTomcat 5.0. To start the server go to bin directory and click on C:Program FilesApache Software FoundationTomcat 6.0in> tomcat6.exe. You will also be able to start the tomcat server by using startprogramsTomcat6.0- tomcat6 or by permanently setting tomcat server to be worked each time you switch on the system by selecting tomcat6 by running config command from startrun config
Servlet libraries-servlet-api.jar: Note that Servlets is not part of pure java. Hence, you need to include servlet-api.jar which is present c:Program FilesApache Software FoundationTomcat 6.0commonlibserver.jar file as part of class path. The procedure for doing so is: start settingscontrolpanelsystemadvanced environment variables select class path from bottom- edit enter the class path shown above press ok
Step 0: | Write servlet code ServletWelcome.java in the directory called Demo1 and place the directory Demo1 C:Program FilesApache Software FoundationTomcat 6.0webapps. The content of directory Demo1 should be as shown in Figure 24.5. |
Figure 24.5 Where to house Servlet programs?−Organization
Example 24.15: ServletWelcome.java A program to Show the Usage of Servlet
1. import java.io.*;
2. import javax.servlet.*;
3. public class ServletWelcome extends GenericServlet {
4. public void service(ServletRequest req,ServletResponse res) throws i. ServletException,IOException{
5. res.setContentType(“text/html”);
6. PrintWriter pw = res.getWriter();
7. pw.println(“<B>Hello Students! Welcome to Servlet Chapter”);
8. }
9. }
Compile javac ServletWelcome.java into C:Program FilesApache Software FoundationTomcat 6.0webappsdemo1WEB-INFclasses. Note that loading class file into the specified directory is mandatory for Tomcat to pick up the class file.
Step 1: Add servlet name and mapping to web.xml file in the following C:Program FilesApache Software FoundationTomcat 6.0webappsdemo1WEB-INF.Web.xml file can be opened by notepad or wordpad for editing. Servlets are embedded onto web.xml file. A typical web.xml file would look like:
Example 24.16: A typical web.xml File for ServletDemo Servlet
<?xml version=”1.0” encoding=”ISO-8859-1”?>
<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”
“http://java.sun.com/dtd/web-app_2_3.dtd”>
<web-app>
<servlet>
<servlet-name>ServletWelcome</servlet-name>
<servlet-class>ServletWelcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletWelcome</servlet-name>
<url-pattern>/ServletWelcome</url-pattern>
</servlet-mapping>
</web-app>
Step 2: Start the tomcat server
Step 3: Send request on web browser
http://localhost:8080/demo1/ServletWelcome
Output: Hello Students! Welcome to Servlet Chapter
Line No. :2 | imports javax.servlet.* ; a package essential to run servlet programs. Make sure you have included Servlets-api.jar file in your class path. |
Line No. 3: | creates a class ServletWelcome as subclass of GenericServlet. That provides init(), destroy() methods. We will override service() method for our own implementation. Service() method takes care of clients requests by accepting ServletRequest object res and gives out ServletResponse object res. |
Line No. 5: | sets the content type to html/text. It is an indication that browser to interpret the data in html. |
Line Nos. 6 & 7: | use getWriter() that obtains PrintWriter object pw. In Line No. 7, the object pw writes the string to web browser to display the message. |
Servelt API contains javax.servlet and javax.setvlet.http. These are part of Tomcat wservlet-api.jar and not part of J2SE 5. javx.servlet package supplies all the interfaces required for the implementation and is shown in Table 24.6, while the important classes in the package are shown at Table 24.7. Interfaces are shown in Table 24.8.
Table 24.6 Interfaces provided javax.servlet package
Javax.servlet package interfaces | Remarks |
---|---|
Servlet | Life cycle methods of servlets included |
ServletRequest | Gets data from the client request |
ServletResponse | Sends data to client request |
ServletConfig | Initial params are set |
ServletContext | Servlets can log events & can get environment info |
Table 24.7 Classes provided javx.servlet package
Javax.servlet package Classes | Remarks |
---|---|
GenericServelet | Implements servlets * config interfaces |
ServletInputStream | InputStreamfor the client request |
ServletOutputStream | OutputStream for sending data |
ServletException | Servlet error |
ServletUnavailableException | Servlet unavailable |
Table 24.8 Servlet interface−Methods
Javax.servlet interface Methods | Remarks |
---|---|
void service(ServiceRequest req, ServiceResonse res) throws Sevlet Exception,IOException | Attends request from client and sends the response |
void init( ServletConfig config) | Initialization params are set |
ServletConfig getServletConfig() | Servlets config information & ServletsContext for accessing environment params |
String getServletInfo() | Returns servlet author 7version |
void destroy() | Called when servlet is unloaded |
ServletException | Servlet error |
ServletUnavailableException | Servlet unavailable |
ServletRequest and ServletResponse interphases shown above receive the request object from client and prepares response to be sent. Servlet packages define two types of abstract classes. One is GenericServlet belonging to javax.servlet and the other is HttpServlet belonging to package javax.servlet.http. In our next example, we will show a program extending to GenericServlet. In this example, we would read the parameter names and values contained in clients request by copying them into object enm of Enumeration class of Javas Utility Package.
Example 24.16: PostParam.java A Program to Show Extending to GenericServlet.
1. import java.io.*;
2. import java.util.*;
3. import javax.servlet.*;
4. public class PostParamServlet extends GenericServlet {
5. public void service(ServletRequest req , ServletResponse res)
6. throws ServletException,IOException{
7. // print writer
8. PrintWriter pwtr = res.getWriter();
9. Enumeration enm = req.getParameterNames();
10. // Display Parameter names and values
11. while( enm.hasMoreElements()){
12. String stg = (String) enm.nextElement();
13. pwtr.print(stg + “ = “);
14. String pval= req.getParameter(stg);
15. pwtr.println(pval);
16. }
17. pwtr.close();
18. }
19. }
Step1: Compile javac PostParamServlet.java into C:Program FilesApache Software FoundationTomcat 6.0webappsdemo2WEB-INFclasses. Load the html file PostParamServlet.html also in the same directory.
HTML File: PostParamServlet
<html>
<body>
<center>
<form name=”Form1”
method =”post”
action =”http://localhost:8080/demo2/PostParamServlet”>
<table>
<tr>
<td><B>StudentName</td>
<td><input type = textbox name=”studentname” size=”24” value =””></td>
</tr>
<tr>
<td><B>RollNumBer</td>
<td><input type=textbox name=”studentnumber” size=”24” value =””></td>
</tr>
</table>
<input type=”submit” value = “Submit”>
</body>
</html>
Web.xml: As shown in Example 24.16b
Step 2: Start the Tomcat Server
Step 3: Send request on web browser
http://localhost:8080/demo2/PostParamServlet
OUTPUT from server
studentname = ShraddaPandey
studentnumber = 50596
Out of the two abstract classes, namely, GenericServlet and HTTPServlet, HttpServlet provides better interface and is widely used. The important methods are:
Whenever doGet() or doPost() methods are called, object of HttpServletRequest is created by the server and passed on to service() method as an argument. The service() method executes the service request and makes the response ready for dispatch to client. A few of the important methods supported by HttpServletRequest interface are shown in Table 24.9.
Table 24.9 HttpServletRequest interface
HttpServletRequest interface | Remarks |
---|---|
String getName() | Gets the argument sent to servlet byget or post requests |
Enumeration getParameterNames() | Returns manes of all parameters |
String[] getParameterValues( String names) | Names of all parameters sent to servlet |
Cookie[] getCookies() | Return an array of cookie object |
HttpSession getSession(boolean create) | Returns current session of the client. Helps in unique identification of the client |
The main job of HttpServletResponse is to prepare the response to be sent to the client on receipt of HttpServletRequest Object. The web servers that is executing the servlet makes an object of HttpServletResponse and hands it over to service() method. A few of the important methods are presented in Table 24.10.
Table 24.10 HttpServletRequest methods interface
HttpServletResponse interface | Remarks |
---|---|
ServletOutputStream getOutputStream() | Gets a Byte-based output stream to be sent to client |
PrintWriter getWriter() | Gets a character-based output stream for sending text data |
void setContentType | Sets Multipurpose Internet Mail Extensions (MIME) type. Ex “text/html” |
void addCookie(cookie cookie) | Returns an array of cookie object |
HttpSession getSession(boolean create) | Returns current session of the client. Helps in unique identification of the client |
HttpServlet class provides several methods to perform tasks of receiving client request and sending servers response. The important methods are doGet() and doPost(). The other methods include doDelete(), doPut() and, of course, service() method. These methods all handle HTTP functions. In our next example, we will show Http Get Request. In this model, we present a form for the user to select his favourite subject by offering options and a submit button. The action statement in the html file links the servlet to be called by the server. Server calls the prescribed servlet and prepares the response and sends them to client. The client selects a preferred subject and submits the choice to servlet at server. The Http request is received by the servlet and prepares the response.
Example 24.18: SubjectGetServlet.java A Program to Show Usage of HTTP Get Request
Step 1: Create HTML File: SubjectGetServlet.html in the Directory C:PROGRA~1APACHE~1TOMCAT~1.0webappsDemo3WEB-INFclasses>
1. <html>
2. <body>
3. <center>
4. <form name=”Form1”
5. action=”http://localhost:8080/Demo3/SubjectGetServlet”>
6. <B>Subject:</B>
7. <select name=”subject” size=”1”>
8. <option value=”Maths”>Mathematics</option>
9. <option value=”Physics”>Physics</option>
10. <option value=”Chemistry”>Chemistry</option>
11. </select>
12. <br><br>
13. <input type=submit value=”Submit”>
14. </form>
15. </body>
16. </html>
DropDown List. User selects any one subject from options at Line Nos. 7, 8, and 9.
Step 2: Create Servlet program SubjectGetServlet.java in the directory: C:PROGRA~1APACHE~1TOMCAT~1.0webappsDemo3WEB-INFclasses>
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SubjectGetServlet extends HttpServlet {
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException, IOException {
7. String subject=req.getParameter(“subject”);
8. res.setContentType(“text/html”);
9. PrintWriter pwtr=res.getWriter();
10. pwtr.println(“<B>The selected subject is: “);
11. pwtr.println(subject);
12. pwtr.close();
13. }
14. }
Line No. 4: | shows SubjectGetServlet extending to HttpServlet |
Line No. 5: | uses doGet() with arguments HttpServletRequest req, HttpServletResponseres. |
Line No. 7: | uses getParameter() method with “subject” being passed as argument from html file. The program will receive mathematics or physics or chemistry as argument. |
Line No. 8: | sets the content as html and Line Nos. 9, 10, 11 send the response to client |
Step 3: Compile the code:
C:PROGRA~1APACHE~1TOMCAT~1.0webappsDemo3WEB-INFclasses>javac SubjectGetServlet.java
Step 4: create web.xml file in the directory: As per example, 24.16b
Step 5: Start the Tomcat server C:Program FilesApache Software FoundationTomcat 6.0in
Step 6: Send request on web browser by double clicking on the html icon
Servlet OUTPUT: The selected subject is: Mathematics
We have seen doGet() method by HttpServlet which is used to get the client request. In this section, we will study doPost() method which is used just like doGet() when fetching input through Form. Html file SubjectPost.html and HttpServlet program called SubjectPostServlet.java. Post request is identical to Get Request except that Form method will have “post” specified explicitly.
Example 24.19: Apcode.java A Program to Show Usage Post Method in HttpPost Request
The program uses Post method to send client request and receive response from the server. The application is a simple coding of text in which capital letter is added 13 to get a new character. For example, character ‘A’ will be coded as 65 + 13 =78, i.e., character ‘B’. If the resultant character goes beyond ‘Z’, then 26 is subtracted. These values are so chosen that characters wrap around when they overflow beyond ‘Z’. Further, observe that we would also shape the response using html document as shown in Apcode.java so that result is displayed using the same form format. We have included coding only for capital letters. There are three distinct files. One is an html file, Apcode.html, and the second file is Apcode.java. These files are created in the directory: C:Program FilesApache Software FoundationTomcat 6.0webappsexamples WEB-INFclasses
Web.xml file is in Directory: FilesApache Software FoundationTomcat 6.0 webapps examples WEB-INF
Step 1: Create Apcode.html file in directory C:Program FilesApache Software FoundationTomcat 6.0webappsexamples WEB-INFclasses
1. <html>
2. <body>
3. <head><title>Apcode Coder</title></head>
4. <h1>Apcode Coder</h1>
5. <p>Text to code:
6. <form name=”Form1”
7. method=”post”
8. action=”http://localhost:8080/examples/Apcode”>
9. <textarea name=”text” rows=”8” cols=”55”>
10. </textarea>
11. <p><input type=submit value = “code”>
12. </form>
13. </body>
14. </html>
Line No. 7: | indicates that we are using post method. The action part of the form specifies that the Servlet resource is at examples/web-inf/classes. |
Step 2: Create Servlet program Apcode.java in the directory: C:Program FilesApache Software FoundationTomcat 6.0webappsexamples WEB-INFclasses
Apcode.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class Apcode extends HttpServlet {
5. public void doPost(HttpServletRequest req, HttpServletResponse res)
6. throws ServletException, IOException {
7. String text = req.getParameter(“text”);
8. String translation = translate(text);
9. res.setContentType(“text/html”);
10. ServletOutputStream out = res.getOutputStream();
11. out.println(“<html>”);
12. out.println(“<body>”);
13. out.println(“<head><title>Apcode Coder</title></head>”);
14. out.println(“<h1>Apcode Coder</h1>”);
15. out.println(“<p>Text to code:”);
16. out.println(“<form action=”Apcode” method=”post”>”);
17. out.println(“<textarea name=”text” ROWS=8 COLS=55>”);
18. out.println(translation);
19. out.println(“</textarea>”);
20. out.println(“<p><input type=”submit” value=”code”>”);
21. out.println(“</form>”);
22. out.println(“</body>”);
23. out.println(“</html>”);
24. }
25. public void doGet(HttpServletRequest req, HttpServletResponse res)
26. throws ServletException, IOException {
27. doPost(req, res);
28. }
29. String translate(String input) {
30. StringBuffer output = new StringBuffer();
31. if (input!= null) {
32. for (int i = 0; i < input.length(); i++) {
33. char inChar = input.charAt(i);
34. if ((inChar >= ‘A’) & (inChar <= ‘Z’)) {
35. inChar += 13;
36. if (inChar > ‘Z’)
37. inChar -= 26;
38. }
39. output.append(inChar);
40. }
41. }
42. return output.toString();
43. }
44. }
Line No. 4: | specifies that Apcode extends to HttpServlet interface. |
Line No. 5: | shows that doPost() method is used to get the request of the client and send the response. |
Line No. 7: | shows usage of req.getParameter(“text”); to get the client request. |
Line No. 9: | sets the content to text / html type. |
Line No. 10: | obtains ServletOutputStream object out for sending response to client. |
Line Nos. 11 to 23: | show that we are sending response to client using out object and in the same format as that used by Apcode.html |
Line No. 16: | Shows use of escape character for setting up of action part of response out.println(“<form action=”Apcode” method=”post”>”); |
Line No. 24: | uses doGet()method and which in turn calls doPost() method at Line No. 27 |
Step 3: Compile the code : C:Program FilesApache Software FoundationTomcat 6.0webappsexamplesWEB-INFclasses >javac SubjectPostServlet.java
Step 4: create web.xml file in the directory: As per example, at 24.16b
Step 5: Start the Tomcat server from C:Program FilesApache Software FoundationTomcat 6.0in directory.
Step 6: Send request on web browser by double clicking on the html icon
OUTPUT form Servlet Apcode:
Java's strong point is its reusability feature and java beans is a feature available in Java for providing this feature. Java bean is a portable, platform-independent component model to facilitate writing highly reusable components. For this, we would use Java Beans API. Once these components are developed, we can embed them in applets or applications. Java beans can be visual or non-visual components. Beans are dynamic in that they can be changed or customized. We can use property of beans component to customize the bean and save the bean using the bean's persistence property.
Introspection
Java Bean API and Important Classes and Interfaces
Normally, several beans are developed by programmers and the third part by developers. In order to reuse them in your applications, you need to know these properties. Hence, these are provided. We can summarize the java beans as:
Let us attempt our first bean example. In this example, the instructor welcomes the class. For this, he calls the beans adds, his own message, and fires the beans. It is a traditional welcome students example, used here to highlight the procedures involved. For executing beans programs you will need a good builder toll like NetBeans 6.1, free downloadable from the net or enterprise version of eclips that supports beans components. For our example, we have chosen NetBeans 6.1. The concept diagram is shown in Figure 24.6.
Example 24.20: Welcomebean.java A Java Beans Example to Demonstrate the Use of NetBeans and Beans Components
We have to use jsp connection because html file is not allowed to call any server components like beans directly. JSP in turn calls for Bean component registered with server like WelcomeBean class. WelcomeBean class is from a normal java class program.
In an application that does not require any input from html form from the user, you can directly start with jsp module and call class file.
Step 0: install NetBean 6.9 version from the net on to your system. Choose the version with full features.
Step 1: Create a new project
FileNew-javaWeb--webapplication1nextnext-GlashFishServer next-Finish.
Step 2: Create Welcome.html file
WebApplication1 webpage Rightclick-newhtmlfileenter in name field :Welcome -finish
1. <html>
2. <body>
3. <form method=post action=Welcome.jsp>
4. <input type=text name=’text1’>
5. <input type=submit>
6. </form>
7. </body>
8. </html>
Line No. 3: | html file calls Welcome.jsp. |
Output of html
Step 3: Create a jsp file
WebApplication1 webpage Rightclick-new JSP enter in name field :Welcome -finish.
Welcome.jsp
1. <%--
2. Document : Welcome
3. Created on : 14 Jan, 2011, 6:28:39
4. Author : Ramesh
5. --%>
6. <%@page contentType=”text/html” pageEncoding=”UTF-8”%>
7. <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 01 Transitional//EN”
8. “http://www.worg/TR/html4/loose.dtd”>
9. <html>
10. <head>
11. <meta http-equiv=”Content-Type” content=”text/html; charset= UTF-8”>
12. <title>JSP Page</title>
13. </head>
14. <body>
15. <jsp:useBean id=”Welcomebean” class=”jchap24beans.Welcombean” />
16. <%
17. String stg = request.getParameter(“text1”);
18. String addlstg = Welcomebean.welcomeStudents(s);
19. out.println(addlstg);
20. %>
21. </body>
22. </html>
Line Nos. 1–14: | are NetBeans generated system document information. |
Line No. 15: | Enter user bean id as :”Welcomebean” class = “jchap24beans.Welcombean” /> |
Line No. 17: | uses getParameter(String msg) format to obtain the request of the client and stores it in String stg. |
Line No. 18: | attaches additional string to the String object addlstg by calling a method welcomeStudents(stg) method of Welcomebean class. |
Line No. 19: | sends out addlstg which is concatenated strings comprising clients request + response i.e. Welcome to Java Beans Students! |
Step 4: Create Package
WEB-INF new-java packagejchap24beans save
Step 5: create class
Jchap24beans new-java class-Welcomebean-finish
1. package jchap24beans;
2. public class Welcomebean
3. {
4. public Welcomebean() { }
5. public String WelcomeStudents(String s)
6. {return “Welcome to Java Beans First Programme….”+s; }
7. }
Welcome to Java Beans.Students!
Line No. 4: | Nil argument constructor |
Line No. 5: | defines a bean method: WelcomeStudents() |
Step 6: Save and compile the files in the package.
Step 7: Select Welcome.html file -- rightclick-run the file Output on the browser screen: Welcome to Java Beans Students!
Class Subject Name subject Code
Teacher Code Teacher Name
Roll No Student Name date1 date2 date3……………………date60
18.188.57.172