簡體   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