Where to use FacesContext object? [duplicate] - jsf

I am not sure whether my approach with the MVC environment in JSF is the best way to go. Since I am trying to get the most out of JSF I would like to know how my Service Layer (or Model, speaking in MVC terms) should be 'designed'.
I know the View-Controller ratio should be 1 to 1 (exceptions ruled out).
Now in what way should I design my Service Layer? Should I use one big service (don't think so)? If not, based on what should I split my services?
Note, my Service will be called from the Beans (Controllers in MVC terms) and the Service itself will call DAO's using JPA when necessary.
Thanks in advance

The service layer (the business model) should be designed around the main entity (the data model). E.g. UserService for User, ProductService for Product, OrderService for Order, etc. You should absolutely not have one huge service class or so. That's extreme tight coupling.
As to the service layer API itself, Java EE 6 offers EJB 3.1 as service layer API. In the dark J2EE ages, long time ago when EJB 2.0 was terrible to develop with, Spring was more often been used as service layer API. Some still use it nowadays, but since Java EE 6 has incorporated all the nice lessons learnt from Spring, it has become superfluous. Note that EJB (and JPA) is not available in barebones servletcontainers such as Tomcat. You'd need to install for example OpenEJB on top of it (or just upgrade to TomEE).
Regardless of the service layer API choice, best would be to keep your JSF backing bean (action)listener methods as slick as possible by performing the business job entirely in the service layer. Note that the service layer should by itself not have any JSF dependencies. So any (in)direct imports of javax.faces.* in the service layer code indicates bad design. You should keep the particular code lines in the backing bean (it's usually code which adds a faces message depending on the service call result). This way the service layer is reuseable for other front ends, such as JAX-RS or even plain servlets.
You should understand that the main advantage of the service layer in a Java EE application is the availability of container managed transactions. One service method call on a #Stateless EJB counts effectively as a single DB transaction. So if an exception occurs during one of any DAO operations using #PersistenceContext EntityManager which is invoked by the service method call, then a complete rollback will be triggered. This way you end up with a clean DB state instead of a dirty DB state because for example the first DB manipulation query succeeded, but the second not.
See also:
Creating master-detail pages for entities, how to link them and which bean scope to choose
When is it necessary or convenient to use Spring or EJB3 or all of them together?
JSF Controller, Service and DAO

The 1:1 ratio between services and model entities maybe not bad if you have few entities in your app. But if it is a big app, there would be too much services.
The number of services depends upon the use cases of the app you are designing. Once you have identified them in the analysis phase, you must group them in several groups according to their functionality. Each group of use cases will be a Service, and each use case will be a method in that service. Each Service can manage several model entities (and you have to inject in it the DAOs it needs to perform its functionality). Usually the uses cases of a Service manage model entities inter-realationated in the class diagram of the model. The Services might follow the good practice of "max cohesion / min coupling".
The ratio between DAOs and model entities is 1:1. Each DAO perform CRUD operations and queries of its entity. If a method needs to query 2 relationated entities, put it in the more suitable DAO depending on the business concepts.
In the JSF presentation layer I neither have a 1:1 ratio between pages and controllers, that would be too much controllers. I group into one contrller all the pages needed to perform the use cases of each service. So the ratio 1:1 is between controllers and services, injecting each service in the controller whose pages perform its use cases.
Of course, these are general principles. You may have some particular cases in the app that broke them, but they are few.
You might not have too much services and controllers, but not too few neither because then they would have too much logic and fields. You must acchieve a compromise.

Related

Should the pre-defined MVC ApplicationDbContext be moved to a different layer, domain or storage?

When using MVC5 I add a domain layer and storage layer using dependency injection for all the business data. But I have always left the ApplicationDbContext in the main MVC application layer project.
I've read a great many posts on SO and see many people recommend moving the ApplicationDbContext out of the MVC project. I'd like to understand why ApplicationDbContext should or should not be moved. Are there any reasons to not move this context?
On the one hand, ApplicationDbContext uses a data model which suggests it should be moved to the storage layer but that will require large DTO's. On the other hand, ApplicationDbContext really relates primarily to application access and I have a separate roles/permissions functionality for the business data anyway. Several SO posts also suggested checking roles in the application layer, not the domain layer, but that seems suspect; don't we want to check business roles in the domain layer?
So I'm confused and before I go to the work to move the ApplicationDbContext to a different layer, I'd like to make sure I'm making a sound and informed decision.
It is not a must, but it is advisable if you are doing DDD and your project tends to grow large.
Although DDD is not about implementation details, DDD asks for a clear separation of concerns. Then you should separate domain logic from infrastructure.
You could achieve that separation in many ways. One way would be to have a single project with folders for Domain, Application and Infrastructure, and have your DbContext reside in the Infrastructure folder. This is suitable for small projects.
In large projects, however, I would recommend you to evaluate the Clean Architecture, which will take this separation to project level.
I'd like to understand why ApplicationDbContext should or should not be moved. Are there any reasons to not move this context?
It can be moved, there's no rule against it. But the tooling will then require you to specify both startup and database projects as parameters, like this:
dotnet ef database update --project <path> --startup-project <path>
But since you're using MVC5, you're probably not using EF Core. In case of EF 6 or lower, you'll be using the Package Manager Console (PMC) to manage migrations and database-updates, which will make your life easier in that regard, since you can mark you MVC project as the Startup Project from the context menu, and select the target project from a dropdown control in the PMC.
Several SO posts also suggested checking roles in the application layer, not the domain layer, but that seems suspect; don't we want to check business roles in the domain layer?
Yes, roles are related to permissions, which are business rules. People probably recommend checking that in the application layer because you need to pull this data from the database, but you could do it like this:
Use the Specification Pattern to represent roles and permissions as an specification in the Domain Layer. But the IRepository interfaces would best be defined in Application Layer, as they represent infrastructure (which will be concretely implemented in the Infrastructure Layer). So you would start the role-checking in the Application Layer by using repositories to retrieve data, but the actual permission validation would be done by an Specification in the Domain Layer.
That would be one way to do it.

Why in JHipster DTOs are generated in the service layer and not in the REST layer?

We've started a JHipster project and used DTOs. At the beginning I wasn't fan, but then, this allowed us to really customize our DTOs for our REST layer: perfect.
But now we are adding JMS to the project and we realize that our message listeners need to access our service layer... but the services returns DTOs that are suited for the REST layer, not the messaging layer.
Why does JHipster generate the DTOs in the service layer ? Why not in the REST layer ? This way, both REST and JMS layer (and something else later) could access the service layer that only deals with entities. Then, both REST and JMS will have their own DTOs suited for their own needs.
Any idea why this was done on the first place ?
Thanks
In JHipster, you have in fact DTOs and VMs:
DTOs (Data Transfer Objects) are in the service layer: they are here to get data out of the transactional layer. The idea is that inside the service layer you have JPA entities, which have relationships (lazy loaded with Hibernate), and that the service layer returns DTOs which are not managed by Hibernate (no lazy loading anymore). There might not be a 1-to-1 relationship between entities and DTOs: maybe DTOs aggregate several entities, maybe they have more fields (or less fields!), that all depends on your business model.
VMs (View Models) are in view layer. This wording comes from Angular, where we often have "vm" objects. The idea is to have objects which are specific to your view layer, so it's easier, more secured and more performant to code the client application. There could be several VMs for one DTOs, as the DTO's data might be used in several different screens. Typically VMs are what is being transferred in JSON from the Java back-end to the JavaScript front-end.
None of those layers are mandatory with JHipster. You will typically have:
Just entities for simple CRUDs
Entities and DTOs for business code
Entities and VMs when there is a specific, complex view
Entities, DTOS and VMs when everything is complex

how to package backing bean controller manager facade business logic

I have looked at several JavaEE 6 login tutorials using servlet 3.0 and JSFtechnology. Often it shows a request scoped credentials bean and a user manager session bean. Most do not provide packaging info or for simplicity sake create everything in one package. I have been struggling with the packaging between the web tier and the business logic. I do not know if backing bean, controller, manager, and facade are all talking about the same thing or not. A short answer could tell me how to package a user manager session bean and the credentials bean, but a more appreciated answer would help me navigate the web tier and the business logic. Thanks in advance.
For packaging I like to break first by functionality (like core, gui) and then by business unit level.
for e.g
com.comp.db.beans // place your database beans here (if using any orm )
com.comp.web.ui.controller // place your controller, managedbeans here, this can be again broken into functionality wise like login, processing e.t.c.
com.comp.web.ui.beans //you place your vo here
In order to start packaging you have to first write down the different functionality of your system.
Then break them into business unit wise
Then break those into more finer level, to distinguish if functionality is going to be very specific to ui, or does it belong to core.

Java EE: separating presentation logic from business logic using beans

I've been developing my first Java EE app, which has a number of JPA entity classes, each of which have a corresponding EJB class for dealing with the business logic. What I've done is changed one of those beans from Stateless to SessionScoped, so I can use it to allow a user to work their way through a series of form fields, all of which are rendered on a JSF form.
However, I'm starting to think this is clearly wrong, as I'm doing things like implementing methods such as "submitStep1" and "goBackToStep2" in my EJB. These methods set indicators which are used by render elements of various tags on the JSF page, so they are clearly "presentation logic".
My question is, how should I re-structure my code? I'm thinking that I should just have one SessionScoped (or should that be stateful?) bean, which deals with the presentation logic of my JSF page, and is able to use all the other ejbs (and by extension my JPA classes). This bean would be in the presentation-tier level of my app, meaning my business logic tier wouldn't need any Session Scoped Session Beans.
Now this all makes sense to me, and is what I am probably going to do. However the reason for my question is that on my JSF xhtml pages I use JSF EL tags a lot to refer to EJB content. Are there any JPA-related pitfalls I need to watch out for when writing presentation tier classes?
I know my question is pretty vague, and not really related to a specific example. And although I've found quite a lot out about Stateful v Stateless beans on this and other sites I just want to know my intended structure is the best one.
Why don't you use backing beans for presentation purpose, as they are intended for it, and you can easyly configure its scope, and leave the EJBs to business tier?
When using entities directly on the presentation tier, you should be aware of the transaction scope, specially regarding lazy relationships. That is, normally it is used one transaction per request, what will mean that amongst different requests, the entities will become detached, so you will need to reatach them to be able to load lazy relationships. You could use a filter that does it automatically each request or handle it by hand. You could also keep the same transaction during different requests but a long transaction is normally not a good idea, specially if there are updates/creations in the DB during this transacion.

What technologies are best for my application: Struts with Hibernate or Spring with Hibernate

I have a working knowledge of Struts2 and Spring. I want to develop an application that manages information for multiple companies. I am totally confused about what technologies are best for my application. For instance: Struts2, and Hibernate MVC with Spring.
Can somebody help me select appropriate technologies?
Here is a quick breakdown of a J2EE stack you can use:
Use Struts2 for your controller layer
Use Hibernate for your data abstraction layer. Create service interfaces for your DAO. The interfaces will allow you to use some type of RMI for services later if desired, meaning those services can run on different machines than your web app. Have concrete classes implement those interfaces. The classes will contain business logic and validation of data, and will wrap the Hibernate session. The Hibernate session is used to read/write to/from the database. Use Hibernate annotations to expedite the implementation of Hibernate beans.
Use Spring for instantiating your service classes and Struts2 actions. Configure Spring to inject service instances into your Struts2 actions. This is called dependency injection. Reference interfaces, not classes in your Struts2 action's setter methods for the DI.
Use the Struts2 tag library or JSTL in your JSP, which will be your view layer.
Use Maven for your builds and deploys.
Run Apache with mod_jk, and use Tomcat as your servlet container. mod_jk runs w/ the Apache process, and passes requests to the Tomcat servlet container, which lives in the JVM.
If your application requires search capabilities, use SOLR, a REST service built on top of Lucene.
Instead of using Struts2, you could also take a look at Apache Wicket.
I had the same question few days back and following are the links I used to make a decision - I settled for Spring MVC. Also check out Spring ROO if you are starting afresh.
Choosing the right web framework
Comparing web frameworks
What Web Application Framework?
Ultimately choice will be based on your needs - but above links discuss what parameters you should consider before choosing one.
Hope that helps.
Agree with #Simian, and add some comments and reasons.
From a technological perspective, you should use any framework that utilize modern and mature technologies, such as Struts 2, Spring MVC, Hibernate, JSF, and etc.
However, from a business perspective, you should take more emphasis on the business model that your project consist of, and the demand for the framework is easy and rapid to implement, as well as robust and easy to maintain.
Therefore, as you are familiar with Struts 2, and Spring, I recommend:
1, Use Struts 2 as the MVC framework of your project, but use AJAX if required. You can also develop your interceptors to fulfill some common requirements of your project.
(Or, if you have time, you can learn Spring MVC as it works well with Spring framework, and has better support of AJAX and RESTful. JSF is not recommended, not because it isn't a superb framework, but it use a set of complete different concepts comparing to Struts 2 and Spring MVC, and it is difficult for an unskilled person to debug )
2, Just use Spring jdbcTemplate as your data layer, use DAO pattern to decouple.
(Or , you can learn Hibernate or JPA as your ORM framework, if you have time.)
3, Use Spring IoC to manage your objects and integration with Struts 2 and Hibernate, and manage transactions with Spring's annotations.

Resources