重定向:
重定向有几种方式:
1.通过response对象
2.在返回的字符串中加上redirect:表示重定向请求 比如:
public String page(){
return "index";
}
public String redirect(){
return "redirect:/index";
}
page方法返回的是逻辑视图名称
redirect方法是重定向请求
重定向携带数据RedirectAttributes:
当controller层需要重定向到指定页面时,如何携带数据?
传统使用session
使用RedirectAttributes (利用session原理)【优点:提供了addFlashAttribute等方法,确保数据只能被使用一次后删除】
@PostMapping("/regist")
public String register(RedirectAttributes attribdatautes){
int data = 1;
attributes.addFlashAttribute("data",data);
return "redirect:/index";
}
使用:
直接在handler的参数中添加RedirectAttributes
addFlashAttribute会重定向到下一个页面取出这个数据以后,将session里面的数据删除
ModelAndView:
其中model表示数据,view表示视图;这两个都是可以设置的,如果不设置view,那么就会使用默认的view,如果不设置model,那么就不会有数据传递到视图层
-默认视图,当前的请求的URL
ResponseBody:
将返回值转换成字符串,响应给客户端
返回值是一个对象,会被转换成json字符串,响应给客户端
如果返回的是字符串,那么就会直接响应给客户端
如果每一个
handler
方法都需要返回
json
字符串,那么就可以在类上面添加一个注解
@ResponseBody
,这样每一个方法都会返回json
字符串
类上面注解
@Controller
以及
@ResponseBody
一起使用,就相当于
@RestController