java - 当我尝试在 Spring Boot 和 MVC 中使用 get 映射时出现异常

标签 java spring-mvc spring-boot jpa spring-data

我有一个简单的 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/

相关文章:

java - 找不到适合 jdbc :mysql://127. xx.xxx.x:3306/的驱动程序

java - 使用 DateFormat.getDateTimeInstance().format(date);

java - 为什么如果我从 IDE (Eclipse) 启动一个 Spring Boot 应用程序作为 Java 应用程序,它可以工作,但是当我从 CMD 启动它时,它会出现 Whitelabel 错误?

spring-boot - spring-boot/spring cloud 升级后,Spring Cloud Sleuth 停止将 X-B3-TraceId 推送到 MDC

Java 版本的 mongo 查询,用于从数组中检索唯一字符串以及计数

java - 无法解决 Intellij IDEA IDE 中 Scalatra 项目的错误

java - 如何将我的 Java 程序转换为 .exe 文件?

java - 避免已存在的更新验证并在 Spring MVC 中进行更新

java - 限制ip地址访问web服务

model-view-controller - Spring 3 的 MVC 框架生产质量中的 REST 支持了吗?