Monday, 20 July 2015

How to use Error Handlers in Java EE

Client sends a request to the Server for a specific resource. Sometimes it is possible that due to one or another reason server sends an Http status code (related to error) to the client, instead of actual response to the client.

In Java EE it is possible to redirect or show a specific error page as and when any particular error message comes up.

There are two simple steps to be performed for "Error Handlers"

1) Modify web.xml (deployment descriptor) file to add "Error Handlers"
2) Add a JSP to be shown when an error occurs
3) Run and Verify

Here are the detailed steps:

1) Modify web.xml (deployment descriptor) file to add "Error Handlers"

<error-page>
        <error-code>404</error-code>
        <location>/login/errors/pagenotfound.jsp</location>
</error-page>

Here, we have configured "Error Handler" for the Http status code "404". It is the code for the resource not found. As and when we hit the URL or request for the
resource which server can not find at that time server will return Http status code "404".

2) Add a JSP to be shown when an error occurs

Whenever server sends 404 error code at that time JSP available inside folder "WebContent/login/errors/pagenotfound.jsp" will be shown to the user instead of technical message
which layman user can not understand.

In our case we have written a message "Hey requested resource not found"

3) Run and Verify

Once above steps are done just Build and deploy your application on the server. To understand the difference quickly lets look at the two snaps when we hit
URL "http://localhost:8080/student/MyLogin"

Before "Error Handlers"



After "Error Handlers"




Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

No comments:

Post a Comment