91-9990449935 0120-4256464 |
Struts 2 Exception Handling - exception interceptorIn our web application, there might occur exception at any point. To overcome this problem, struts 2 provides a mechanism of global exception handling where we can display a global result to the user. Struts 2 automatically log the uncaught exceptions and redirects the user to the error handler page. Understanding the internal working of exception interceptorIf there occurs exception, it is wrapped in ExceptionHolder and pushed in the valuestack so that we can easily access exception object from the result. It is recommended to make this interceptor as the first interceptor, so that it can handle all the exception whether it is thrown by other interceptors.Parameters of exception interceptorThere are 3 parameters defined for exception interceptor. All are optional.
Example of exception handling in struts 2For exception handling, we specify the global-result and global-exception-mappings in the struts.xml file. struts.xmlThe global-results sub-element of package specifies the global-result for this package. The result sub-element of global-result specifies the result page that will be rendered to the user as a view. The global-exception-mappings sub-element of package specifies the exception mapping for all the actions of this package. The exception-mapping sub-element of global-exception-mapping maps the given result for the given exception type. In this example, we are using the Exception which the parent of many exception classes such as IOException, ArithmeticException etc. It means if any exception occurs, specified result will be invoked. Notice that global-results must be specified before global-exception-mappings as we are using global result in global-exception-mappings.Displaying exceptionWe can display the exception on the browser by printing the exception or exceptionStack. The exception object prints the exception name whereas exceptionStack prints the exception details. globalresult.jspFull example of exception handlingThe other required resources to complete this example are as follows:
1) Create index.jsp for inputThis jsp page creates a form using struts UI tags. It receives name and password from the user. index.jsp2) Create the action classThis action class contains two fields name and password and one method execute. Here, we are throwing exception self if password matches struts. This is dummy example, if you comment the mentioned line in the execute method, exception will not occur. Login.java3) Create view componentsThere are three view components globalresult.jsp that displays the exception message, welcome.jsp that displays the welcome message with the username and error.jsp that displays the error message. globalresult.jsp welcome.jsp error.jsp
download this example (developed using Eclipse IDE without JARs)
download this example (developed using Myeclipse IDE)
Next TopicStruts2 File Upload Example
|