在控制器方法

时间:2016-12-13 11:47:03

标签: java spring spring-mvc spring-boot spring-validator

修改 如果有人在遵循以下指南时遇到问题,我建议您使用更简单的方法,例如:https://www.youtube.com/watch?v=yaxUV3Ib4vM

我仍然关注本教程:spring-mvc-radiobutton-and-radiobuttons-example并且到目前为止我已创建此控制器:

    @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);
    }
}

当然这个解决方案不起作用,因为重定向是GET类型。 我试图将最后两种方法融合在一起,如下所示:

    @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);
    }
}

但通过这种方式验证不起作用。我不知道如何解决这个问题,我想使用弹簧验证器,但如果我不能使用它,我会退回该项目,这是一种耻辱。

1 个答案:

答案 0 :(得分:0)

如果有人在遵循同一指南时遇到问题,我建议您使用更简单的方法,例如:https://www.youtube.com/watch?v=yaxUV3Ib4vM 它没有更新maven依赖