如何重置一个@ModelAttribute在Spring MVC后,它已在控制器中处理



我已经定义了一个@ModelAttribute("mymodel")

@ModelAttribute("mymodel")
MyModel mymodel() {
  MyModel mymodel = new MyModel();
  return mymodel;
 }

@RequestMapping(value = "/save", method = RequestMethod.POST)
public final void save(@ModelAttribute("mymodel") MyModel mymodel, 
                           final BindingResult binding,
    final HttpServletRequest request, 
    final ModelMap modelMap) throws Exception {
    modelService.save(mymodel);
            // try to reset the model --> doesn't work!!!
    myModel = new MyModel();
}

问题是,即使我在保存方法中重置了模型,如果我在保存操作后重新加载页面并第二次保存,该模型仍包含前一个myModel的所有值。

处理后如何重置?

除非我猜错了,否则这是因为

myModel = new MyModel();

只会重置方法中的引用,就像从List<MyModel>获得MyModel然后调用myModel = new MyModel();不会改变列表中的元素一样,只会改变您的本地引用。

您很可能需要将新的MyModel()放入模型或modelMap中。

post后的重定向模式在这里可能也很有用。有POST方法

return "redirect:originalpage.htm"

这将刷新原始页面,也意味着如果你点击刷新,你不会重新提交POST,保存你的对象两次。

我不会这样做的。

试着在get请求中设置你的模型:

@RequestMapping(value = "/save", method = RequestMethod.GET)
public ModelAndView getSaveForm(ModelMap model) {
   model.addAttribute("mymodel", new MyModel());
   return new ModelAndView("newView", model);
}

在操作中使用 portlet的BookCatalog时,我遇到了类似的问题。我的解决方案是使用Model.addAttribute()手动重置它。例如:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public final void save(@ModelAttribute("mymodel") MyModel mymodel, 
   final BindingResult binding,
   Model model
   final HttpServletRequest request, 
   final ModelMap modelMap) throws Exception 
{
   modelService.save(mymodel);
   model.addAttrubute("mymodel", new MyModel());
}

当我们想在控制器完成处理后添加响应头时,下面的示例方法可以工作。@ModelAttribute("mymodel")在控制器方法处理之前被调用,因此我们不能根据处理结果设置任何值。//在请求方法中添加参数"HttpServletResponse"

@RequestMapping(method = RequestMethod。POST, value = apiconconstants。Request_URL, headers = APIConstants。Request_HEADER, produces = apiconconstants . produces)@RequestBody() PojoRQ apiRequest, HttpServletResponse响应)抛出异常{

    try
    {
        // All code related to processing
    }
    catch(Exception e)
    {
        throw e;
    }
    //Just before sending back the response add below line
    response.setHeader("Response_Key","Response_Header_value");
    return PojoRS;
}

最新更新