下面为方法返回类型的几种形式:
//形式一:返回值为String,代表要访问的URL地址
@RequestMapping("test1")
public String test1(){
return "index";
}
//形式二:返回ModelAndView
//构造可以传URL地址,和传入一个Map集合到request域中
//JSP取Map集合时为:${requestScope.admin.username }
//不是:${requestScope.map.admin.username }
@RequestMapping("test2")
public ModelAndView test2(){
Map<String,User> map = new HashMap<String, User>();
map.put("admin",new User("admin","1234"));
ModelAndView mv = new ModelAndView("index",map);
//mv.addObject("map",map);
return mv;
}
//形式三:返回值为String,但形参为Map集合,键值最好为:String,Object类
//JSP取Map集合时为:${requestScope.admin.username }
//不是:${requestScope.map.admin.username }
@RequestMapping("test3")
public String test3(Map<String,Object> map){
map.put("admin",new User("admin","1234"));
return "index";
}
//形式四:返回值为String,形参为Model
@RequestMapping("test4")
public String test4(Model model,HttpServletRequest request){
//添加一个List集合
List<User> list = new ArrayList<User>();
list.add(new User("list5","1234"));
model.addAttribute("list",list);
//添加一个Map集合
Map<String,User> map = new HashMap<String, User>();
map.put("user1",new User("map","1234"));
//注意:下面两个方法不同
//addAllAttributes在JSP中取值时为:${requestScope.user1.username }
model.addAllAttributes(map);
//addAttribute在JSP中取值时为:${requestScope.map.user1.username }
model.addAttribute("map",map);
//添加一个对象
model.addAttribute("user",new User("admin","1234"));
return "index";
}
//形式五:返回值为void,利用Ajax返回,参数为HttpServletResponse
@RequestMapping("test5")
public void test5(HttpServletResponse response) throws IOException{
response.setContentType("application/json");
response.getWriter().write("{\"json\":\"json\"}");
}
//形式六:返回值为void,利用Ajax返回,形参为PrintWriter
@RequestMapping("test6")
public void test6(HttpServletResponse response ,PrintWriter pw){
response.setContentType("application/json");
pw.write("{\"json\":\"json\"}");
}