Monday, 12 May 2014

Exception Handling in Spring MVC

Exception Handling in Spring MVC using SimpleMappingExceptionResolver.

Spring has long provided a simple but convenient implementation of HandlerExceptionResolver - the SimpleMappingExceptionResolver. It provides options to:
  • Map exception class names to view names - just specify the classname, no package needed.
  • Specify a default (fallback) error page for any exception not handled anywhere else

In this Post you can get simple example on  SimpleMappingExceptionResolver step by step.



Final Project Structure Look like below

 



Below is the pom.xml Configuration



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mahesh.spring</groupId>
    <artifactId>spring-exception-resolver</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Spring Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <jdk.version>1.6</jdk.version>
        <spring.version>3.2.2.RELEASE</spring.version>
        <jstl.version>1.2</jstl.version>
    </properties>

    <dependencies>


        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
    <build>
        <finalName>spring-exception-resolver</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>false</downloadJavadocs>
                    <wtpversion>2.0</wtpversion>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>



Below is the Custom Exception Class GenericException.java


package com.mahesh.web.exception;

public class GenericException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    private String errCode;
    private String errMsg;

    public String getErrCode() {
        return errCode;
    }

    public void setErrCode(String errCode) {
        this.errCode = errCode;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public GenericException(String errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

}


Below is the Controller Class CustomerControlle.java here just throw Custom Exception that we created above with error code and error desription.



package com.mahesh.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mahesh.web.exception.GenericException;

@Controller
public class CustomerController {

    @RequestMapping("/customer")
    protected String getCustomer() throws Exception {

        throw new GenericException("E2425", "This is custom message X");

    }

    @RequestMapping("/owner")
    protected String getOwner() throws Exception {

        String OwnerName = null;

        return OwnerName.toString();

    }

}


Below is the spring configuration file.

we mapped below 2  mappings in  exceptionMappings property of SimpleMappingExceptionResolver.

  1. GenericException is thrown, it will map to the view name “error/generic_error”.
  2. Any other Exceptions is thrown, it will map to the view name “error/exception_error”.


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.mahesh" />

    <bean
        class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="com.mahesh.web.exception.GenericException">
                    error/generic_error
                </prop>
                <prop key="java.lang.Exception">error/exception_error</prop>
            </props>
        </property>
    </bean>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <mvc:annotation-driven />

</beans>

Below is the web.xml configuration



<web-app 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"
    version="2.5">

    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/pages/error/404.jsp</location>
    </error-page>

</web-app>

Below is the jsp code for generic_error.jsp



<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>

    <c:if test="${not empty exception.errCode}">
        <h1>${exception.errCode} : System Errors</h1>
    </c:if>
   
    <c:if test="${empty exception.errCode}">
        <h1>System Errors</h1>
    </c:if>

    <c:if test="${not empty exception.errMsg}">
        <h4>${exception.errMsg}</h4>
    </c:if>
   
</body>
</html>


Below is the jsp code for exception_error.jsp



<html>
<body>

    <h1>${exception}</h1>
   
</body>
</html>

Below is the code for 404.jsp



<%@ page isErrorPage="true"%>
<html>
<body>

<h2 style="font-size: 35px;margin: 0;text-align: center;">Oops..! </h2>

<h3 style="font-size:17px;text-align: center;">A 404 error happened because the resource could not be found.</h3>
   
</body>
</html>

Last Step is to clean and install project and deploy war in Tomcat and run.




























No comments:

Post a Comment