Calling a Jsp page from a controller in Spring MVC

I am new to Spring MVC. I am a contoller that catches the exception, after detecting the exception, I want to redirect to the error.jsp page and display the exception message (ex.getMessage ()). I don't want to use Spring's exception handler, but I have to programmatically redirect to error.jsp.

@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 } 
+4
source share
1 answer

I'm not sure why you are returning a String from your method; the standard in Spring MVC is for methods annotated with @RequestMapping to return a ModelAndView , even if you are not using the Spring Exception Handler. As far as I know, you cannot 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 that shows 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 returns 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"); } 
+2
source

All Articles