首页 > 解决方案 > Spring Boot:从 @RequestParam("id") 获取对象

问题描述

我正在尝试通过单击此表单中的删除按钮来删除对象:

<form action="/applications/delete" method="get">
  <input type="hidden" name="_csrf" value="${_csrf.token}"/>
  <input type="hidden" name="applicationId" value="${application.id}"/>
  <button type="submit" class="btn btn-primary btn-block">
    <p class="Btn">Delete</p>
  </button>
</form>

我进入applicationId我的

@GetMapping("/delete")
public String deleteApplication(@AuthenticationPrincipal User user, @RequestParam("applicationId") Application application, Model model)

但我有一些奇怪的例外:

2019-04-25 22:08:07.248  WARN 7492 --- [nio-8080-exec-9] o.h.e.l.internal.CollectionLoadContext   : HHH000160: On CollectionLoadContext#cleanup, localLoadingCollectionKeys contained [1] entries
2019-04-25 22:08:07.249  WARN 7492 --- [nio-8080-exec-9] o.h.e.loading.internal.LoadContexts      : HHH000100: Fail-safe cleanup (collections) : org.hibernate.engine.loading.internal.CollectionLoadContext@29b119a7<rs=HikariProxyResultSet@1925344473 wrapping Result set representing update count of -1>
2019-04-25 22:08:07.250  WARN 7492 --- [nio-8080-exec-9] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'JobHunter.domain.Application'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam JobHunter.domain.Application] for value '1'; nested exception is java.lang.NullPointerException]

所以它不能从 String = '1' 转换为 Application 对象。

我在另一个模板中使用完全相同的东西

<form action="/vacancy/add" method="post" class="form-inline">
  <input type="hidden" name="_csrf" value="${_csrf.token}"/>
  <select name="departmentId" class="custom-select mb-2 mr-sm-2">
    <option value="" disabled selected hidden>Select department</option>
    <option value="${department.id}">${department.departmentName}</option>
  </select>
  <button class="btn btn-primary mb-2"= type="submit">Add</button>
</form>

另一个控制器:

public String add(@RequestParam("departmentId") Department department

它工作正常。所以我不知道出了什么问题。

标签: springhibernatespring-bootjpafreemarker

解决方案


刚刚使用@Getter@Setter而不是因为注释@Data中包含的 equals 和 hashCode 存在一些问题@Data


推荐阅读