Spring MVC之返回类型
在spring MVC中存在多种返回类型,例如;view、modelandview、string、json或Map类型。
- 返回String类型 返回逻辑视图名称,根据由于springMVC-servlet.xml配置文件中配置的图解析器解析成物理视图
2.返回ModelAndView 类型 ModelAndView相对于String的返回类型的优势,可以携带参数传递到页面
3.返回void类型 一般配合PrintWriter使用,和Servlet用户类似
4.返回JSON类型 一般使用在JQuery的异步请求返回json格式的数据 返回String类型,通过“springMVC-servlet.xml”中的配置的视图解析器,解析并响应 prefix+returnValue+suffix 对应的视图
实例代码:
1. package com.wangbiao.springMVC;
2. import java.util.HashMap;
3. import java.util.Map;
4. import javax.servlet.ServletContext;
5. import javax.servlet.http.HttpServletRequest;
6. import javax.servlet.http.HttpServletResponse;
7. import org.springframework.context.ApplicationContext;
8. import org.springframework.stereotype.Controller;
9. import org.springframework.ui.Model;
10. import org.springframework.web.bind.annotation.RequestMapping;
11. import org.springframework.web.bind.annotation.RequestMethod;
12. import org.springframework.web.servlet.ModelAndView;
13. import org.springframework.web.servlet.View;
14. import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
15. @Controller
16. @RequestMapping("/return")
17. public class HelloWorld extends MultiActionController{
18.
19.
22. public ModelAndView sayHelloWorld(HttpServletRequest request, HttpServletResponse response) {
23. String param = request.getParameter("param");
24. System.out.println("springMVC测试:helloWorld;"+param);
25. ModelAndView mv = new ModelAndView();
26. User user = (User) this.getApplicationContext().getBean("user");
27. mv.addObject("content", "springMVC HelloWorld:"+param);
28. mv.setViewName("springMVC/helloWorld");
29. ServletContext ctx = this.getServletContext();
30. return mv;
31. }
32.
35. @RequestMapping(value="/returnString",method=RequestMethod.GET)
36. public String returnString(Model model) {
37. model.addAttribute("test", "return string!!!");
38. System.out.println("springMVC测试:helloWorld;");
39. return "return/returnString";
40. }
41.
42.
46. @RequestMapping("/returnVoid")
47. public void returnVoid(Model model){
48. model.addAttribute("test", "return void!!!");
49. }
50.
51.
55. @RequestMapping("/returnModel")
56. public Model returnModel(Model model){
57. model.addAttribute("test", "return Model!!!");
58. return model;
59. }
60.
61.
65. @RequestMapping("/returnMap")
66. public Map returnMap(Model model){
67. Map map = new HashMap<String,String>();
68. map.put("test", "return map!!!");
69. return map;
70. }
71.
72.
73. }
|