Java Server Pages - Exception Handling in JSP Pages, Accessing Database from JSP, Predefined Variables in JSP, Syntax Summary
Exception Handling in JSP Pages |
What are Exceptions? |
Exceptions mean exceptional events and as we all know exceptional events can occur anywhere in a program e.g. we are trying to connect to a database and the database server is down, now we wouldn't have expected this to happen. |
How to catch Exceptions? |
We can catch exceptions in a JSP page like we would do in other Java classes. Simply put the code which can throw an exception/s between a try. Catch block. |
<% try { // Code which can throw can exception } catch(Exception e) { // Exception handler code here } %> |
There is yet another useful way of catching exceptions in JSP pages. |
We can specify error page in the 'page' directive. Then if any exception is thrown, the control will be transferred to that error page where we can display a useful message to the user about what happened and also inform our sysadmin about this exception depending obviously on how important it may be. |
Building the Demo Pages |
To demonstrate the run-time exception handling feature of JSP pages, we will build three pages: |
• Form.php - Display a Form to the user to enter his or her age. • FormHandler.jsp - A JSP Page which receives this value and prints it on the user screen. • ExceptionHandler.jsp - An exception handler JSP page which is actually an error page to which control will be passed when an exception is thrown. |
Form.jsp |
Create a new Form.jsp page. Copy the following code and paste it into the Form.php page : |
<html> <head> <style> body, input { font-family:Tahoma; font-size:8pt; } </style> </head> <body> <!-- HTML Form --> <form action="FormHandler.jsp" method="post"> Enter your age ( in years ) : <input type="text" name="age" /> <input type="submit" value="Submit" /> </form> </body> </html> |
Explanation |
Form.php page simply displays a single input field Form to the user to enter his age in years. The name of input field where user will enter his/her age is "age". We will use this input field name "age" in the FormHandler.jsp page to receive it's value. |
Output: |
FormHandler.jsp |
Create new FormHandler.jsp page. Copy and paste the following code in it : |
<%@ page errorPage="ExceptionHandler.jsp" %> <html> <head> <style> body, p { font-family:Tahoma; font-size:10pt; } </style> </head> <body> <%-- Form Handler Code --%> <% int age; age = Integer.parseInt(request.getParameter("age")); %> <%-- Displaying User Age --%> <p>Your age is : <%= age %> years.</p> <p><a href="Form.php">Back</a>.</p> </body> </html> |
Output: |
Explanation |
Code above is rather simple. Notice the first line, the page directive. It specifies an errorPage ExceptionHandler.jsp, our exception handler JSP page. |
<%@ page errorPage="ExceptionHandler.jsp" %> |
Then we declare an int variable "age". Then using the static method of Integer class we parse the entered value using Integer.parseInt() method. The value is retrieved using request.getParameter() method. The argument to request.getParameter() is the name of Form field whose value we want to retrieve. |
<% int age; age = Integer.parseInt(request.getParameter("age")); %> |
If all goes well and user entered an int ( e.g. 12345 ) value in the input field then we display that value back to the user. |
<p>Your age is : <%= age %> years.</p> |
Now things can go wrong and exceptional events can occur. For example, if user didn't enter a value and what if user entered his name ( e.g. "Aman Kumar"), of String type instead of an integer ?. |
These things will be handled by the ExceptionHandler.jsp JSP page. |
ExceptionHandler.jsp |
Create a new ExceptionHandler.jsp page. Copy and paste the following code in it : |
<%@ page isErrorPage="true" import="java.io.*" %> <html> <head> <title>Exceptional Even Occurred!</title> <style> body, p { font-family:Tahoma; font-size:10pt; padding-left:30; } pre { font-size:8pt; } </style> </head> <body> <%-- Exception Handler --%> <font color="red"> <%= exception.toString() %><br> </font> <% out.println("<!--"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); out.print(sw); sw.close(); pw.close(); out.println("-->"); %> </body> </html> |
Output: |
Explanation |
To make a JSP page exception handler ( i.e. errorPage ), we have to specify isErrorPage attribute in the page directive at the top and set it's value to true. |
<%@ page isErrorPage="true" %> |
When a JSP page has been declared an errorPage, it is made available an object with name of "exception" of type java.lang.Throwable. We use different methods of this exception object to display useful information to the user. |
<font color="red"> <%= exception.toString() %><br> </font> |
We can put the stack trace information for debugging inside HTML <!-- --> comment tags. So that user only sees a useful message and the sysadmin, developers can see the whole things. |
<% out.println("<!--"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); out.print(sw); sw.close(); pw.close(); out.println("-->"); %> |
To use the PrintWriter and StringWriter classes we'll have to import java.io.* package in our JSP page by changing the page directive at the top to : |
<%@ page isErrorPage="true" import="java.io.*" %> |
Running the Demo Pages |
Place Form.php, FormHandler.jsp and ExceptionHandler.jsp pages in a place where our application server ( e.g. Tomcat, Orion etc ) can find them. Never put our JSP pages in the /WEB-INF/ folder. |
We placed these three pages in the /web/jsp/ folder so the path to these pages on my system will be http://localhost:8080/web/jsp/Form.php and so on. Notice that on our system application server is running on 8080 port. We should change the port number to the one where our application server is running. |
Enter your age e.g. 24, in the input field and press the submit button. We should see FormHandler.jsp page giving us a response like following : |
Your age is : 24 years. |
Now try again. This time don't enter any value or simply enter a non-integer value e.g. your name, and press the submit button. Now instead of FormHandler.jsp page showing us your age, the control will be internally passed to ExceptionHandler.jsp page which will show an exception message in red color : |
java.lang.NumberFormatException: |
To see the complete stack trace view the source of the page. On Internet Explorer, click View -> Source. On the source page you will see complete exception stack trace written. |
Although our demo application worked and we learned about specifying error pages e.g. ExceptionHandler.jsp, in our normal JSP pages e.g. FormHandler.jsp, there is still a catch. The exception message that was given to the user i.e. java.lang.NumberFormatException, is not very useful, is it? To give a more useful message keep reading. |
Improved FormHandler.jsp page |
Remove the FormHandler code in FormHandler.jsp page and add the following one : |
<% int age; try { age = Integer.parseInt(request.getParameter("age")); } catch (NumberFormatException e) { throw new JspException("Please enter a valid integer value!"); } %> |
Explanation |
This time we catch the NumberFormatException locally and throw a new JspException with our own exception message. JspException is a JSP special exception class which extends java.lang.Exception. So all we had to do is to give our own message to the JspException class. Now lets see what will happen this time. |
We will just have to edit one single line in ExceptionHandler.jsp for it to work. |
Improved ExceptionHandler.jsp |
Simply change the exception handler code with this one : |
<font color="red"> <%= exception.getMessage() %><br> </font> |
That's it. Now view the Form.php page again and don't enter any value and press the submit button. |
This time we will not see "java.lang.NumberFormatException", rather the message will be : |
Please enter a valid integer value! |
And like before we can see the complete stack trace by viewing the source for the FormHandler.jsp page in your browser. |
Accessing Database from JSP |
Introduction |
In this object we are going to discuss the connectivity from MYSQL database with JSP. |
take a example of Books database. |
Book database contains a table named books_details. |
This table contains three fields- id, book_name & author. |
First we learn how to create tables in MySQL database after that we write a html page for inserting the values in 'books_details' table in database. |
After submitting values a table will be showed that contains the book name and author name. |
Database | ||||||||||||
The database in example consists of a single table of three columns or fields. The database name is "books" and it contains information about books names & authors. | ||||||||||||
Table: books_details | ||||||||||||
|
||||||||||||
Start MYSQL prompt and type this SQL statement & press Enter- | ||||||||||||
MYSQL>CREATE DATABASE `books` ; | ||||||||||||
This will create "books" database. | ||||||||||||
Now we create table a table "books_details" in database "books". | ||||||||||||
MYSQL>CREATE TABLE `books_details` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT , `book_name` VARCHAR( 100 ) NOT NULL , `author` VARCHAR( 100 ) NOT NULL , PRIMARY KEY ( `id` ) ) TYPE = MYISAM ; |
||||||||||||
This will create a table "books_details" in database "books" | ||||||||||||
JSP Code for connection |
The following code contains html for user interface & the JSP backend: |
<%@ page language="java" import="java.sql.*" %> <% String driver = "org.gjt.mm.mysql.Driver"; Class.forName(driver).newInstance(); Connection con=null; ResultSet rst=null; Statement stmt=null; try { String url="jdbc:mysql://localhost/books?user=<user>&password=<password>"; con=DriverManager.getConnection(url); stmt=con.createStatement(); } catch(Exception e) { System.out.println(e.getMessage()); } if(request.getParameter("action") != null) { String bookname=request.getParameter("bookname"); String author=request.getParameter("author"); stmt.executeUpdate("insert into books_details(book_name,author) values('"+bookname+"','"+author+"')"); rst=stmt.executeQuery("select * from books_details"); %> <html> <body> <center><h2>Books List</h2> <table border="1" cellspacing="0" cellpadding="0"> <tr><td><b>S.No</b></td><td><b>Book Name</b></td><td><b>Author</.b></td></tr> <% int no=1; while(rst.next()) { %> <tr><td><%=no%></td><td><%=rst.getString("book_name")%></td><td> <%=rst.getString("author")%> </td></tr> <% no++; } rst.close(); stmt.close(); con.close(); %> <tr> </table> </center> <body> <html> <%}else{%> <html> <head> <title>Book Entry FormDocument</title> <script language="javascript"> function validate(objForm) { if(objForm.bookname.value.length==0) { alert("Please enter Book Name!"); objForm.bookname.focus(); return false; } if(objForm.author.value.length==0) { alert("Please enter Author name!"); objForm.author.focus(); return false; } return true; } </script> </head> <body><center> <form action="BookEntryForm.jsp" method="post" name="entry" onSubmit="return validate(this)"> <input type="hidden" value="list" name="action"> <table border="1" cellpadding="0" cellspacing="0"> <tr> <td> <table> <tr><td colspan="2" align="center"><h2>Book Entry Form</h2></td></tr> <tr><td colspan="2"> </td></tr> <tr><td>Book Name:</td><td><input name="bookname" type="text" size="50"></td></tr> <tr><td>Author:</td><td><input name="author" type="text" size="50"></td></tr> <tr><td colspan="2" align="center"><input type="submit" value="Submit"></td></tr> </table> </td> </tr> </table> </form> </center> </body> </html> <%}%> |
Explanation of Code |
Declaring Variables: |
Java is a strongly typed language which means, that variables must be explicitly declared before use and must be declared with the correct data types. |
In the above example code we declare some variables for making connection. |
Theses variables are- |
Connection con=null; ResultSet rst=null; Statement stmt=null; |
The objects of type Connection, ResultSet and Statement are associated with the Java sql. |
"con" is a Connection type object variable that will hold Connection type object. |
"rst" is a ResultSet type object variable that will hold a result set returned by a database query. |
"stmt" is a object variable of Statement .Statement Class methods allow to execute any query |
Connection to database: |
The first task of this programmer is to load database driver. |
This is achieved using the single line of code:- |
String driver = "org.gjt.mm.mysql.Driver"; Class.forName(driver).newInstance(); |
The next task is to make a connection. |
This is done using the single line of code :- |
String url="jdbc:mysql://localhost/books?user=<userName>&password=<password>"; con=DriverManager.getConnection(url); |
When url is passed into getConnection() method of DriverManager class it returns connection object. |
Executing Query or Accessing data from database: |
This is done using following code :- |
stmt=con.createStatement(); //create a Statement object rst=stmt.executeQuery("select * from books_details"); |
stmt is the Statement type variable name and rst is the RecordSet type variable. |
A query is always executed on a Statement object. |
A Statement object is created by calling createStatement() method on connection object con. |
The two most important methods of this Statement interface are executeQuery() and executeUpdate(). |
The executeQuery() method executes an SQL statement that returns a single ResultSet object. |
The executeUpdate() method executes an insert, update, and delete SQL statement. |
The method returns the number of records affected by the SQL statement execution. |
After creating a Statement ,a method executeQuery() or executeUpdate() is called on Statement object stmt and a SQL query string is passed in method executeQuery() or executeUpdate(). |
This will return a ResultSet rst related to the query string. |
Reading values from a ResultSet: |
while(rst.next()) { %> <tr><td><%=no%></td><td><%=rst.getString("book_name")%></td> <td><%=rst.getString("author")%></td></tr> <% } |
The ResultSet represents a table-like database result set. |
A ResultSet object maintains a cursor pointing to its current row of data. Initially, the cursor is positioned before the first row. Therefore, to access the first row in the ResultSet, we use the next () method. This method moves the cursor to the next record and returns true if the next row is valid, and false if there are no more records in the ResultSet object. |
Other important methods are getXXX () methods, where XXX is the data type returned by the method at the specified index, including String, long, and int. |
The indexing used is 1-based. |
For example, to obtain the second column of type String, we use the following code: |
resultSet.getString(2); |
We can also use the getXXX () methods that accept a column name instead of a column index. |
For instance, the following code retrieves the value of the column LastName of type String. |
resultSet.getString("book_name"); |
The above example shows how we can use the next() method as well as the getString() method. |
Here we retrieve the 'book_name' and 'author' columns from a table called 'books_details'. We then iterate through the returned ResultSet and print all the book name and author name in the format " book name | author " to the web page. |
Predefined Variables in JSP |
Introduction |
To simplify code in JSP expressions and scriptlets, we are supplied with eight automatically defined variables, sometimes called implicit objects. The available variables are request, response, out, session, application, config, pageContext, and page. |
Different Predefined Variables |
request |
This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter()), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never done in practice. |
response |
This is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client. |
out |
This is the PrintWriter used to send output to the client. However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. |
session |
This is the HttpSession object associated with the request. Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference. The one exception is if you use the session attribute of the page directive to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet. |
application |
This is the ServletContext as obtained via getServletConfig().getContext(). |
config |
This is the ServletConfig object for this page. |
pageContext |
JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher performance JspWriters. The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines. |
page |
This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the time when the scripting language could be something other than Java. |
Syntax Summary | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Syntax Summary | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Post a Comment