首先来看常规用法
@RequestMapping("/index")
public String index(){
System.out.println("index Controller...");
return "hello";
}
发送请求
http://localhost:8080/springmvc-rest/index
后台接收请求直接跳转到hello.jsp页面。
重定向(redirect)
重定向也是web开发中常用的,在springmvc中,重定向相当的简单
@RequestMapping("/index")
public String index(){
return "redirect:hello";
}
@RequestMapping("/hello")
public String hello(){
return "hello";
}
- 发送请求
http://localhost:8080/springmvc-rest/index
当执行到return "redirect:hello";
时,发现是个重定向服务端会要求客户端重新发送http://localhost:8080/springmvc-rest/hello
请求 - 由于重定向Model不共享,所以之前提交的数据在重定向后请求对应的处理方法hello()中中无法获取。
- 重定向后浏览器的输入框中URL也发生变化。
- 对于redirect而言,Request的attribute不会被传递,放到session中,session在跳到页面后也会马上移除对象。
如果你希望Request的attribute被传递,可以使用RedirectAttributes类
@RequestMapping("/index")
public String index(HttpServletRequest request,RedirectAttributes redirectAttributes){
String userName = request.getParameter("name");
String password = request.getParameter("pwd");
//重定向传递参数的两种方法
//1.这种方式会将参数拼接到重定向的 url中
redirectAttributes.addAttribute("name", userName);
//2.这种方式会将参数放到session中,如果刷新页面就会丢失
redirectAttributes.addFlashAttribute("pwd", password);
return "redirect:hello";
}
@RequestMapping(value="/hello", method=RequestMethod.GET)
public String hello(HttpServletRequest request){
String userName = request.getParameter("name");
return "hello";
}
- 由于重定向是客户端重新通过url发送的请求,所以重定向后的请求是 GET 方式的。
- 使用RedirectAttributes类的addAttribute方法传递参数会跟随在URL后面,如
上面这个重定向后重新发送的请求url是:
http://localhost:8080/springmvc-rest/hello?name=xxx
- 使用RedirectAttributes类的addFlashAttribute方法传递参数不会跟随在URL后面,会把该参数值暂时保存于session,待重定向URL获取该参数后从session中移除,这里的redirect必须是方法映射路径,jsp无效。redirect后的hello.jsp页面中pwd只会出现一次,刷新后pwd再也不会出现了。
注:也可以将数据放进Model进行传递,和使用RedirectAttributes的addAttribute效果一样。
@RequestMapping("/index")
public String index(String userName,Model model){
//重定向传递参数,效果和RedirectAttributes的addAttribute类似
model.addAttribute("userName", userName);
return "redirect:hello";
}
@RequestMapping(value="/hello", method=RequestMethod.GET)
public String hello(HttpServletRequest request){
//可以在request中获取到数据
String userName = request.getParameter("userName");
return "hello";
}
将数据放进Model中然后进行重定向,相当于重新提交了数据,在request中是可以获取到的。
转发(forward)
@RequestMapping(value="/index",method=RequestMethod.GET)
public String index(){
return "forward:hello";
}
@RequestMapping("/hello",method=RequestMethod.GET)
public String hello1(){
return "hello1";
}
@RequestMapping("/hello",method=RequestMethod.POST)
public String hello2(){
return "hello2";
}
- 发送请求
http://localhost:8080/springmvc-rest/index
当执行到
return "forward:hello";
时发现是个转发,服务器就将请求转发给hello1()处理,为什么不是hello2()方法呢?那是因为还需要匹配请求的method。 - 转发不会再经过客户端,直接由服务端调控。
- 转发后浏览器的输入框中URL不会发生变化。
- 转发后连带着request一起转发。