I want to know the use of service classes in J2EE.
I have 2 projects.
One is in spring hibernate integration.That project contain DAO,MODEL,SERVICE and CONTROLLER.Within that The request is access by the controller and send to the values to the dao class through the service class.
2nd project contain only BEAN,CONTROLLER and DERIVED classes.Within that the request is access by the controller and send the values directly to the derived class.Query is written in this derived class.
I want to know the difference between these two projects. Why we use service class ?
in my experience, service class contains all business , calculate, logic
for example in login module :
base on MVC pattern
Model class (DAO,MODEL is call model) : User, UserDAO
Controller : UserController
View : LoginPage
That's doesn't mean we cannot create another class like Service
we can have UserBusinessthis class contain all method, logic realted to User like validateUserLogin ... etc
application may work like :
User access LoginPageinput value and submit => UserController=> UserBusiness=> UserDAO
we need divide to easy handle and maintain
In spring we have some annotation like
#Business
#Repository
#Controller
that is a maker spring will create a object , we no need to using "new" keyword.
Controllers: are used to just delegating the calls, meaning once the request arrive on controller it will forward it to relative service
Services: Service are develop to write the business logic in general.
Dao: Data transfer object, which intend to deal with the DTO's
So, Briefly, when Spring MVC receive a call. I will lend to controller, controller than redirects it to respective service. Service performs business login if any on the api call and than delegated data updation to DAO layer.
Related
There are a lot of definitions on what MVC is, but most of them say that the user contacts the controller and then the controller changes the view and sends it to the user. If I am using React.js for my frontend and calling endpoints in my controller, am I still using MVC pattern or not?
Is the #Controller even the same thing as the controller in MVC because in the definitions it says that the controller handles the application logic which in my case it does not I have service classes for that. I am writing an essay and I don't even know what type of application I am creating. It is driving me nuts.
Yep, it's still MVC. In this case you have controller (Spring #Controller or #RestController and React) model (services) and view (html generated by React). There is no strict definition what is MVC.
In MVC controller should not contain logic themself, but communicate with model (your services), this is the correct layered backend architecture. Otherwise, the Single Responsibility Principle is violated.
Spring Controller i.e., #Controller is the responsible person to provide the view the user requested if you need only the view page, it can be anything .html,.JSP and many more. So, if the user requested for any page either by the react.js or anything like angular then it calls the dispatcher servlet of the spring front controller and calls the handler mapper to which controller the user have requested.
If you requested something from the client to provide or do some crud operation then Rest Controller comes into the picture where #RestController...#Service...#Repository is been used.
So indirectly, the spring provides the way where developers can define the user request in the model view and controller format in which it segerrate the things separately and provides more convenient way to organise the code it looks like and spring have assigned annotations where it marks the class the responsibility it should behave.
Environment :
Spring MVC 3
Angular JS
Tomcat 6
Issue :
We are migrating a legacy application from struts2 to spring MVC REST with angular JS as UI.
This is a typical SPA.
The typical application flow is : Angular JS + Spring REST controller + Servicelayer
The business logic in struts2 actions is moved to service classes.
My question is - What is the correct way to make HttpServetRequest object available to Service classes in Spring ?
Two options available are :
1)Pass HttpServletRequest to Spring MVC controller method. Pass the same HttpServetRequest to Spring service layer.
But this will result in HttpServletRequest being part of Service interface like -
public ProductDto getProductDetails(HttpServletRequest req,int productId)
Is this a correct way ? Can HttpServletRequest be part of Service interface ?
2)Use Spring provided API :
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Please guide on this ?
In addition to those mentioned options, you can introduce a class or another abstraction into your service layer, then populate it with the required parts of the HttpServletRequest and use that abstraction inside the Service Layer.
For example (Borrowed from Spring Data), Suppose you want to access to page, size and sort and user related query strings from the HttpServletRequest. Instead of passing the request to the service layer methods, you can also encapsulate those parameters into an abstraction, say, Pageable or UserFilterCriteria:
public interface Pageable {
int page();
int size();
List<Sort> sorts();
}
Then instead of passing the HttpServletRequest to the service layer:
public interface UsersService {
List<User> filterUsers(HttpServletRequest request);
}
You can pass those new abstractions:
public interface UsersService {
List<User> filterUsers(UserFilterCriteria criteria, Pageable pageable);
}
This way you can easily define abstractions in the same level of abstraction as your service layer.
You should rather not make HttpServletRequest/-Response be part of your service-layer, as HttpServletRequest/-Response are classes specific to your user interface/view technology.
Introducing them to your service layer will make your service layer depend on the technology used for the user interface, thus making it harder to change the UI/View technology later.
I have a Spring form which is called AddNewItemForm and contains the validation annotations.
This form is the parameter of my Spring RestController addNewItem() method and it will be validated, the results being stored in BindingResults.
From my controller I need to call the service. Here is my question. Is it ok to have a method inside my service with this signature
public Item add(AddNewItemForm form)
or is it better to have it like
public Item add(Item item)
I am thinking that the form is only needed for the controller validation but the service doesn't need to know about it. It just needs to know how to operate with entities.
I suppose that I should construct my Item in the controller, with all the data I have and then pass this item to the service add(item) method.
Am I right?
Think of it in terms of dependencies: your web layer always needs to know about your service module and by passing the AddNewItemForm (which I assume exists in your web module/package) back to your service you now have a circular dependency.
Dependencies should only flow downwards:
Repository > Service > Web
From my point of view the service should not know about your command object (AddNewItemForm) since they are totally independent.
I agree with your last suggestion, you have to construct your model object before calling your service. Basically in your controller or with the help of an utility class.
Spring MVC application with JPA
I have flow of my application like:
#Controller
Class
---> returning a view (JSP) page.
Before returning to view I would like to modify contents or before sending it to entity persistence service layer , would like some values to be altered.Where shall I introduce those classes?
EDIT :
I am clear about rendering the data from database and displaying to front view.
What I actually want to ask is like :
A a = aService.findXXX(aId);
//here i want some operations to be performed for specific view while converting it to dto and sending it to UI.
Where the class for doing the same would be introduced else my controller will have very large line of code sp. to what has to be displayed to sp. view?
As #chrylis said, it's not very clear what you are asking. But if I understood you correctly, this will help you.
The usual pattern is that your #Controller has a #Autowired service reference
#Autowired
private MyService myService;
and that #Service has a #Autowired reference to DAO class (annotated with #Repository). Service encapsulates business logic, and DAO layer is responsible for interaction with database.
In your case, you would call some service method from controller, service would alter the entity and pass it down to DAO, and controller then fills the necessary data to Model which is used for rendering appropriate view.
Lets assume a simple Spring MVC Controller that receives the ID of a domain object. The Controller should call a service that should do something with that domain object.
Where do you "convert" the ID of the domain object into the domain object by loading it from the database? This should not be done by the Controller. So the service method interface has to use accept the ID of the domain object instead of the domain object itself. But the interface of the service would be nicer if it takes the domain object as a parameter.
What are your thoughts about this common use case? How do you solve this?
The controller should pass the id down into the service layer and then get back whatever is needed to render the rest of the HTTP response.
So -
Map<String,Object> doGet (#RequestParam("id") int id) {
return serviceLayer.getStuffByDomainObjectId(id);
}
Anything else is just going to be polluting the web layer, which shouldn't care at all about persistence. The entire purpose of the service layer is to get domain objects and tell them to perform their business logic. So, a database call should reside in the service layer as such -
public Map<String,Object> getStuffByDomainObjectId(int id) {
DomainObject domainObject = dao.getDomainObjectById(id);
domainObject.businessLogicMethod();
return domainObject.map();
}
in a project of mine I used the service layer:
class ProductService {
void removeById(long id);
}
I think this would depend on whether the service is remote or local. As a rule I try to pass IDs where possible to remote services but prefer objects for local ones.
The reasoning behind this is that it reduces network traffic by only sending what is absolutely necessary to remote services and prevents multiple calls to DAOs for local services (although with Hibernate caching this might be a mute point for local services).