Tuesday, October 26, 2010

02 TGMC - Talking to the Data Base



Now that we know how to create a new web application. Lets go a step further, see if we can interact with the database. In this exercise, we'll build a simple app where we enter details of a student and try to retrieve the data that we just entered.

Before we get started with the actual app development, lets first install IBM DB2 (alternatively if you just want to learn how to build an app you can try installing MySQL).

Note: IBM DB2 Express C 9.5 has compatibility issues with Windows Vista and Windows 7. So I suggest you download the latest version of DB2 Express C 9.7 here, which is working fine on my windows 7 machine.

Step 1:

Now, we need create a sample database, with a database name say "Exercise" and then create a table, say "Student". Here I am assuming you have basic knowledge of DBMS.  If not, you can go through a couple of basic tutorials on

Lets create the table "Student" with the following fields in DB2.

Field          Datatype
USN    VARCHAR(10)
Name    VARCHAR(25)
Semester    INTEGER
Branch    VARCHAR(10)
DOB    DATE 

Now, once DB2 is installed on your system, go to "Control Center" from the Start Menu, and you will get to see the following program.


Now, click on "All Databases", and create a new "Standard Database" and mention the db name. After that you can see that a new Database that you created can be seen on the left, under "All Database".

Now, choose the create a new table option and create the table named " Student" with the fields as mentioned above. You can either use the GUI to create the table, or use the command editor, where you can type the SQL commands to create the table as follows:


CONNECT TO EXERCISE;
CREATE TABLE STUDENT(
USN VARCHAR(10) NOT NULL,
NAME VARCHAR(20) NOT NULL,
SEM INTEGER NOT NULL,
BRANCH VARCHAR(10),
DOB DATE,
PRIMARY KEY(USN));
Now, we are done with the creating the database and a table in the db which we shall be using to insert data and retrieve from.

Step 2:

Once we are done creating a new database, now like we did in the first exercise, create a new Dynamic Web Application and call it, "Exercise2". Once you are done with creating a new web application, and setting the runtime server as WASCE (refer to the earlier post to know how to do it).



Now lets create the JSP with a name "AddStudentDetails.jsp", which has a form to enter the details of a student which will be entered into the database. Again, for which right click on your project in the Project Explorer and choose New->Web->Jsp, and enter the name and click ok. A new jsp with the mentioned name would be placed in the "Web Content" folder.

 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ExerciseTwo: Add Student Details</title>
</head>
<body>
<h2 align="center">02 TGMC: Talking to the Database</h2>

<fieldset><legend style="size: 10px;">Add Student Details</legend>
<form action="SubmitStudentDetails.jsp">
<table align="center" width="50%" border="1" bordercolor="GRAY">
 
<tr>
 <td width="15%" style="padding: 3px">USN :</td>
 <td width="35%" style="padding: 3px"><input type="text" name="usn"/></td>
 </tr>
 <tr>
  <td style="padding: 3px">Name :</td>
  <td style="padding: 3px"><input type="text" name="name" /></td>
 </tr>
 <tr>
  <td style="padding: 3px">Semester :</td>
  <td style="padding: 3px"><input type="text" name="sem" /></td>
 </tr>
 <tr>
  <td style="padding: 3px">Branch :</td>
  <td style="padding: 3px"><select name="branch">
   <option value="CSE">CSE</option>
   <option value="ISE">ISE</option>
   <option value="ECE">ECE</option>
  </select></td>
 </tr>
 <tr>
  <td style="padding: 3px"> Date of Birth :</td>
  <td style="padding: 3px"> <input type="text" name="dob"/> 
MM-DD-YYYY </td>
 </tr>
</table>
<br/>
<div align="center"> <input type="submit" value="Add Student Details"/> 
              <input type="reset" value="Clear"/>
</div>
</form>
</fieldset>

</body>
</html>

With the above code in the "AddStudentDetails.jsp", when the server is run, we get the following page on the browser.


After the form is done, now we need to create another jsp, which gets the called on clicking the "Add Student Details Button". Lets call the second jsp as "SubmitStudentDetails.jsp", where we make the database connection and add the form values.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1" import="java.sql.*;"%>

<%

Connection con = null;  // Create an object of Connection class
String url = "jdbc:db2://localhost:50000/"; // The Database url
String db = "Exercise"; //Database Name
String driver = "com.ibm.db2.jcc.DB2Driver"; // Database driver for DB2
String user = "db2admin"; //DB2 Username
String pass = "admin"; //DB2 Password

try
{
 //To Establish Database Connection
 Class.forName(driver).newInstance();
 con = DriverManager.getConnection(url+db, user, pass);
 
 // Obtain the student details from the form
 String strUsn = request.getParameter("usn");
 String strName = request.getParameter("name");

 // Converting the String to Integer Type
 int strSem = Integer.parseInt(request.getParameter("sem"));
 
 String strBranch = request.getParameter("branch");
 String strDob = request.getParameter("dob");

        //Insert query to enter the details to database
 String query="INSERT INTO DB2ADMIN.STUDENT (USN, NAME, SEM, BRANCH, DOB) 
VALUES('"+strUsn+"','"+strName+"','"+strSem+"','"+strBranch+"','"+strDob+"')";
 
con.setAutoCommit(false);
 
PreparedStatement ps = con.prepareStatement(query);
 
 int rowsUpdated = ps.executeUpdate();
 
    // Condition to check if there was any data inserted to the db
if(rowsUpdated>0){%>

<h2>Student Details Inserted successfully! :)</h2>
<% }
 else{%>
<h2>Operation Failed!! :( :( <br />
Check the Stack trace to identify the mistake!! :-)</h2>
<%} 
 // Commit the changes
 con.commit();
 
 // Close the connection
 con.close();
 } 
 
 // Handle the Exception
 catch (Exception e) 
 {
  e.printStackTrace();
  System.out.print(e.getMessage());
 }
%>

Now, we are ready to test out our application. Just right click on the project and Run on Server.
.
.
.
.
.
I'm sure if you had run the project, you mostly encountered an error! Which is a good sign, coz it helps to learn things better! :)
And the error would be certainly, "Class Not Found Exception" pointing to the Database driver that you have mentioned in the SubmitStudentDetails.jsp.. Thats because we haven't added the database driver Jar file.

To add the driver jar files to the project all you need to do is, right click on the project ->Build Path -> Configure Build Path -> Add External Jars. Here browse to the location where you have installed IBM DB2 and find the following 2 jars and add them.

1. db2jcc.jar
2. db2jcc_ license_cu.jar

Once you've done this, I guess there shouldn't be any more problems. Once u enter the details in the form and hit "Submit" if everything goes right, you must be seeing the following screen..


Hope you could understand the various concepts involved, we have completed only a part of the exercise that we set out to do. We have entered the details into the database, the next thing we need to do, is retrieve the data from the data base and display it on a page. I'll be teaching you how we can do that in the next blog post. By then you can try it out yourself. Just in case you get lost, download the project from one of the below locations.


For any assistance you can leave a comment or send out a mail to  [ voidpointers@gmail.com ].

Try out some more samples which you can find at http://roseindia.net. Happy coding.. We'll be back with the next exercise very soon.!

Cheers! :)

Wednesday, October 13, 2010

01 TGMC : The Starting Problem

Starting with this, there would be a series of posts that would try to help students who are looking to participate in IBM's The Great Mind Challenge. One of the biggest software development contest at present.

For those who have no prior knowledge of how to build a software application, your journey of Enterprise application development starts here and we hope to make it as easy and comfortable as possible. :)

Assuming the readers have some basic knowledge of core java and HTML, we are now ready to build our first simple "HelloWorld" application.

Software Required:

1. IDE - Eclipse
2. Application Server - IBM WASCE / Apache Tomcat 6.0
3. RDBMS - IBM DB2
3.Text Editor - NotePad++ (a good text editor that could come handy)
4. jdk 1.5 or above

Step 1:

Install the software mentioned above, which can be obtained online or from the DVD ( excluding NotePad++ which needs to be downloaded) provided by IBM to your college. We would not need IBM DB2 for this exercise, we shall see how to work with DB2 in the coming posts.

Eclipse does not require a installation, all you need to do, is extract the compressed file to an appropriate location and choose a "workspace" where you would be placing all the projects.

Step 2:

So, we are all set to get started with Eclipse, to build our first Hello World web application.

Now, to create a new project, Click on File -> New -> Web -> Dynamic Web Project


On choosing which, you will be asked for a project name, give a name of your choice say, "HelloWorld".

The next thing we are supposed to do is set the "Target Runtime" , i.e, on which application server would we be running the web application. In this case we need to set it to IBM WASCE.
Clicking on "new" would give us the following dialog box.

Choose IBM WASCE v2.0 and click next, where it asks for the Server installation directory. Point it to the location where you installed the Wasce app server on your machine and say "Finish" to set up IBM Wasce app server on Eclipse.


Step 3:

Once we are done with setting up the runtime server, now we need to create the first jsp, for that, right click on your project in the Project Explorer, and create new JSP with a name say, "welcome.jsp" and assuming you have some basic knowledge of HTML, we just add a simple header tag, which says "Hello World!!".

Then before we can run this application, we need to do a small check with the web.xml file that, u can find at ../WEB-INF/web.xml

By default in the web.xml file you can find that the default welcome page (that is the page which is displayed once the application is started) is set to "index.html/index.jsp" since, we created a jsp with the name "welcome.jsp" we need to edit the web.xml file, and set "welcome.jsp" in the welcome-page list as shown in the figure below.

Once you have done this, we are ready to run the application.

Step 4:

Now to run the application, right click on the project in the project explorer, and choose Run-> Run on Server option.


On clicking which, the server startup is initialized, be patient, the server takes a little time to start up, but once its done you can see the following message on the console window.


Immediately after the server startup is completed, an Internal Web Browser is started, and the application's welcome page is displayed. (You can set the default web browser at your default web browser, eg. IE or firefox). To do that click on the Window-> Web Browser from the menu bar and set the web browser of your choice.


As you can see, the welcome page displaying "Hello World" is obtained on the internal web browser.

So, Congratulations you have just successfully created and deployed your first web application!! :)

Our next post would be on Database Connectivity, which is coming soon.