1. The main difference
Model is a default parameter that exists in each request, and its addAttribute() method can be used to pass the value of the server to the jsp page; ModelAndView contains two parts, model and view. You need to instantiate it yourself when using it. You can use ModelMap to pass values, and you can also set the name of the view.
2. Examples
1) Use Model to pass value
- @RequestMapping(value="/list-books")
- private String getAllBooks(Model model){
- logger.error("/list-books");
- List<Book> books= bookService.getAllBooks();
- model.addAttribute("books", books);
- return "BookList";
- }
Use ${books} on the jsp page to retrieve the value
2) There are two ways to use ModelAndView to pass values. Different methods have different values on the jsp page, and the name of the view is set at the same time.
- public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
- Object handler, Exception ex) {
- LibraryException le=null;
- if(ex instanceof LibraryException){
- le=(LibraryException)ex;
- }else{
- le= new LibraryException( "Unknown exception from the system!");
- }
- ModelAndView modelAndView= new ModelAndView();
- modelAndView.addObject("exception",le.getMessage());
- modelAndView.getModel().put("exception",le.getMessage());
- modelAndView.setViewName( "error");
- return modelAndView;
- }
${requestScope.exception1} in jsp can take out the value of exception1;
${exception2} in jsp can take out the value of exception2