一、跳转
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class Login{ /**转发**/ @RequestMapping("/login.do") public String login(HttpServletRequest request,HttpServletResponse response){ request.setAttribute("message", "hello"); return "forward:/index.do"; //forward在跳转后可以取到message值 } @RequestMapping("/index.do") public String index(HttpServletRequest request,HttpServletResponse response){ return "welcome"; } /**重定向**/ @RequestMapping("/logout.do") public String logout(HttpServletRequest request,HttpServletResponse response){ request.setAttribute("message", "hello"); return "redirect:/register.do"; //redirect在跳转后无法取到message值 } @RequestMapping("/register.do") public String register(HttpServletRequest request,HttpServletResponse response){ return "register"; } }
另外forward跳转后地址栏URL不会改变 而redirect会改变
二、传参
@RequestMapping(value = "update", method = RequestMethod.POST) public String update(@Valid @ModelAttribute("user") User user, RedirectAttributes redirectAttributes) { accountService.updateUser(user); redirectAttributes.addFlashAttribute("message", "更新用户" + user.getLoginName() + "成功"); return "redirect:/admin/user"; }
为了防止用户刷新重复提交,save操作之后一般会redirect到另一个页面,同时带点操作成功的提示信息。因为是Redirect,Request里的attribute不会传递过去,如果放在session中,则需要在显示后及时清理,不然下面每一页都带着这个信息也不对。Spring在3.1才提供了这个能力,原理是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢掉。