0
You could tell me the difference between classes in the package "control" in a MVC project and service classes?
0
You could tell me the difference between classes in the package "control" in a MVC project and service classes?
2
Citing Spring MVC as an example I like to separate the MVC project into Model, View, Control and Service. The reason is that in my projects I don’t like to leave business rules directly in the Controller. So I delegate this to the Service. Example:
@RequestMapping(value = "/novo", method = RequestMethod.POST)
public ModelAndView cadastrar(@Valid Cerveja cerveja, BindingResult result, Model model, RedirectAttributes attributes) {
if (result.hasErrors()) {
return novo(cerveja);
}
/* Eu poderia deixar dezenas de linhas relativas as regras de negócio
de como salvar uma cerveja aqui. */
cadastroCervejaService.salvar(cerveja);
attributes.addFlashAttribute("mensagem", "Cerveja salva com sucesso!");
return new ModelAndView("redirect:/cervejas/novo");
}
In this code, the Controller basically only receives data from the View and returns validation errors (if any). If there are no errors, it triggers Service to save the record and returns a success message.
The point here is that every business rule of saving an object Beer could be inside the Controller, but the Controller would receive, save, and return data. What if there were too many business rules? It would get very polluted the code so I transferred all the business rules relating to saving a beer to the Cadastrocervejaservice. So the Controller just calls.
In my view, it is more a decision of taste even, I prefer this way for the sake of organization.
Browser other questions tagged java java-ee
You are not signed in. Login or sign up in order to post.
A yes friend, now I understand, thank you very much.
– Gabriel Martins
Nice. Glad I could help.
– Hélio Márcio Filho