james01 james01 - 5 months ago 22
Java Question

Calling Jsp page from controller in Spring MVC

I'm new to Spring MVC. I've contoller which catches an exception, after catching the exception i want to redirect to error.jsp page and display the exception message (ex.getMessage()). I don't want to use Spring's Exception Handler rather i have to redirect to error.jsp programmatically.

@RequestMapping(value = "http/exception", method = RequestMethod.GET)
public String exception2()
{
try{
generateException();
}catch(IndexOutOfBoundsException e){
handleException();
}
return "";
}

private void generateException(){
throw new IndexOutOfBoundsException();
}

private void handleException(){

// what should go here to redirect the page to error.jsp
}

Answer Source

I'm not sure why you're returning String from your method; the standard in Spring MVC is for methods annotated with @RequestMapping to return a ModelAndView, even if you're not using Spring's Exception Handler. As far as I know you can't send your client to error.jsp without returning a ModelAndView somewhere. If you need help understanding the basic idea of Spring controllers, I found this tutorial showing how to create a simple "Hello World" application in Spring MVC, and it has a good example of a simple Spring controller.

If you want your method to return an error page if it encounters an exception, but otherwise return a normal page, I would do something like this:

@RequestMapping(value = "http/exception", method = RequestMethod.GET)
public ModelAndView exception2()
{
    ModelAndView modelAndview;
    try {
        generateException();
        modelAndView = new ModelAndView("success.jsp");
    } catch(IndexOutOfBoundsException e) {
        modelAndView = handleException();
    }
    return modelAndView;
}

private void generateException(){
    throw new IndexOutOfBoundsException();      
}

private ModelAndView handleException(){
     return new ModelAndView("error.jsp");
}