The difference between Model and ModelAndView in springMVC

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
[java]  view plain copy  
 
  1.   
 
[java]  view plain copy  
 
  1. @RequestMapping(value="/list-books")  
  2.     private String getAllBooks(Model model){  
  3.         logger.error("/list-books");  
  4.         List<Book> books= bookService.getAllBooks();  
  5.         model.addAttribute("books", books);  
  6.         return "BookList";  
  7.     }  
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.
  1. public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,  
  2.                                          Object handler, Exception ex) {  
  3.         LibraryException le=null;  
  4.         if(ex instanceof LibraryException){  
  5.             le=(LibraryException)ex;  
  6.         }else{  
  7.             le= new LibraryException( "Unknown exception from the system!");  
  8.         }  
  9.   
  10.         ModelAndView modelAndView= new ModelAndView();  
  11.         modelAndView.addObject("exception",le.getMessage());  
  12.         modelAndView.getModel().put("exception",le.getMessage());  
  13.         modelAndView.setViewName( "error");  
  14.   
  15.         return modelAndView;  
  16.     }  
${requestScope.exception1} in jsp can take out the value of exception1;

 

${exception2} in jsp can take out the value of exception2

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325292119&siteId=291194637