stack man stack man - 2 months ago 13
Java Question

Any hint to simplify this POST? (Java)

I implemented this POST operation in Jax-RS and it is working fine, however I am sure I can send the body in other way somehow. Any hint to simplify it? (By receiving an object for instance?)

Thanks!

@POST
@Path("updateUser/{name}/{surname}/{address}")
@Produces(MediaType.TEXT_PLAIN)
public Response updateUser(@FormParam("user") String name,
@FormParam("surname") String surname,
@FormParam("address") String address) throws UnknownHostException {
User user;
user = new CorporateUser(name, surname, address);
usersService.updateUser(user);
return Response.ok(user).build();
}

Answer

Add a JSON provider like Jackson to your project.

@POST
@Path("updateUser")
@Consumes(value = { MediaType.APPLICATION_JSON })
@Produces(value = { MediaType.APPLICATION_JSON })
public Response updateUser(NewCorporateUserRequest req) throws UnknownHostException {
      User user;
      user = new CorporateUser(req.getName(), req.getSurname, req.getAddress); 
      usersService.updateUser(user);
      return Response.ok().entity(user).type(MediaType.APPLICATION_JSON).build();
}

public class NewCorporateUserRequest implements java.io.Serializable {

    private String name;
    private String surname;
    private String address;

    ... Getters and Setters.

}
Comments