繁体   English   中英

表单支持bean不保留已设置的属性值

[英]Form backing bean is not retaining already set property values

我正在使用像这样的表单支持bean。

public class BeanData implements Serializable{

    private String param1;
    private String param2;
    private String param3;
    private String param4="india";

    getters setters
}

然后在模型中发送bean对象,如下所示 -

@RequestMapping(value=/formPage, method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView getPage(HttpSession session, ModelAndView modelAndView) {   

        BeanData formBean = new BeanData();
        formBean.setParam2("123456"); // this param2 doens't have any field in JSP
        modelAndView.addObject("formBean", formBean);
        modelAndView.setViewName(PAGE);

        return modelAndView;
    }
@RequestMapping(value=submitData, headers="Accept=*/*", method={RequestMethod.POST})
    public void submitData(@Valid @ModelAttribute("formBean") BeanData formBean, BindingResult result, HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView, HttpSession session) {


        LOGGER.info("param1:"+formBean.getParam1()); // Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info(" param2:"+formBean.getParam2()); // It has not been used in JSP. Though from controller it was populated before sending the bean to the jsp. but here the value is null . This is the concern
        LOGGER.info("param3:"+formBean.getParam3());// Param1 has a path map in jsp field. So whatever user is puuting into form field, that is getting populated here
        LOGGER.info("param4:"+formBean.getParam4());//thsi field also has not been used in JSP. But this property was set in bean instantiation. It is also getting retrieved successfully.


        modelAndView.setViewName(SUCCESS PAGE);

    }

我关心的是,我想使用setter方法设置一个bean属性,并希望将bean支持对象传递给JSP。 然后所有属性值应该绑定(我使用表单字段路径属性显式绑定的内容以及我在创建bean对象时已经设置的内容)到后备对象,它应该在控制器中接收。 请指导我在哪里做错了。

如果你想在JSP中保存param2字段的值并将其恢复到表单提交,你可以使用隐藏字段绑定它,如下所示:

<form:hidden path="formBean.param2"/>

它不会显示在您的JSP中,但它将按原样保存您的值。

另一种方法是将BeanData存储到会话中。

模型属性是请求范围的bean。 你可以用的解决方案:

  • 将您的属性映射到html表单中的隐藏字段。 我不建议这样做,因为它们可以在客户端轻松更新。
  • 使用会话属性而不是模型属性,我认为这是最后一个选项。
  • 您真正应该做的是将表单bean的创建委托给使用@ModelAttribute注释的方法,而不是在getPage方法中执行。

Spring在处理请求之前执行使用@ModelAttribute注释的方法,然后使用来自表单的属性更新对象。

@ModelAttribute("formBean")
public BeanData setFormBeanModel()
{
  BeanData formBean = new BeanData();
  formBean.setParam2("123456");
  return formBean;
}

@RequestMapping(value=/formPage, method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView getPage(HttpSession session, ModelAndView modelAndView) 
{ 
  modelAndView.setViewName(PAGE);

  return modelAndView;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM