spring mvc supports the following return methods: ModelAndView, Model, ModelMap, Map, View, String, void.
ModelAndView
@RequestMapping("/hello") public ModelAndView helloWorld() { String message = "Hello World, Spring !"; return new ModelAndView("hello", "message", message); }
The ModelAndView constructor can specify the returned page name, or you can jump to the specified page through the setViewName() method
Map
@RequestMapping("/demo2/show") public Map<String, String> getMap() { Map<String, String> map = new HashMap<String, String>(); ("key1", "value-1"); ("key2", "value-2"); return map; }
In the jsp page, you can directly obtain the value through ${key1}, () is equivalent to the method.
View
You can return to PDF Excel, etc., but I haven't learned more about it yet.
String
Specify the returned view page name, and access it with the set return address path plus the page name suffix.
Note: If the method declares the annotation @ResponseBody, the return value will be output directly to the page.
@RequestMapping(value="/showdog") public String hello1(){ return "hello"; }
@RequestMapping(value="/print") @ResponseBody public String print(){ String message = "Hello World, Spring MVC!"; return message; }
Returns an example of json (using Jackson):
@RequestMapping("/load1") @ResponseBody public String load1(@RequestParam String name,@RequestParam String password) throws IOException{ (name+" : "+password); //return name+" : "+password; MyDog dog=new MyDog(); ("Little Ha");("1 year old");("Dark Grey"); ObjectMapper objectMapper = new ObjectMapper(); String jsonString=(dog); (jsonString); return jsonString; }
void
If the return value is empty, the response view page corresponds to the access address
@RequestMapping("/index") public void index() { return; }
The corresponding logical view is named "index"
summary:
1. Using String as the return value type of the request processing method is a relatively common method. In this way, the returned logical view name will not be bound to the request URL, which has great flexibility, and the model data can be controlled through ModelMap.
2. When using void, map, and Model, the corresponding logical view name is returned to the real url: prefix prefix + view name + suffix suffix.
3. Using String, ModelAndView returns the view name and can not be bound by the requested url, and ModelAndView can set the returned view name.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.