我有一个简单的 getmapping:
@GetMapping(value = "{user}")
public String edit(@PathVariable User user, Model model) {
model.addAttribute("user", user);
return "userEdit";
}
在我看来,我只提供实体 ID:
<tr>
<td>${user.name}</td>
<td><a href="/user/${user.id}">Edit</a></td>
</tr>
最后在我的数据库中我有这个实体:
@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
}
但是当我尝试使用我的 Controller 时,我得到了这个异常:
There was an unexpected error (type=Bad Request, status=400). Failed to convert value of type 'java.lang.String' to required type 'com.newtwitter.model.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.PathVariable com.newtwitter.model.User] for value '1'; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Provided id of the wrong type for class com.newtwitter.model.User. Expected: class java.lang.Long, got class java.lang.Integer; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class com.newtwitter.model.User. Expected: class java.lang.Long, got class java.lang.Integer
我可以修复它吗?
最佳答案
本质上,您的 Controller 方法将用户对象作为参数,但框架有一个字符串,并且它无法转换为用户的实例。
您的代码目前受支持,但是您需要使用 Spring 数据(您可能就是这样)并启用 Spring Data MVC 扩展才能自动进行此转换。
这在手册中进行了记录(4.8.2. Web 支持):
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web
其中指出将 @EnableSpringDataWebSupport
添加到您的配置中:
registers a few basic components:
[including]
A DomainClassConverter to let Spring MVC resolve instances of repository-managed domain classes from request parameters or path variables.
如果没有 Spring Data Web 扩展,您需要将方法签名更改为以下内容并手动查找实例。
@GetMapping(value = "{user}")
public String edit(@PathVariable Long userId, Model model) {
User user = //user userId to fetch
model.addAttribute("user", user);
return "userEdit";
}
关于java - 当我尝试在 Spring Boot 和 MVC 中使用 get 映射时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53554475/