Quantcast
Channel: web – Imran Tariq's Blog
Viewing all articles
Browse latest Browse all 33

Spring MVC exception handling and show custom view

$
0
0

Spring MVC is a powerfull Java application framework to create web applications for Java. In this example we’ll learn how to handle exception in Spring MVC and then based on that how to show a different view to user

Exception Handling Example 1

Spring mvc can handle all exception within a controller with the following annotation

@ExceptionHandler(Exception.class)
@Controller
public class HelloWorldController {

	@ExceptionHandler(Exception.class)
	public ModelAndView handleMyException(Exception exception) {
		ModelAndView mv = new ModelAndView("redirect:errorMessage.html?error=" + exception.getMessage());
		return mv;
	}

@RequestMapping(value = "/errorMessage", method = RequestMethod.GET)
public ModelAndView handleMyExceptionOnRedirect(@RequestParam("error") String error) {

       ModelAndView mv = new ModelAndView("uncaughtExceptionSpring");
mv.addObject("error", error);
return mv;
}
}

So this means that when an exception will occur it will redirect to error page url and that url will display an error view

Exception Handling Example 2

You can also use SimpleMappingExceptionResolver it might be more useful in your case: you can just map each exception to each page and the default page.

Set this in spring config. file.

     <bean class="com.imran.web.handler.CustomSimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>              
                <prop key="java.lang.Throwable">error</prop>
            </props>
        </property>
    </bean>

Class

package com.imran.web.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver{
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
     if(int a = 1)
         return new ModelAndView("ViewName1");
     else
         return new ModelAndView("ViewName2"); }
 }
}


Viewing all articles
Browse latest Browse all 33

Trending Articles