Service layer and controller: who takes care of what?

Generally a Spring service is transactional. Things go into a particular service method because they ought to be grouped together in the same transaction. If you want to retrieve an object from the database, twiddle it, and save the new version, the retrieval and save ought to be in the same service method. So your service methods are determined according to what you need the application to do for the user.

I try to restrict controllers to doing work related to validating http parameters, deciding what service method to call with what parameters, what to put in the httpsession or request, what view to redirect or forward to, or similar web-related stuff.

As far as validation goes: Validating input parameters in the controller is a good thing to make sure nobody can break your application with bogus inputs. Validation in the controller tends to be about making sure the inputs are syntactically ok (including detecting injection attacks) while service-level validation is about making sure the state of things in the database is what you expect it to be.

So controllers contain web-framework infrastructure code, services contain application logic code.

Leave a Comment