In this session, let us learn how to handle exceptions in a spring MVC application. Spring Exception Handling can be done in four ways. You will think Harmer exception resolver controller based exception handler, response status and global exception handler. To start with in this particular session, we will see how to handle exception using handler exception resolver interface and controller based exception handler handler exception resolver. This is an interface. With the help of this interface, we can handle the custom exceptions that occur in a spring MVC application.
For this, we need to create our own class which implements handler exception resolver. And you need to override the small exception method within which you can say When an exception occurs, what has to happen? Now, what actually I have given over here is I am just telling retrieve the exception that has occurred in a spring MVC application and pass it to a view page, the view pages era dot JSP. The name of the model name is message what actually is having the exception what exception has been, I mean what exception has occurred, that message we are passing on to the view page. This is using handler exception resolver next controller based exception handler. What is this?
If you want to handle exceptions for a particular controller, in that scenario, you need to go in for controller based exception handler. That is, you create a method within that controller itself. annotate a method with exception handler at the rate exception handler whenever an exception occurs In that particular controller, it will be handled by this method. Either you can handle all the exceptions of that controller in that method or a specific exception in that method. Well, what will be the return type, either you can just return a JSON view of error messages are you can just return redirect your page to another page that also is possible. In a single controller.
You can have any number of methods that are annotated with exception handling exception handlers to handle specific exceptions. Say for example, name not found exception, invalid name exception. I mean city not found exception. If you want to ask specific exception handlers for that particular handler controller, you can add it in that controller itself. What is the limitation of this? If an exception occurs in any other controller You will not be handled by these exception handlers, because they belong to this controller only.
Now, we will learn how to use handle exception resolver and controller based exception handler. Let me go back to eclipse. I'm an eclipse I have created a spring MVC application using spring boots, the application name of spring MVC exception. Here I have done the initial setup for working with the application. The first thing is the application class, which is extending Spring Boot servlet initializer. Then inside the controller package, I have got user controller inside the model class I have got user user is not annotated with at the rate component.
And to play with that I've got few JSP pages inside views. Let us see the flow. Once the application starts automatically to come to user controller because of the flat and from here and going into this home that JSP In Home dot JSP I am having a simple link, which is calling show from. From here again I'm going to this user controller in the user controller, I'm having another method which is calling for show form, which is requesting for show form. I here I have added the HTTP method as get just to show you that you can add the method also in request mapping. In this case, if you see I am trying to create a user object why because we are not added added component annotation about the user class it means that you are creating the user objects all by yourself and giving it to spring.
Spring has to retrieve the user object using this dummy name and then only call the setter method when you are using model attribute. That is the next method. Okay, so what is the return type? It is user from the JSP and going into this user form dot JSP. Here I've got name ID and city. What are the Names of the form fields user name, ID and city, I need to create a user class with these three as instance variables.
So I have a user class with these three as instance variable getter and setter methods. This has completed I'll again come back to user controller wherein we are trying to call Add User method. Okay, and here I'm returning success bar and I am trying to get the user object. First let us try running this application. So this is a very basic application without any exception. Katana started, this is homepage.
Let me click this. This is user form dot JSP. Let me add some values. Click Add User. This is success dot JSP. This is working perfectly fine.
Now we are going to create custom exception and handle the exception using handle exceptions the solver interface. So for this, I'm going to assume controller, let me add some logic inside this here I am going to have an array what actually I am going to do is I am going to check if the user name is available in this particular array then it must not throw an exception it has to go to success dot JSP if the user name is not available in that array then it has to throw a name not found exception. So, let me write the logic I have written the logic I have created a user array and I trading through the user array to check whether the user name is available. If the name is available, he is already registered. So, you can log in and go to the next page to success dot JSP.
If the name is not available, in that scenario, it has to throw an exception name not found exception. So, again let me just go and continue with the logic you not flat Throw a new name not found exception, I don't have the exception I need to create it. It's giving me an error. Let me just keep the cursor here and create the class been imported already there is an exception as name not found exception in Java dot naming package. We are going to have this exception our own custom exception. So click this and select the second one create class name not found exception, we need constructor.
So selected click finish, we need only the first and second constructor, rest of the things are not needed. So I'm just removing it off. Still I will be having exception in user controllers. Because your method is throwing a custom exception you need to either handle it or declare it in the method. We are going to declare it using throws keyword and keep the cursor here add throws declaration throws name not found exception. So if the user name is not available, this method is going to throw an exception, we need to handle it and send it to an exception page.
So let me create a new class which implements handler. Exception resolve. Yeah, handler. Exception resolver. The package exception, the class name of my exception handler. Click Finish.
This class should implement handler exception the solver. Control space just give automatically we'll get it next keep the cursor and add on implemented methods that is resolve exception method. It is having four parameters HTTP servlet. request, response object and exception. Let me just change the parameters. Within this, I need to retrieve what exception has occurred.
So it's exception is equal to UI dot get message. And I need to return a model and view object return new model and view which takes three parameters. Either you can just set all the I mean, you can create a model and view object inside the method, set the view name set the message and then return us some dummy object that also is fine. I mean return the object that also is fine. So first parameter is the view name. The second parameter is the message and the third parameter is the exception object.
Okay, so for this I need to create era dot JSP inside views, so let me just add it, I will just copy paste at home dot JSP Ctrl V and give the name of Sierra dot JSP era dot JSP ready wherein I don't need this night. Simply I'm just going to have a message. Okay, so what does Message whatever you are going to have after that name not found exception we have not given anything over here. So, in user controller I can do have a parameter username does not exist okay this is the message that you will be getting in error dot JSP okay this is completed this actually is a beam, this beam should be created by the container for that you have to either go in for a direct component annotation above this class or you can create it ourselves being using Java based configuration.
I am not going to use at the rate component I am going to create it as a beam inside the application class. So, let me open this application class spring MVC exception application okay how to create it? First let me add the method public handle exception the solver exception handler I need to return I mean I myself I am creating an object. I don't want spring to create an object. So, I am creating an object for exception handling and I need to annotate it with at the rate beam okay. So, this spring bean is also ready, I hope we have completed everything what actually we have done is we are explicitly creating an exception in the user controller class.
And when an exception occurs, it must not throw an exception to the browser. Instead of that the exception must be handled, which class is responsible for handling the exception the class that implements handling exception resolver. So, we are created a class and we have registered that as a beam in the application class. This is done let me run this application. Now application has started. Let me just click this.
I need to give a different name which does not Texas click Add Users username does not exist. It means that this class is handling the exceptions and throw a try means showing a user friendly error page there are pages error dot JSP Baron we are printing the error message user name does not exist. So, this is how you use handler exception resolver to handle the exception. Next, let us see how to handle the exception using controller based exception handler for the later method that is annotated with accurate exception handler, public string handle exception This is this should be annotated with adequate exception handling. If you want to handle specific exceptions, you can just pass this parameter value equal to name not found exception But now, in this method, I can create a model map. And also I can just pop on the exception message a message here what I have to return again, I can return return that view page name, I can directly say return error.
What happens when an exception occurs automatically it will be taken to era dot JSP. wherein you are showing to the user that username does not exist, how to come back to the user form, you need to have a link so that when the user clicks that link, he can come back to the user from internet that's what I'm going to do. I'm just going to send the user directly to user form dot JSP. Okay, this is fine, perfectly fine. But there is a problem over here. When you go to user form dot JSP.
When the user is entering all the details when he clicks Add User button, your user object should be created and the value should be populated. If you are using Are the red component annotation in that scenario the user objects will be created by the IOC containing by by spring, but in this case you are creating the object explicitly you can just have a look I am creating the object explicitly. So, what is the meaning it is necessary that I need to come back to this method from the handle exception method how to do I am just going to use redirect it to something like redirect colon slash show from I hope you can understand what actually we are doing is we are redirecting this is kind of a URL, we are redirecting to a method that is annotated with show form this is not the JSP page name okay.
So, this is done now. Okay, so, what actually we have done we have created a method that is annotated with at the rate exception handler to handle the exception that is occurring in this particular controller in the country. Lola we are throwing name not found exception. Let me run this application. The application has started let me click the link. Click Add User.
Now you can see it is staying in the same page only because you have redirected. Now I will open the console. I will maximize the console. You can see the output the last line you will be seeing the exception but we have not used any logger. That's why we are not seeing the exception. I will show you how to add a logger.
We have learned about love but love to see default logger framework for spring. So we will be using log back only together with a DSL for using a logger. You can just show the message over here. Like username does not exist. I hope you understood how to handle exception using a controller based exception handlers. In the next session, let us learn how to handle exception using response status and global exception handler.
Together with that I will also show you how to add the logger message so that it will be displayed in the console. Thank you