I am developing a Spring Web MVC application. I have query related to CRUD or complex operation.
My question is where to put our logic, in the controller or in-service layer?
Currently, I am writing all code in controller and call save()
or delete()
methods of service
in the controller
.
See below code examples. Please help me to find the correct way to code.
Controller level:
@Controller
@RequestMapping(value = "/Shipping")
public class ShippingController {
@Autowired
private ShippingService shippingService;
@RequestMapping(value = "/addNewShippingMethod/{id}", method = RequestMethod.POST)
public String addshippingMethod(@PathVariable("id") String id, HttpServletRequest request) {
Shipping shipping=new Shipping();
shipping.setName(request.getParameter("name"));
shippingService.save(shipping);
return "/Shipping/ShippingMethodList";
}
}
@Service
public class ShippingService {
@Autowired
private ShippingMethodRespository shippingMethodRespository;
public ModelAndView saveShippingMethod(HttpServletRequest request, String id) {
shippingMethodRespository.save(shipping);
}
}
Service level:
@Controller
@RequestMapping(value = "/Shipping")
public class ShippingController {
@Autowired
private ShippingService shippingService;
@RequestMapping(value = "/addNewShippingMethod/{id}", method = RequestMethod.POST)
public ModelAndView addshippingMethod(@PathVariable("id") String id, HttpServletRequest request) {
return shippingService.saveShippingMethod(request, id);
}
}
@Service
public class ShippingService {
@Autowired
private ShippingMethodRespository shippingMethodRespository;
public ModelAndView saveShippingMethod(HttpServletRequest request, String id) {
Shipping shipping=new Shipping();
shipping.setName(request.getParameter("name"));
shippingMethodRespository.save(shipping);
ModelAndView shippingMethodsPage = new
ModelAndView("/Shipping/ShippingMethodList");
return shippingMethodsPage;
}
}
I have described both scenarios first one is: we save all data from the controller and return to the page.
The second one is: use a controller for redirect and writing logic and save data in the service layer.
Can you please tell me which is the best way to do code?