How to Handle Error in Web.xml for Java Web Applications

Hello friends, Today I will show you how to handle the error or display customized error messages in JSP and servlet. This example will display the personalized error messages on the JSP pages.

In the web.xml page, we can add the definition of the different errors and display the error page based on the error that occurred.

To do that, go to src => main => web app and create a folder like errors. Basically in this folder, we add the different customized error pages.

To demonstrate, I have created two JSP pages 404.JSP and 500.JSP page.

404.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>404 Error - Page Not Found</title>
</head>
<body>
	<center>
		<h1>Sorry, the page you requested were not found.</h1>
	</center>
</body>
</html>

500.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>500 Error - Server Issues</title>
</head>
<body>
	<center>
		<h1>Sorry, there were server issues</h1>
	</center>

</body>
</html>

You can create as many error pages as your need. so far I have created only two pages only.

Now, it’s time to handle and configure this error page and how it will display. To do that go to src => main => web app => WEB_INF => web.xml.
Open this web.xml file and configure it this way.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	id="WebApp_ID">
	<error-page>
		<error-code>404</error-code>
		<location>/errors/404.jsp</location>
	</error-page>
	<error-page>
    <error-code>500</error-code>
    <location>/errors/500.jsp</location>
</error-page>
</web-app>

<error-page> is used for indicating that is an error page and within this tag <error-code> is used for specifying the corresponding error and <location> is used for mainly telling which page will be displayed based on the error.

Hope it makes sense!

Leave a Reply