在控制器方法内以 post 模式重定向

问题描述 投票:0回答:1

编辑: 如果有人在遵循以下指南时遇到问题,我建议使用更简单的方法,例如: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);
    }
}

但是这样验证就不起作用了。我不知道如何解决这个问题,我想使用 spring 验证器,但如果我不能使用它,我将回归该项目,这是一个耻辱。

java spring spring-mvc spring-boot spring-validator
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.