Spring MVC Flash 属性解决属性丢失

正常的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";
         
         
     }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值