java - 使用多个表单在 View 上提交表单时出现 Spring "Neither BindingResult nor plain target object for bean name"错误

标签 java spring spring-mvc spring-boot thymeleaf

目前我遇到了相当棘手的问题,并且找不到解决方法。我在我的项目中使用 Thymeleaf 和 Spring Boot。我在这里和其他论坛上查看了各种主题,但没有解决上述问题。 我有一个包含两个非嵌套表单的 View ,具有单独的提交按钮和单独的操作:

<form id="bidForm" th:action="@{'/auction/bid/' + ${auctionDto.id}}" 
th:object="${bidDto}" method="post">
/* more html code here */
</form>

<form id="buyoutForm" th:action="@{'/buyout/confirm-buyout'}" 
th:object="${buyoutDto}" method="post">
/* more html code here */
</form>

View 是通过 Controller 中的以下方法生成的:

@GetMapping("/get/{id}")
public ModelAndView getAuction(@PathVariable String id) {
    ModelAndView modelAndView = new 
    ModelAndView(Templates.AuctionTemplates.ITEM);
    modelAndView.addObject("auctionDto", getAuctionService.getOne(id));
    modelAndView.addObject("bidDto", new BidDto());
    modelAndView.addObject("buyoutDto", new BuyoutDto());
    return modelAndView;
}

th:action 中指定的方法映射位于两个不同的 Controller 中。 具有“bidForm”操作的 Controller :

@Controller
@RequestMapping("/auction")
public class AuctionController {

   @PostMapping("/bid/{id}")
   public ModelAndView bid(@PathVariable String id, 
    @ModelAttribute("bidDto") 
    @Valid BidDto bidDto, BindingResult bindingResult, Principal principal) {
    /* more code here */
    }
}

对于“buyoutForm”:

@Controller
@RequestMapping("/buyout")
public class BuyoutController {

    @PostMapping("/confirm-buyout")
    public ModelAndView confirmBuyout(@Valid @ModelAttribute("buyoutDto") 
    BuyoutDto buyoutDto) {
        ModelAndView modelAndView = new ModelAndView();
        return modelAndView;
        }
   }

现在,问题是:当我使用相应的按钮提交“bidForm”时,出现错误:

Neither BindingResult nor plain target object for bean name "buyoutDto"

我不知道为什么 Spring 在“bid”方法中需要一个“BuyoutDto”类的对象。这是我第一次遇到这个问题。你能帮我解决一下吗?问候,卢卡斯。

最佳答案

我认为发生错误是因为在您的出价方法中您没有返回对象 buyoutDto。当您从此方法返回时,您是否会再次进入同一页面(具有两个表单的页面)?

例如,您的代码应该如下所示

@PostMapping("/bid/{id}")
   public ModelAndView bid(@PathVariable String id, 
    @ModelAttribute("bidDto") 
    @Valid BidDto bidDto, BindingResult bindingResult, Principal principal) {
         /* more code here */
         modelAndView.addObject("buyoutDto", new BuyoutDto());
    }

关于java - 使用多个表单在 View 上提交表单时出现 Spring "Neither BindingResult nor plain target object for bean name"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48223932/

相关文章:

java - 访问 Spring/Maven 应用程序中的资源文件夹

java - Spring MVC动态列表表单提交

java - 如何为过滤器创建 HATEOAS 链接?

java - 监控数据库的连接数

java - 我的程序崩溃了,我不知道为什么

java - 将超链接插入 XWPFTableRow

java - 如何从 Spring Web 应用程序返回一个字符串作为有效的 JSON?

java - 是否有更好的方法来减少长时间运行的 quartz 作业的执行时间?

java - Spring Boot或者Tomcat缓存静态资源,每次刷新都得重新构建

java - 面临空指针异常