Reputation: 1854
I don't know this is the right approach but the easiest solution I can come up with in the moment.
I want to use multiple values in @RequestMapping and do the business logic in the method according which value is called the method. Example:
@RequestMapping(value = {"/delete", "/save"}, method = RequestMethod.POST)
public String crudOps(@ModelAttribute ("userForm") User user) {
// find user in repository....
if(value is delete) // don't know how to make this check
delete(user);
else
save(user);
}
How can I make that if statement work?
Upvotes: 1
Views: 7814
Reputation: 4621
I would personally go ahead with something like below,
@RequestMapping(value = "user/{userid}", method = RequestMethod.DELETE)
And use
@RequestMapping(value = "/save", method = RequestMethod.POST)
for creating an user. This helps in Single Responsibility Principle and more modular code. Let your method do one thing, and do it right!
Would recommend this link for using which HttpMethod for which purpose.
Upvotes: 1
Reputation: 3073
You can use @PathVariale to grab part of the URL as follows
@RequestMapping(value = /{action}, method = RequestMethod.POST)
public String crudOps(@PathVariable String action, @ModelAttribute ("userForm") User user) {
// find user in repository....
if(action.equals("delete"))
delete(user);
else
save(user);}
Upvotes: 1
Reputation: 1377
fter adding a comment above, I thought of a different solution by accessing the HttpServletRequest getServletPath method,
@RequestMapping(value = {"/delete", "/save"}, method = RequestMethod.POST)
public String crudOps(@ModelAttribute ("userForm") User user, HttpServletRequest request) {
// find user in repository....
if(request.getServletPath().equals("/delete"))
delete(user);
else
save(user);
}
Upvotes: 5