/* SpringMVC Controller的返回类型
Controller的三种返回类型中
ModelAndView类型 带数据带跳转页面
String 跳转页面不带数据
void 通常是ajax格式请求时使用 */
1.返回void
返回这种结果的时候可以在Controller方法的形参中定义HTTPServletRequest和HTTPServletResponse对象进行请求的接收和响应
1)使用request转发页面
request.getRequestDispatcher("转发路径").forward(request,response);
2)使用response进行页面重定向
response.sendRedirect("重定向路径");
3)也可以使用response指定响应结果
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter.write("json串");
Map
PS:响应的view应该也是该请求的view。等同于void返回。通常应用于ajax请求
@RequestMapping(method=RequestMethod.GET)
public Map<String, String> index(){
Map<String, String> map = new HashMap<String, String>();
map.put("1", "1");
//map.put相当于request.setAttribute方法
return map;
}
2.ModelAndView
@RequestMapping(method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView("/user/index");
modelAndView.addObject("xxx", "xxx");
return modelAndView;
}
String
对于String的返回类型,可以配合Model来使用的;
@RequestMapping(method = RequestMethod.GET)
public String index(Model model) {
String retVal = "user/index";
List<User> users = userService.getUsers();
model.addAttribute("users", users);
return retVal;
}
通过配合@ResponseBody来将内容或者对象作为HTTP响应正文返回(适合做即时校验);
@RequestMapping(value = "/valid", method = RequestMethod.GET)
public @ResponseBody String valid(@RequestParam(value = "userId", required = false) Integer userId,
@RequestParam(value = "logName") String strLogName) {
return String.valueOf(!userService.isLogNameExist(strLogName, userId));
}
SpringMVC Controller的返回类型
最新推荐文章于 2024-07-17 21:30:13 发布