Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@RequestMapping(method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseStatus(HttpStatus.CREATED)
void create(@RequestBody @Valid User user, HttpServletRequest request, HttpServletResponse response) {
long userId = userService.create(user);
String location = ServletUriComponentsBuilder.fromRequestUri(request).path("/{userid}")
.build()
.expand(userId).toUriString();
response.addHeader("Location", location);
}
@RequestMapping(value = "/{userId}",
method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
void delete(@PathVariable("userId") long userId) {
userService.delete(userId);
}
@RequestMapping(value = "/{userId}",
method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseBody
User read(@PathVariable("userId") long userId) {
return userService.read(userId);
}
@RequestMapping(value = "/{userId}",
method = RequestMethod.PUT,
consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseStatus(HttpStatus.NO_CONTENT)
void update(@PathVariable("userId") long userId, @RequestBody @Valid User user) {
userService.update(userId, user);
}
@XmlRootElement
public class User {
@NotBlank
@Length(min = 3, max = 30)
private String name;
@Email
private String email;
public User() {
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@Controller
@RequestMapping("/user")
class UserController {
private final UserService userService;
@Autowired
UserController(UserService userService) {
this.userService = userService;
}
// TODO implement CRUD methods
}
public interface UserService {
long create(User user);
User read(long userId) throws UnknownUserException;
void update(long userId, User user) throws UnknownUserException;
void delete(long userId) throws UnknownUserException;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.