SpringMVC支持的返回值类型有:ModelAndView,Model,ModelMap,Map,View,void,Sting.
SpringMVC未指定跳转页面时,有@ResponseBody注解则会根据请求的路径最后/后的字段去掉后缀作为跳转的文件名.
SpringMVC对其支持的返回值类型,默认返回类型为:text/html
不是其支持的类型对象默认返回形式为:application/json
1.返回ModelAndView对象
package com.danger.superclub.controller; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; @Controller public class SpringTestController { /** * 跳转到test.jsp页面 * @return */ @RequestMapping("/test1.do") public ModelAndView test1(){ ModelAndView mav = new ModelAndView("test1");//指定返回的视图页面 mav.addObject("mav", "this is a ModelAndView type"); return mav; }
2.返回Model对象
/** * Model是一个接口,其实现类为ExtendedModelMap,继承了ModelMap类, * 跳转到test2.jsp页面, * @param model * @return */ @RequestMapping("/test2.do") @ResponseBody public Model test2(Model model){ model.addAttribute("model","this is a Model type"); return model; }
效果如下:
<span style="font-size:18px;">/** * @ReponseBody注解可将对象按照请求的消息头格式返回 */ @RequestMapping("/test3.do") @ResponseBody public ModelMap test3(ModelMap modelMap){ modelMap.addAttribute("modelMap","this is a ModelMap type"); return modelMap; }</span>
效果如下:
/** * 直接跳转到test4.jsp */ @RequestMapping("/test4.do") @ResponseBody public Map<String,String> test4(Map<String, String> map){ map.put("map", "this is a Map<String,String> type"); return map; }
/** * 跳转到index.jsp界面 * @return */ @RequestMapping("/test5.do") public String test5(){ return "index"; }
6.返回字符串
/** * 当加了@ResponseBody注解后将返回字符串 * @return */ @RequestMapping("/test6.do") @ResponseBody public String test6(){ return "index"; }</span>
7.返回视图对象
/** * 可返回pdf,excel等视图,自动跳转到test8.jsp页面 */ @RequestMapping("/test8.do") public View test8(){ return null; }
8.返回void
/** * 不返回任何东西,直接跳转到tset7.jsp页面 * @param model */ @RequestMapping("/test7.do") public void test7(Model model){ model.addAttribute("void","this is a void type"); }
9.返回一个对象,或值
/** * 返回一个值或对象 * @return */ @RequestMapping("/test9.do") @ResponseBody public boolean test9(){ return true; }