SpringMVC Controller的返回类型

/* 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));
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值