简体   繁体   中英

Jersey: Best practice handling restful HTTP PUT (update) request

Suppose I have very simple User class:

@JsonIgnoreProperties({"password", "created", "lastModified"})
public class User {
    public String id;
    public String name;
    public String password
    public Long created;
    public Long lastModified;
}

When we serialize a User entity to JSON string, we filter out password , created and lastModified . And then user at the front end will update the user's name and put the user back to our Restful service.

And my pseudo controller method handling the PUT request:

@Path("/user/{id}")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void saveUpdate(@PathParam("id")String id, User user) {
    userService.save(user);
}

In the above method I expect Jackson will deserialize the JSON string sent by front end to the POJO user instance, and then call our service to save the instance.

So far everything looks cool. However the concern raised when we pass the user POJO to userService to save it. Remember we have three properties ignored when we serizalize the user into JSON: password , created , lastModified , and we have to get the value of those missing properties from database and then merge with the data sent through from front end.

Doing the merge operation is a very simple but tedious task for coder. I was wondering if there is any good practices to handle this case in an easy and elegant way

I suppose User object is entity object that is going to be saved into DB so Best practice is not to expose entity objects to FE but use DTO objects that contains only fields that FE needs to know about (consider to hide id aswell and use UUID instead as id values are predictable). Later you can map such DTO object to Entity by using ModelMapper so you can easily merge between userDTO and user entity objects and then just persist entity without worrying about state of missing fields

Moreover nowdays many web services disabling PUT requests for their applications and uses POST instead. I don't familiar much with reason why but that was one of the security issues when we passed out application to security checks

I think the concern is more about your service instead of the REST API. I mean, if user's 3 properties "password", "created" and "lastModified" shouldn't be visible to the presentation layer, then the service should be able to handle saving without them.

In the persistent layer, you can definitely update User without all properties populated. Or a better design, let's separate UserLogin("id", "password", "created", "lastModified") and User("id", "name") which point to the same DB table. Then an update on User doesn't need other unnecessary properties at all.

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