【问题标题】:how to keep modelattribute value in jsp?如何在jsp中保持模型属性值?
【发布时间】:2018-09-24 18:22:51
【问题描述】:

我有一个名为 product.jsp 的 jsp 页面。 onload jsp 页面,我需要填充许多下拉列表和其他。但无论成功与否,它都会提交表单,它会清除所有文本字段。 我想保持价值,直到我清楚为止。这是我使用的过程。当我提交它时重定向同一页面但模型属性值变为空。我要保留模型属性值

  1. jsp页面

    <form:form method="POST" action="/productSetup/add" modelAttribute="productForm">
      <spring:bind path="name">
          <input type="text" class="form-control" id="name" name="name"   value="${productForm.name}" />              
    </spring:bind>
    
  2. 这是控制器..

     @Controller
     @RequestMapping("/productSetup")
     public class ProductController {
    
      @RequestMapping(value = "", method = RequestMethod.GET)
       public ModelAndView index(Model model) {
    
        ModelAndView modelAndView = new ModelAndView("product");    
        model.addAttribute("getCategoryList", dao.getCategoryList());        
        model.addAttribute("productForm", new ProductModel());
    
        return modelAndView;
      }
    
     @RequestMapping(value = "/add", method = RequestMethod.POST)
     public ModelAndView usrReg(@ModelAttribute("productForm") ProductModel productModel, Errors error, Model model,
    HttpSession session,RedirectAttributes redir,BindingResult result) {        
    
       ModelAndView modelAndView = new ModelAndView("product");
    
       redir.addFlashAttribute("productForm", productModel); 
    
       return new ModelAndView("redirect:/productSetup");
    
      }
    
    }
    

    请帮帮我

【问题讨论】:

标签: spring spring-boot spring-security


【解决方案1】:

您正在发布表单并将其重定向到 get。 问题是你总是在创建一个新的模型属性:

model.addAttribute("productForm", new ProductModel());

您应该检查 RedirectAttributes 是否包含“productForm”并添加它。

Object productForm = redirectAttributes.getFlashAttributes().get("productForm");
if(productForm == null){
     productForm = new ProductModel();
}
model.addAttribute("productForm", productForm);

这仅适用于第一次重定向,第二次访问将不包含该属性。如果要在连续获取请求之间保留数据,则应将其保存在会话中。 在您的 post 方法中,您可以替换

redir.addFlashAttribute("productForm", productModel); 

与:

session.setAttribute("productForm", productModel);

在你的获取请求中

Object productForm = session.getAttribute("productForm");
if(productForm == null || !(productForm instanceOf ProductModel)){
     productForm = new ProductModel();
}
model.addAttribute("productForm", productForm);

【讨论】:

    猜你喜欢
    • 2021-02-22
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2013-03-23
    • 2017-07-23
    • 1970-01-01
    • 2019-08-12
    相关资源
    最近更新 更多