正常的MVC Web应用程序在每次提交都会POST数据到服务器。一个正常的Controller (被注解 @Controller标记)从请求获取数据和处理它 (保存或更新数据库)。一旦操作成功,用户就会被带到(forward)一个操作成功的页面。传统上来说,这样的POST/Forward/GET模式,有时候会导致多次提交问题. 例如用户按F5刷新页面,这时同样的数据会再提交一次。
为了解决这问题, POST/Redirect/GET 模式被用在MVC应用程序上. 一旦用户表单被提交成功, 我们重定向(Redirect)请求到另一个成功页面。这样能够令浏览器创建新的GET请求和加载新页面。这样用户按下F5,是直接GET请求而不是再提交一次表单。
Spring提供了一种方案:将属性放到会话中,会话能够长期存在,并且跨多个请求,所以我们可以在重定向前将属性放到会话中,在重定向后,从会话中将其取出
以下为栗子
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.iboyaa.pojo.Flashinfo;
/**
* @author 清水贤人
*
*/
@Controller
public class flashController {
@RequestMapping(value="/register",method=RequestMethod.POST)
public String processRegistration(Flashinfo flashinfo,RedirectAttributes model) {
model.addAttribute("username","");
//将属性以key value形式存入,待重定向之后可以直接取出
model.addFlashAttribute("flashinfo",flashinfo);
return "redirect:/apitter/{username}";
}
@RequestMapping(value="/{username}",method=RequestMethod.POST)
public String showSpitterProfile(@PathVariable String username,Model model) {
//判断在重定向之前是将值存入,有的话就直接传递到视图进行渲染,没有再去数据库查询
if(!model.containsAttribute("flashinfo")) {
model.addAttribute("去数据库执行查询");
}
return "profile";
}
}