简体   繁体   English

当我尝试在Spring Boot和MVC中使用get映射时发生异常

[英]Exception when I try use get mapping in Spring Boot and MVC

I have a simple getmapping: 我有一个简单的getmapping:

@GetMapping(value = "{user}")
    public String edit(@PathVariable User user, Model model) {
        model.addAttribute("user", user);
        return "userEdit";
    }

On my view I provide only entity Id: 我认为我仅提供实体ID:

<tr>
   <td>${user.name}</td>
   <td><a href="/user/${user.id}">Edit</a></td>
</tr>

And finaly in my DB I have this entity: 最后,在我的数据库中,我有这个实体:

@Entity
@Table(name = "users")
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

}

But when I try to use my controller i get this exception: 但是,当我尝试使用控制器时,会出现以下异常:

There was an unexpected error (type=Bad Request, status=400). 发生意外错误(类型=错误的请求,状态= 400)。 Failed to convert value of type 'java.lang.String' to required type 'com.newtwitter.model.User'; 无法将类型“ java.lang.String”的值转换为必需的类型“ 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'; 嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型[java.lang.String]转换为类型[@ org.springframework.web.bind.annotation.PathVariable com.newtwitter.model.User]获取值'1'; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Provided id of the wrong type for class com.newtwitter.model.User. 嵌套的异常是org.springframework.dao.InvalidDataAccessApiUsageException:为com.newtwitter.model.User类提供了错误类型的ID。 Expected: class java.lang.Long, got class java.lang.Integer; 预期:类java.lang.Long,得到类java.lang.Integer; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class com.newtwitter.model.User. 嵌套异常是java.lang.IllegalArgumentException:为com.newtwitter.model.User类提供了错误类型的ID。 Expected: class java.lang.Long, got class java.lang.Integer 预期:类java.lang.Long,得到类java.lang.Integer

Can I fix it? 我可以解决吗?

Essentially your controller method takes a User Object as a param but the framework has a String and this cannot be converted to an instance of a User. 本质上,您的控制器方法将User Object作为参数,但是框架具有String,并且不能将其转换为User的实例。

Your code as it stands is supported however you need to be using Spring data (which you probably are) and have the Spring Data MVC extensions enabled in order for this conversion to happen automatically. 您的代码,因为它代表不过支持你需要使用Spring数据(你可能是),并具有启用,以使这种转换的数据春MVC扩展自动发生。

This is documented in the manual (4.8.2. Web support): 手册(4.8.2。Web支持)中对此进行了记录:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web

which notes that adding @EnableSpringDataWebSupport to your configuration: 注意到将@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. 一个DomainClassConverter,可让Spring MVC从请求参数或路径变量解析存储库管理的域类的实例。

Without the Spring Data web extension you would need to change the method signature to the following and look up the instance manually. 如果没有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";
}

You are accepting User object in controller but sending an id from front end so this error is occurring so you can Change method to like below. 您正在控制器中接受User对象,但从前端发送ID,因此发生此错误,因此您可以将方法更改为如下所示。

@GetMapping(value = "{id}")
    public String edit(@PathVariable Long id, Model model) {
        User user = userService.read(id); //read user from the DB by id
        model.addAttribute("user", user);
        return "userEdit";
 }

UPDATE : 更新:

Otherwise you should follow the below approach to update the user by using modelattribute which will contain the full updated object, you just have to save it to DB directly. 否则,您应该按照以下方法使用modelattribute来更新用户,该属性将包含完整的更新对象,您只需将其直接保存到DB。

@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(User user, BindingResult bindingResult, Model uiModel,
            HttpServletRequest httpServletRequest)
    {
        //update user
        uiModel.addAttribute("user", user);
        return "updatedSuccess.jsp";
    }
@GetMapping(value = "{user}")

Change value to string, you can not pass object to endpoint. 将值更改为字符串,则无法将对象传递给端点。

public String edit(@PathVariable User user, Model model) {
        model.addAttribute("user", user);
        return "userEdit";
    }

Change @PathVariable to @RequestBody, so you can access user as object.Or you can change as below: 将@PathVariable更改为@RequestBody,以便可以将用户作为对象访问。也可以按以下方式进行更改:

@GetMapping(value = "user/{id}")
    public String edit(@PathVariable String id, Model model) {
// you can get user information base on id here
        model.addAttribute("user", user);
        return "userEdit";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么当我尝试在servlet映射开始时不带“ /”的情况下出现异常 - Why do I get an exception when I try a servlet mapping without the “/” in the beginning 我的 Spring 引导项目出现映射异常 - I have Mapping Exception on my Spring Boot project 当我尝试在 TomCat 上部署和执行这个使用 Spring 的应用程序时,为什么会出现此异常? - Why I obtain this exception when I try to deploy and execute on TomCat this application that use Spring? 如何使用Spring MVC框架为Spring Boot应用程序加载jsp页面? 我得到空指针异常 - How do I load the jsp pages using Spring MVC framework for a Spring Boot application? I get null pointer exception 我尝试在春季引导中使用undertow,但这是错误的 - I try use undertow in spring boot ,but it's error Restful Spring启动应用程序中的异常映射 - Exception Mapping in Restful Spring boot application 当我尝试在Spring Boot应用程序中访问URL时找不到页面 - page not found when I try to access URL in Spring Boot application Spring MVC-如何在Intercetor中获取映射信息 - Spring mvc - How can I get mapping info in intercetor Spring MVC自定义异常映射不起作用 - Spring MVC Custom exception mapping not working 如何查看Spring MVC请求映射异常 - How to view Spring MVC request mapping exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM