我想知道是否有更新现有@ModelAttribute的方法。如果可能的话,不保留会话中的值
我们说我有一个豆子:
class TravelDetails{
private String origin;
private String destination;
private String travelerName;
private String travelerAge;
// Getters & Seters
}
这是我的控制人员:
@Controller
class TravelerController{
@RequestMapping(value="/searchDetails", method=RequestMethod.GET)
public ModelAndView getSearchDetails(@RequestParam("origin") String origin,
@RequestParam("destination") String destination,ModelMap modelMap){
TravelDetails travelDetails = new TravelDetails();
travelDetails.setOrigin(origin);
travelDetails.setDestination(destination);
modelMap.addAttribute("travelDetails",travelDetails);
return new ModelAndView("get_traveler_details");
}
@RequestMapping(value="/addTravelerDetails", method=RequestMethod.POST)
public ModelAndView addTravelerDetails(
@ModelAttribute("travelDetails") TravelDetails travelDetails,
ModelMap modelMap){
System.out.println(travelDetails.getOrigin);
System.out.println(travelDetails.getDestination);
System.out.println(travelDetails.getTravelerName);
System.out.println(travelDetails.getTravelerAge);
return new ModelAndView("get_traveler_details");
}
}
在第二个控制器方法中获得的帖子表格只包含旅行者姓名和年龄,而需要从第一个控制器中设置的模型属性中检索原点和目的地。
我不想在Post表单中明确设置隐藏字段。
我们假设我的HTML为:
<form:form modelAttribute="travelDetails" action="/addTravelerDetails" method="POST">
<form:input type="text" path="travelerName"/>
<form:input type="text" path="travelerAge"/>
</form:form>
注意:我在StackOverflow的文本区域编写代码而不是在某些IDE上编写代码,因此如果代码中存在一些错误的拼写或语法错误,请忽略。
答案 0 :(得分:0)
您可以在类级别使用@SessionAttributes注释
@Controller
@SessionAttributes("travelDetailsPersist")
class TravelerController{
@RequestMapping(value="/searchDetails", method=RequestMethod.GET)
public ModelAndView getSearchDetails(@RequestParam("origin") String origin, @RequestParam("destination") String destination,ModelMap modelMap){
TravelDetails travelDetails = new TravelDetails();
travelDetails.setOrigin(origin);
travelDetails.setDestination(destination);
modelMap.addAttribute("travelDetails",travelDetails);
modelMap.addAttribute("travelDetailsPersist",travelDetails);
return new ModelAndView("get_traveler_details");
}
@RequestMapping(value="/addTravelerDetails", method=RequestMethod.POST)
public ModelAndView addTravelerDetails(@ModelAttribute("travelDetailsPersist") TravelDetails travelDetailsPersist, @ModelAttribute("travelDetails") TravelDetails travelDetails, ModelMap modelMap){
System.out.println(travelDetailsPersist.getOrigin);
System.out.println(travelDetailsPersist.getDestination);
System.out.println(travelDetails.getTravelerName);
System.out.println(travelDetails.getTravelerAge);
return new ModelAndView("get_traveler_details");
}
}