简体   繁体   中英

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

I have a simple 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:

<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). 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

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.

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.

This is documented in the manual (4.8.2. Web support):

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

which notes that adding @EnableSpringDataWebSupport to your configuration:

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.

Without the Spring Data web extension you would need to change the method signature to the following and look up the instance manually.

@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.

@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.

@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:

@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";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM