Spring MVC model
I am trying to display the exception occurred in the controller on the view layer. For this I have setup a try catch block like:
public String persistUserData( )
{
try
{
//Make DB Call
// Update DB and get new Data
model.addAttribute( "updatedData", data );
throw new Exception("Creating an Exception");
}
catch(Exception e)
{
model.addAttribute开发者_运维问答("myException", ex.getClass());
}
return "myPage.jsp";
}
In my view I am trying to print it with ${myException}
, but its not printing anything. What is going wrong here?
I am so sorry to tell this, but it works for me...
@Controller
@RequestMapping("/")
public class MyController {
@RequestMapping
public String omg(@RequestParam("name") String name, Model model) {
try {
model.addAttribute("name", name);
throw new Exception("OMG!");
} catch (Exception e) {
model.addAttribute("myException", e);
}
return "/WEB-INF/foo.jsp";
}
}
And foo.jsp
:
Name: ${name}<br/>
Error was: ${myException}
This renders (with default Spring MVC configuration under http://localhost:8080/app/?name=abc
):
Name: abc
Error was: java.lang.Exception: OMG!
I swear!
You can use this pattern :
@Controller
@RequestMapping("/")
public class MyController {
//catch any exception
@ExceptionHandler(Exception.class)
public ModelAndView handleMyException(Exception exception) {
ModelAndView mv = new ModelAndView("errorPage);
mv.addObject("message",exception.getMessage());
return mv;
}
@RequestMapping(value="/doSomething", method=RequestMethod.GET)
public ModelAndView doSomething() {
/doSomething
throw new Exception("OMG!");
return mv;
}
}
Hope it helps.
You should return the model from the function, which would look like
return model;
And model should be from type ModelAndView
.
精彩评论