views:

30

answers:

1

Hi!

I'm trying build my application using REST and Spring MVC. For some entities I have special page for update. After data submit it validated. If there are no errors it's redirecting to view of this entity otherway to edit page. haw I must pass data (entity and validator result) between controllers?

here implementation with some very bad practice.

@RequestMapping(method = RequestMethod.PUT, value = "/workers/{id}")
public ModelAndView update(@PathVariable final Long id, @Valid Worker entity, Errors errors, NativeWebRequest request) {
    ModelAndView model = new ModelAndView();
    entity.setId(id);
    if (errors.hasErrors()) {
        request.setAttribute("entity", entity, RequestAttributes.SCOPE_SESSION);
        request.setAttribute("errors", errors.getAllErrors(), RequestAttributes.SCOPE_SESSION);
        model.setViewName("redirect:/workers/" + entity.getId()+ "/edit");
    } else {
        System.out.println("upd-done");
        service.update(entity);
        model.setViewName("redirect:/workers/" + entity.getId());
        model.addObject(entity);
    }
    return model;
}

@RequestMapping(method = RequestMethod.GET, value = "/workers/{id}/edit")
public ModelAndView updatePage(@PathVariable Long id, NativeWebRequest request) {
    ModelAndView model = new ModelAndView();
    DomainObject entity = (DomainObject)request.getAttribute("entity", RequestAttributes.SCOPE_SESSION);
    model.addObject("entity", entity != null ? entity : service.get(id));
    model.setViewName(names.provideViewName(Pages.EDIT));
    return model;
}

here form for edit

<form id="entity" action="/workers/6" method="post"><input type="hidden" name="_method" value="PUT"/>
foo <input id="foo" name="foo" type="text" /></td>
<input type="submit" value="Save Changes" />
</form>

Thanks.

+1  A: 

When there are errors and you need to send the user back to the form view, just use the same view name that you used in the GET/edit method ("names.provideViewName(Pages.EDIT)"). You will want to modify that view to check if there are errors in the model and if so show them to the user.

@RequestMapping(method = RequestMethod.PUT, value = "/workers/{id}")
public ModelAndView update(@PathVariable final Long id, @Valid Worker entity, Errors errors, NativeWebRequest request) {
    ModelAndView model = new ModelAndView();
    entity.setId(id);
    if (errors.hasErrors()) {
        model.addObject("entity", entity);
        model.addObject("errors", errors);
        model.setViewName(names.provideViewName(Pages.EDIT));
    } else {
        System.out.println("upd-done");
        service.update(entity);
        model.setViewName("redirect:/workers/" + entity.getId());
        model.addObject(entity);
    }
    return model;
}
sdouglass