Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to handle Exception in JSP Page

In this article, we will discuss how a JSP page handles exception at run time. We will see how to handle it in some of the scenarios where generally exception occurs.

Introduction

An exception in any programming language is a situation which causes disruptions in the normal execution flow of the program. Some of the scenarios where generally exception occurs are :

  • trying to connect to a database which doesn't exist
  • trying to access a file on the disk and the file is not available
  • trying to connect to the service layer and the layer is not available etc.

Exception handling is the process to handle these (or more) unforeseen situations at runtime. Similar to a java program, these exceptions can occur in JSP pages as well. An efficient way of handling exceptions in JSP pages is to redirect the user to a standard error page. In JSPs there are multiple ways to handle the exceptions :

  • using errorPage and isErrorPage attribute of page directive.
  • using <error-page> element in the web.xml file.
  • using java scriplets within a jsp file.

Handling Exceptions using page directive

In this approach, we should define a jsp page to handle the exception. In our example, our exception handling page is - error.jsp. The jsp where the exception might occur should have defined the error page attribute of the page directive. In our case this is done in process,jsp file.

Listing 1: Index.jsp file - Sample file to take user input

<form action = "process.jsp" >
<h3> Devide the first number by 2nd number </h3>
Number 1 : <input type = "text" name="n1" /> <br/> <br/>
Number 2 : <input type = "text" name="n2" /> <br/> <br/>
<input type="submit" value="Compute"/> </form>

Listing 2: process.jsp file - Sample file to process user input

<%@ page errorPage = "error.jsp" %>
<%
	String num1 =request.getParameter( "n1" );
	String num2 =request.getParameter( "n2" );
	int a = Integer.parseInt(num1);
	int b = Integer.parseInt(num2);
	int c = a/b;
	out.print( "division of numbers is: " +c );
%>

Listing 3: error.jsp file - Sample file to catch the error

<form action = "index.jsp" >
<%@ page isErrorPage = "true" %>
<h3>Sorry an exception has occured!</h3>
Exception is: <%= exception %> <br/>
<input type="submit" value="Re-Compute"/> </form>

Listing 4: The web.xml file - Contains the first page

<?xml version="1.0" encoding="UTF-8"?>

<web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee "
	xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance "
	xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >
	<welcome-file-list>
		<welcome-file> index.jsp </welcome-file>
	</welcome-file-list>
</web-app> 

As we see in the web.xml file, the application starts by loading the index.jsp file. This page comes out as :

the index.jsp file loaded.

Figure 1 : the index.jsp file loaded.

Once the user inputs two numbers in the text box provided, and hits the compute button, the process.jsp file is invoked from here. Based on the input given by the user, the process.jsp either produces a result or an error page as under :

result page for user inputs - 36 & 3. This shows the result as 12.

Figure 2 : result page for user inputs - 36 & 3. This shows the result as 12.

If the user enters invalid inputs e.g. an alphanumeric value in any of the fields, the process.jsp results into the following output page :

an exception has occurred as the user has entered a text instead of numeric value.

Figure 3 : an exception has occurred as the user has entered a text instead of numeric value.

Here the user enters a text - 'dfg' in the divisor field. The application is unable to parse the string 'dfg' into a numeric value. If the user enters zero - 0 in the divisor field the output is as under :

an exception has occurred as the user has entered '0' in the divisor field.
Figure 4 : an exception has occurred as the user has entered '0' in the divisor field.

Any uncaught exception which is thrown in the body of a JSP page is forwarded to the errorPage URL which is specified by the JSP page directive. For example:

<%@ page errorPage = "error.jsp" %>

The above code redirects the browser to the JSP page error.jsp if an exception occurs while the request is in process. The error jsp page should indicate that it an error page by setting the isErrorPage attribute to true. In the above example, the error.jsp page indicates that it is an error processing page via the directive:

<%@ page isErrorPage="true" %>

In this case, exception implicit scripting language of this page, is initialized to the java.lang.Throwable reference. The following points should be kept in mind while using the page directive approach:

  • The developer must always use a relative URL as the value for the errorPage attribute in the page directive.
  • If the autoFlash is set to true by setting
     autoFlush=true 
    then, if the contents of the initial Jsp-Writer has been flushed to the ServletResponse output stream then any subsequent attempt to dispatch an uncaught exception from the offending page to an errorPage may fail.
  • If the error page is also indicated in the web.xml descriptor, the JSP error page applies first, then the web.xml.

Handling exceptions using error-page element in the ‘web.xml’ file

This approach is better as the user doesn't need to use the page directive to declare the error page in each jsp file. Making a single entry in the web.xml file serves the purpose. We can either specify the exception type or the error code with the location element. If we want to handle all the exceptions we need to specify the java.lang.Exception in the exception type element. The web.xml file for each of these cases is given as under :

  • web.xml file which handles any type of exception

Listing 5: Sample file to handle any type of exceptions

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<error-page>
		<exception-type> java.lang.Exception </exception-type>					<location> /error.jsp </location>
	</error-page>
	<welcome-file-list>
		<welcome-file> index.jsp </welcome-file>
	</welcome-file-list>
</web-app>

web.xml file which handles the exception for a specific error code:

Listing 6: Sample file to handle specific error

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<error-page>
		<error-code> 500 </error-code>
		<location> /error.jsp </location>
	</error-page>
	<welcome-file-list>
		<welcome-file> index.jsp </welcome-file>
	</welcome-file-list>
</web-app>

index.jsp and the error.jsp files are exactly the same as in the above sample. process.jsp is slightly different from the one above. This is as under :

Listing 7: Sample calculation

<%
	String num1 = request.getParameter("n1");
	String num2 = request.getParameter("n2");
	int a = Integer.parseInt(num1);
	int b = Integer.parseInt(num2);
	int c = a / b;
	out.print("division of numbers is: " + c);
%>

As we can see here the process.jsp file does not need to declare the page directive - errorPage with @page tag.

Handle exceptions using scriplets

This approach is the traditional way of handling exceptions. This is not considered to be the best way of handling exception but used in case fast debugging is required. In this approach the developer can simply use the try ... catch .. format within the jsp file. A sample is shown as under :

Listing 8: Sample code to handle exception using scriptlet

<%
try{
	String num1 = request.getParameter("n1");
	String num2 = request.getParameter("n2");
	int a = Integer.parseInt(num1);
	int b = Integer.parseInt(num2);
	int c = a / b;
	out.print("division of numbers is: " + c);
} catch (Exception ex) {
	out.println("An exception hs occurred - " +ex.getMessage());
}
%>

Conclusion

In any programming language, exception is the event which indicates that some has gone wrong with the execution of the program. An exception changes the flow route of the program. A JSP page handles exceptions in the following ways :

  • using errorPage and isErrorPage attribute of page directive.
  • using <error-page> element in the web.xml file.
  • using java scriplets within a jsp file.

The java.lang.Throwable class is initialized when there is an exception which is handled using the page directive.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login