SpringMVC重定向很简单,只需要让控制器返回RedirectView对象即可(或者在返回的视图名前加上前缀“redirect:”,也可以表示这是重定向而不是ViewName)
例如:
@Controller
public class UserController
{
@Resource(name="userService")
private UserService userService;
@PostMapping("/login")
public View login(String username, String password, RedirectAttributes model)
{
if (userService.userLogin(username,password)>0)
{
// model.addAllAttributes(Map.of("tip","欢迎您,登入成功!"));
model.addFlashAttribute("tip","欢迎您,登入成功!");
return new RedirectView("success");
}
// model.addAllAttributes(Map.of("tip","账号或者密码错误!"));
model.addFlashAttribute("tip","账号或者密码错误!");
return new RedirectView("error");
}
@GetMapping("/success")
public String success(@ModelAttribute("tip") String tip)
{
System.out.println(tip);
return "success";
}
@GetMapping("/error")
public String error(@ModelAttribute("tip") String tip)
{
System.out.println(tip);
return "error";
}
}
通过上面代码可以看到,重定向中用到的model是RedirectAttributes 而不是Model,其实RedirectAttributes 是Mdel的子接口,重定向中用Model无法准确传输数据,SpringMVC会将Model中的数据以HTTP请求参数的方式传递,那么就要求Model中的value的类型必须为String并且这样做会很不安全,为了解决这个问题就引入了RedirectAttributes 。
获取RedirectAttributes 中的数据:
java程序获取RedirectAttributes 中的数据很简单只需要在方法参数前用@ModelAttribute(“xxxx”)修饰就可以,这个参数就代表了RedirectAttributes 中指定的数据。
jsp中获取RedirectAttributes 中的数据和获取Model数据一样,用EL或者JSTL表达式即可。