Reputation: 43
I've got simple WebApp who is have two tables Clothes
and Shoes
.
What is the best practice to create Controllers because both of they have CRUD methods.
I have two controllers like this:
@Controller
@RequestMapping("/shoes")
@Component
public class ShoesController {
private ShoesService shoesService;
@Autowired
public void setShoesService(ShoesService shoesService) {
this.shoesService = shoesService;
}
public ShoesService getShoesService() {
return shoesService;
}
@RequestMapping(value = "/view/all", method = RequestMethod.GET)
public @ResponseBody
List<Shoes> getAllShoes(){
return shoesService.getAllShoes();
}
@RequestMapping(value = "/byId/{id}", method = RequestMethod.GET)
public @ResponseBody
Shoes getShoesById(@PathVariable ("id") Integer id, Shoes shoes){
//TODO remove hardcoded values
return shoesService.getShoesByID(id, shoes);
}
@RequestMapping(value = "/view/{columnName}={value}", method =
RequestMethod.GET)
public @ResponseBody
List<Shoes> getByColumnValue(@PathVariable ("columnName") String colunmName,
@PathVariable("value") String columnValue, Shoes shoes){
//TODO remove hardcoded values
return shoesService.getByColumnValue(colunmName, columnValue, shoes);
}
@RequestMapping(value = "/edit/id={id}", method = RequestMethod.GET)
public @ResponseBody
Shoes update(@PathVariable ("id") Integer id, Shoes shoes){
shoes = getShoesById(id, shoes);
shoes.setShoesSeason("SPRINGGG");
shoesService.updateShoes(shoes);
return shoes;
}
@RequestMapping(value = "/delete/{id}", method =RequestMethod.GET)
public @ResponseBody
List<Shoes> delete(@PathVariable ("id") Integer id, Shoes shoes){
shoes = getShoesById(id, shoes);
shoesService.delete(shoes, id);
return getAllShoes();
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public @ResponseBody
List<Shoes> add (Shoes shoes){
shoes = new Shoes(333666, "Blue", "Autumn", "Noski", "URL");
shoesService.add(shoes);
return shoesService.getAllShoes();
}
}
Clothes
controller has the same realisation.
What is the best practice of realisation controllers whith same functionality ?
Upvotes: 3
Views: 73
Reputation: 675
You can also create a parent class and use inheritance. In this way, all child classes will have the same methods as the parent classes. If any specific method is required, it can be created directly in the child class.
Upvotes: 1
Reputation: 196
I think that good and simple solution is to use Spring Data REST. You can also create abstract controller which may be parametrized by the type you want to use with it.
Upvotes: 2