开发者

Spring MVC - command object binding question

I'm using a domain object as a command object in the web layer. In one case, this command object is backing开发者_运维知识库 a form that represents a partial update of the domain object.

@RequestMapping( value = "/club/edit", method = RequestMethod.GET )
public String setupEditClubForm( ModelMap model, @RequestParam( "clubId" ) Long clubId ) {
    Club club = clubService.findClubById( clubId );
    model.addAttribute( "club", club );
    model.addAttribute( "action", "edit" );
    return "clubForm";
}

@RequestMapping( value = "/club/edit", method = RequestMethod.POST )
public String processEditClubForm( ClubEntity club, BindingResult result ) {
    if ( result.hasErrors() ) {
        return "clubForm";
    }
    clubService.updateClub( club );
    return "redirect:/club/" + club.getId();
}

My problem is that the domain object has some fields that are not changed by submitting this form. These fields that don't have the corresponding request parameters become null, I need them to stay as they are.

I though that this could be fixed by putting the object in the session (via @SessionAttributes) to allow it to live between the two requests, but it doesn't work.

I looked in the Spring reference, but I couldn't find any information on how Spring manipulates the command objects.


Well, the problem was simple - I was actually creating a new command object in the processEditClubForm method. Here is the correct method code:

@RequestMapping( value = "/club/edit", method = RequestMethod.POST )
public String processEditClubForm( @ModelAttribute Club club, BindingResult result ) {
    if ( result.hasErrors() ) {
        return "clubForm";
    }
    clubService.updateClub( club );
    return "redirect:/club/" + club.getId();
}

Thanks to Daniel for making me see it :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜