Redirect in post mode inside a controller's method

别等时光非礼了梦想. 提交于 2019-12-12 04:20:07

问题


EDIT: If someone have problems following the guide below, I suggest to use an easier approach, like this one: https://www.youtube.com/watch?v=yaxUV3Ib4vM


I'm still following this tutorial: spring-mvc-radiobutton-and-radiobuttons-example and I've created this controller so far:

    @RequestMapping(value = "add", method = RequestMethod.GET)
public String add(Model model) {
    MyObject object = new MyObject();
    object.setParameter("fake parameter");
    model.addAttribute("add", object);
    initModelList(model);
    return "add";
}

@RequestMapping(value = "add", method = RequestMethod.POST)
public String add(@ModelAttribute("add") @Validated MyObject object, BindingResult result, Model model) {
    model.addAttribute("add", object);
    String returnVal = "redirect:/add/object";
    if(result.hasErrors()) {
        initModelList(model);
        returnVal = "add";
    } else {
        model.addAttribute("add", object);
    }       
    return returnVal;
}

@RequestMapping(value = "/add/object", method = RequestMethod.POST)
public String addObject(
                            @ModelAttribute MyObject object,
                            ModelMap model) throws DatatypeConfigurationException {
      try{
      ...marshalling results in xml output 
      ...inserting it in database
      ...showing the result

        return "objectResult";

    } catch (Exception e) {
        LOG.error(e.getMessage(), e);

        throw new RuntimeException(e);
    }
}

Of course this solution don't work, since the redirect is of type GET. I've tried to fuse the last two methods together, like so:

    @RequestMapping(value = "add", method = RequestMethod.POST)
public String add(@ModelAttribute("add") @Validated MyObject object, BindingResult result, Model model)
         throws DatatypeConfigurationException {
    model.addAttribute("add", object);
    String returnVal = "objectResult";
    if(result.hasErrors()) {
        initModelList(model);
        returnVal = "add";
    } else {
        model.addAttribute("add", object);
    }       
    try{
    ...mashalling etcetera
        return returnVal;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);

        throw new RuntimeException(e);
    }
}

But in that way the validation don't work. I don't know how to solve this problem, I would like to use the spring validator but if I can't use it I will regress the project, wich is a shame.


回答1:


If someone have problems following the same guide, I suggest to use an easier approach, like this one: https://www.youtube.com/watch?v=yaxUV3Ib4vM It doesn't neeed to update the maven dependency



来源:https://stackoverflow.com/questions/41120380/redirect-in-post-mode-inside-a-controllers-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!