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

时间:2017-04-03 07:10:45

标签: java spring-mvc

我正在使用像这样的表单支持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对象时已经设置的内容)到后备对象,它应该在控制器中接收。请指导我在哪里做错了。

2 个答案:

答案 0 :(得分:0)

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

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

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

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

答案 1 :(得分:0)

模型属性是请求范围的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;
}