有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

控制器方法内post模式下的java重定向

编辑: 如果有人在遵循下面的指南时遇到问题,我建议使用一种更简单的方法,例如: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验证器,但如果我不能使用它,我将退回项目,这是一个耻辱


共 (1) 个答案