Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Let's share Java based web application architectures!
There are lots of different architectures for web applications which are to be implemented using Java. The answers to this question may serve as a library of various web application designs with their pros and cons. While I realize that the answers will be subjective, let's try to be as objective as we can and motivate the pros and cons we list.
Use the detail level you prefer for describing your architecture. For your answer to be of any value you'll at least have to describe the major technologies and ideas used in the architecture you describe. And last but not least, when should we use your architecture?
I'll start...
Overview of the architecture
We use a 3-tier architecture based on open standards from Sun like Java EE, Java Persistence API, Servlet and Java Server Pages.
Persistence
Business
Presentation
The possible communication flows between the layers are represented by:
Persistence <-> Business <-> Presentation
Which for example means that the presentation layer never calls or performs persistence operations, it always does it through the business layer. This architecture is meant to fulfill the demands of a high availability web application.
Persistence
Performs create, read, update and delete (CRUD) persistence operations. In our case we are using (Java Persistence API) JPA and we currently use Hibernate as our persistence provider and use its EntityManager.
This layer is divided into multiple classes, where each class deals with a certain type of entities (i.e. entities related to a shopping cart might get handled by a single persistence class) and is used by one and only one manager.
In addition this layer also stores JPA entities which are things like Account, ShoppingCart etc.
Business
All logic which is tied to the web application functionality is located in this layer. This functionality could be initiating a money transfer for a customer who wants to pay for a product on-line using her/his credit card. It could just as well be creating a new user, deleting a user or calculating the outcome of a battle in a web based game.
This layer is divided into multiple classes and each of these classes is annotated with #Stateless to become a Stateless Session Bean (SLSB). Each SLSB is called a manager and for instance a manager could be a class annotated as mentioned called AccountManager.
When AccountManager needs to perform CRUD operations it makes the appropriate calls to an instance of AccountManagerPersistence, which is a class in the persistence layer. A rough sketch of two methods in AccountManager could be:
...
public void makeExpiredAccountsInactive() {
AccountManagerPersistence amp = new AccountManagerPersistence(...)
// Calls persistence layer
List<Account> expiredAccounts = amp.getAllExpiredAccounts();
for(Account account : expiredAccounts) {
this.makeAccountInactive(account)
}
}
public void makeAccountInactive(Account account) {
AccountManagerPersistence amp = new AccountManagerPersistence(...)
account.deactivate();
amp.storeUpdatedAccount(account); // Calls persistence layer
}
We use container manager transactions so we don't have to do transaction demarcation our self's. What basically happens under the hood is we initiate a transaction when entering the SLSB method and commit it (or rollback it) immediately before exiting the method. It's an example of convention over configuration, but we haven't had a need for anything but the default, Required, yet.
Here is how The Java EE 5 Tutorial from Sun explains the Required transaction attribute for Enterprise JavaBeans (EJB's):
If the client is running within a
transaction and invokes the enterprise
bean’s method, the method executes
within the client’s transaction. If
the client is not associated with a
transaction, the container starts a
new transaction before running the
method.
The Required attribute is the implicit
transaction attribute for all
enterprise bean methods running with
container-managed transaction
demarcation. You typically do not set
the Required attribute unless you need
to override another transaction
attribute. Because transaction
attributes are declarative, you can
easily change them later.
Presentation
Our presentation layer is in charge of... presentation! It's responsible for the user interface and shows information to the user by building HTML pages and receiving user input through GET and POST requests. We are currently using the old Servlet's + Java Server Pages (JSP) combination.
The layer calls methods in managers of the business layer to perform operations requested by the user and to receive information to show in the web page. Sometimes the information received from the business layer are less complex types as String's and integers, and at other times JPA entities.
Pros and cons with the architecture
Pros
Having everything related to a specific way of doing persistence in this layer only means we can swap from using JPA into something else, without having to re-write anything in the business layer.
It's easy for us to swap our presentation layer into something else, and it's likely that we will if we find something better.
Letting the EJB container manage transaction boundaries is nice.
Using Servlet's + JPA is easy (to begin with) and the technologies are widely used and implemented in lots of servers.
Using Java EE is supposed to make it easier for us to create a high availability system with load balancing and fail over. Both of which we feel that we must have.
Cons
Using JPA you may store often used queries as named queries by using the #NamedQuery annotation on the JPA entity class. If you have as much as possible related to persistence in the persistence classes, as in our architecture, this will spread out the locations where you may find queries to include the JPA entities as well. It will be harder to overview persistence operations and thus harder to maintain.
We have JPA entities as part of our persistence layer. But Account and ShoppingCart, aren't they really business objects? It is done this way as you have to touch these classes and turn them into entities which JPA knows how to handle.
The JPA entities, which are also our business objects, are created like Data Transfer Objects (DTO's), also known as Value Objects (VO's). This results in an anemic domain model as the business objects have no logic of their own except accessor methods. All logic is done by our managers in the business layer, which results in a more procedural programming style. It's not good object oriented design, but maybe that's not a problem? (After all object orientation isn't the only programming paradigm which has delivered results.)
Using EJB and Java EE introduces a bit of complexity. And we can't use purely Tomcat (adding an EJB micro-container isn't purely Tomcat).
There are lots of issues with using Servlet's + JPA. Use Google for more information about these issues.
As the transactions are closed when exiting the business layer we can't load any information from JPA entities which is configured to be loaded from the database when it's needed (using fetch=FetchType.LAZY) from inside the presentation layer. It will trigger an exception. Before returning an entity containing these kinds of fields we have to be sure to call the relevant getter's. Another option is to use Java Persistence Query Language (JPQL) and do a FETCH JOIN. However both of these options are a little bit cumbersome.
Ok I'll do a (shorter) one:
Frontend : Tapestry (3 for older projects, 5 for newer projects)
Business layer: Spring
DAO's : Ibatis
Database : Oracle
We use Sping transaction support, and start transactions upon entering the service layer, propagating down to the DAO call's. The Service layer has the most bussines model knowledge, and the DAO's do relatively simple CRUD work.
Some more complicated query stuff is handled by more complicated queries in the backend for performance reasons.
Advantages of using Spring in our case is that we can have country/language dependant instances, which are behind a Spring Proxy class. Based on the user in the session, the correct country/language implementation is used when doing a call.
Transaction management is nearly transparent, rollback on runtime exceptions. We use unchecked exceptions as much as possible. We used to do checked exceptions, but with the introduction of Spring I see the benefits of unchecked exceptions, only handling exceptions when you can. It avoids a lot of boilerplate "catch/rethrow" or "throws" stuff.
Sorry it's shorter than your post, hope you find this interesting...
Ideal Java Based Web Development Technologies Today.
Web Layer :
HTML+CSS+Ajax+JQuery
RESTFul Web Controller/Action/Request Processing Layer :
Play Framework
Business Logic/Service Layer:
Use Pure Java Code as long as possible. One can do fusion of web services here.
XML/JSon Data Transformation Layer :
XMLTool(Search On Google Code),JSoup,Google GSon,XStream,JOOX (Search On Google Code)
Persistence Layer :
CRUD : JPA or SienaProject or QueryDSL /
Complex Queries : JOOQ,QueryDSL
Here's my 5 cents
Presentation
Android, Angular.JS WebClient, OAUTHv2
API
REST, Jersey (JAX-RS), Jackson (JSON de-/serialisation), DTO-objects (different from business logic models)
Business Logic
Spring for DI and Event handling. DDD-ish approach of model objects. Longer running jobs are offloaded with SQS in worker-modules.
DAO
Repository model with Spring JDBC-templates to store Entities.
Redis (JEDIS) for Leaderboards, using Ordered Lists.
Memcache for Token Store.
Database
MySQL, Memcached, Redis
What we have followed in our project is :
Front end Technology
AngularJS
HTML5
css3
Javascript
Bootstrap 3
API
REST
JERSEY (JAX-RS)
REST ASSURED
SPRING BOOT
Jackson
spring security
Business Logic
SPRING DATA
SPRING data MongoDB
Data base
MongoDB
Server (For caching)
redis
We are still using the usual Struts-Spring-Hibernate stack.
For future apps, we are looking into Spring Web Flow + Spring MVC + Hibernate or
Spring + Hibernate + Web Services with Flex front end.
A distinct characteristic of our architecture is modularization. We have a number of modules, some starting with 3 to max 30 tables in the database. Most of modules consist of business and web project. Business project holds business and persistence logic while web holds presentation logic.
On logical level, there are three layers: Business, Persistence and Presentation.
Dependencies:
Presentation depends on Business and Persistence.
Persistence depends on Business.
Business does not depend on other layers.
Most of business projects have three types of interfaces (note: not GUI, it is a programatic java interface layer).
Interface that presentation is using as a client
Interface that other modules are using when they are the client of the module.
Interface that can be used for administrative purposes of the module.
Often, 1 extends 2.
This way, it is easy to replace one implementation of module with another. This helps us adopt to different clients and integrate more easily. Some clients will buy only certain modules and we need to integrate functionality they already have. Since interface and implementation layer are separated, it is easy to roll out ad-hock module implementation for that specific client without affecting dependant modules. And Spring Framework makes it easy to inject different implementation.
Our business layer is based on POJOs. One tendency I am observing is that these POJOs resemble DTOs. We suffer from anaemic domain model. I am not quite sure why is this happening but it can be due to simplicity of problem domain of many of our modules, most of the work is CRUD or due to developers preferring to place logic somewhere else.
Here is one more web architecture I have worked on:
One major requirement was the application should support mobiles/other
devices. The application should also be extensible or flexible to
changes in technology choices.
Presentation Tier:
JSP/JQuery (Client-side MVC)
Native Android
Native iPhone
Mobile web (HTML5/CSS3/Responsive design)
Spring REST Controllers (Can change to JAX-RS)
Business Service Tier:
Spring #Service (Can change to Stateless EJB)
Data Access Tier:
Spring #Repository (Can change to Stateless EJB)
Resource Tier:
Hibernate(JPA) entities (Can change to any ORM)
You can find more information on the book which follows this architecture here.
IMHO, most of us have a common denominator. Atleast in the back-end, we have some form of IOC/DI container and a persistence framework. Personally I use Guice and Mybatis for this. The differences are in how we implement the view/UI/presentation layer. There are 2 major options here (may be more) .. Action based (URLs mapped to controllers) and component based. Currently am using component based presentation layer (using wicket). It perfectly mimics a desktop environment where I use components and events as opposed to URLs and controllers. Am currently looking for a reason why I should migrate to this URL-controller kind of architecture (that's how I ended up on this page). Why the hype about RESTful and Stateless architectures.
To answer this question in short: I write stateful web applications using a component oriented framework on top of Guice IOC container and put data in relational database using Mybatis.
A bit different, and I would claim more modular java architecture here. We have:
Spring WS/Rest/JSP front end
Spring MVC for business service logic, containing presentation layer logic as well as Spring transactions
Component service communication interface, looked up through EJB by business services. EJBs set their own transaction boundaries that are able to join Spring transactions.
Component service implementations, again Spring components
Integration layer, MyBatis for database integrations, Spring WS for web service integrations, other integration techonologies for other services
Mainframes, databases, other services at other servers...
In addition to the above, we have the shared library modules which is common functionality provider for all srevices.
Use of different layers allows us full decoupling and the modularity we need. We are also able to fully utilize the power of Java EE as well as Spring. Nothing prevents us from using JSF, for example, for the front end if needed.
Compared to example architecture by OP, I think this can be described as having four main layers instead of three, albeit with a twist.
I've worked on projects that use that rigid manager pattern. Historically, I was a huge proponent of the rigid hierarchy where everything fit into a neat box. As I progress in my career I find it to be forced in a lot of cases. I believe that adopting a more agile mindset towards application design leads to a better product. What I mean by this creating a set of classes that solve the problem at hand. Rather than saying "Did you build a manager for this and that?"
The current project I'm working on is a web app with a combination of Spring MVC and RestEasy JSON/Ajax calls. On the server side embedded in our controllers is a sensible facade based data tier with JPA/Hibernate for direct Database access, some EJB access, and some SOAP based web service calls. Tying all this together is some custom java controller code that determines what to serialize as JSON and return to the client.
We spend almost no time attempting to create some unified pattern instead opting to adopt the "Worse is Better" idea of the Unix Design Philosophy. Being that its much better to color outside the lines and build something sensible, quickly than it is to build something that adheres to a bunch of strict design mandates.
The components in Web Application Architecture include :
1 : Browser : Client interaction
HTML
JavaScript
Stylesheet
2 : Internet
3 : Webserver
CSS
Image
Pages(Java render )
4 : Application Server
App Webapp (Java interaction)
Others WebApps
5 : Database Server
Oracle, SQL, MySQL
6 : Data
Related
Spring empowers POJO based programming.
It offers support for MVC out of the box
wires up code in less time.
How does it support layered architecture?
provides an abstraction layer to simplify development process(why is this a benefit and how does spring handle this?)
How does spring do that?
I read a lot of articles talking about the advantages of spring. But none of them explain in theory i.e. in words not code, how spring does that?
for example, one of the advantages says it empowers POJO programming? we can do that with plain java too, why is that a benefit or what's the opposite of POJO?
Kindly request everyone to address those 3 questions. THanks
in short:
spring was created a long time ago. it was probably compared to ejb2 that needed more setup code. POJO vs EJB vs EJB 3 Also spring does support pojos for example as return value in MVC-controllers. pojos dont have external dependencies so your application stays portable (non-functional requirement of an application).
yes you can easily (my opinion) create web applications.
at its core spring provides a container in which bean definitions are stored. when a service is requested that needs a dependecy, spring can look up whether it has a bean definition for that dependency, construct an instance of that bean and inject it in that service. That way you dont need to manually instantiate your service.
for example in web applications spring has abstractions for controllers, services and repositories. typically an application provides controllers so that caller can use your api. controllers should call services that handle your business logic. and services can call repositories that persist your data. that way you have a layered flow:
controllers --> services --> repository
this has the advantage that when you change e.g. your repository you dont have to make changes to your controllers.
spring provides many abstractions for common problems out-of-the-box (e.g. spring security) and empowers convention-over-configuration. That way you can reduce boilerplate code. less code -> less probability for a developer to make a mistake.
e.g. spring-security-oauth2: you can just set some properties in a .properties file and spring autoconfigures beans that solve the validation of an oauth-token when a user requests one of your controllers.
We are trying to split a big monolithic J2EE application into a set of modules to provide unified business logic for all web application clients.
Our goal is to have smaller and more specialized business modules that can be used in any combination by many distinct web applications. This way we expect the applications get easier to maintain individually (compared to the now heavily coupled monolithic one).
We are planning to arrange it like the following diagram:
Where Web Apps call module services on the upper layer to handle business logic through method calls (RMI was the intended protocol but we are open to other options).
J2EE makes it easy to arrange services on three tiers like this through EJB remote beans.
But we are also trying to setup these modules as spring boot applications (using the Spring Boot JPA Starter) because it makes development much more convenient.
My initial plan was to implement the modules with Spring Boot and expose a thin layer of EJB beans as proxies to spring beans with the actual implementation of the service. EJB beans would have spring beans injected using the SpringBeanAutowiringInterceptor class as in spring v4 documentation.
But since this kind of integration was removed from spring v5 I don't know how to proceed.
They are also considering "EJB as an effectively deprecated technology now" as stated in the issue above. But for my use case I can't find a good enough alternative.
So far I have thought of the following options:
Using a custom interceptor as the issue suggests. But it looks like reinventing a discarded old wheel (if that analogy makes any sense).
Spring remoting is an alternative but it's challenging to make it work with Wildfly JNDI for RMI configuration and trying to looks like re-implementing EJB remoting.
Spring Integration I think will add too much complexity and overhead for this simple task.
Message based integration (JMS, MQTT, etc...) may not fit well because of the synchronous nature of what we are trying to achieve.
REST API calls would add a lot of boilerplate code (for serialization and deserialization of objects into JSON, endpoints configuration and so on) and also add some ovehead because the HTTP handling.
Our goals, in this order of priority, are:
Make this integration as solid and fail-proof as possible.
Make calls to business logic from the web layer to the service layer as simple as possible.
Have as little overhead as possible.
With all that said which of those five options mentioned (or maybe another one I haven't considered) would be the best way and why?
I am planning to build a web application with Java Server Faces but i am unsure how to handle the persistence of my entities. For php projects i am using the Symfony framework with Doctrine 2. I call the persist method of the entity manager mainly in the controllers. So there are no seperate classes for business logic. I tried Hibernate and i think that is a good replace for Doctrine. ;)
The java project is for university and i want to transfer the business logic from the controllers/beans to classes for business logic.
I read articles and tutorials about the data access object and repository pattern (http://docs.spring.io/spring-data/jpa/docs/1.3.0.RELEASE/reference/html/jpa.repositories.html).
In the data access object pattern i have a class for my Entity and an interface and a class for my DAO object/entity, in the repository pattern i have a class for my entity and a class for the repisitory.
But where goes my business logic? Do I have to write an interface and a class per entity for the business logic layer and inside the classes i simply call my dao/repository methods? If so, what is the difference between both patterns?
If I am totally wrong: What is the (industry) standard for data persistence (with Hibernate/JPA) with Java Server Faces?
The architecture of the project must be well organized according to principle "low coupling and high cohesion"
The system layers should be well seperated. The basic architecture have 3 layers.
Presentation Tier: JSF managed beans are in this layer. The task of this layer is to correspond user actions, hold user data and show the data to the user. Basically, its responsibility is bounded by MVC pattern regardless of which implementation you use (JSF, Spring MVC or Struts)
Bussimess Logic Tier: The data and actions which was collected from page was sent to this layer to operate on data. You should not manipulte the data and prepare the response inside Presentation Tier. It is the responsibility of Bussiness Logic Tier.(Spring, CDI)
Integration Tier: Database access should be done in this layer regardless of the library technology used (Hibernate, JPA, JDBC).
As you can see in the pic. your JSF managed beans should only be capable of requests from the pages(controller) and page data (model). You can have a look to this answer to understand JSF MVC. Therefore, It is better to not to connect DB inside JSF managed beans. It is not a good practice.
The second part of your question. All technologies, Hibernate, JPA, Spring JDBC, uses JDBC driver of the related DB. JDBC Drivers is the just thing which connects to the DB. However, it is beter to select a method how to connect to DB, Hibernate, JPA or Spring JDBC.
You can download my example application which implements this architecture basically.
I have a design/architectural problem:
I've started developing a java web application. I thought of using 3 layers: a persistence layer (with jpa and hibernate), a business layer and a presentation layer. My problem now is:
the jpa entities would make the model but can or may I use the entities as business objects?
Is this a practice? My common sense says I shouldn't, but then, I need to duplicate these entities as business objects?
Finally, I'd like the presentation layer to be really decoupled from the other layers. While using spring mvc with jsp at first, I'd like. if it's suitable, at some moment to switch to javascript-based application that communicates with the backend through rest requests.
Yes, you can. Outside the persistence context, the JPA Entities are like simple POJOs. It is legal to use them in business code (actually, as hinted by JB Nizet, you usually ALWAYS use them in your business layer without DAO). If it is tightly related to the Entity, you can even add business logic into your JPA beans. Nevertheless, it will be harder to read and understand what the code does. But if you have a reason to do that - there is nothing illegal. It all comes down to software design practices and what you need most.
When you want to change your app into the REST-powered service, it is not difficult. You will have to change the Servlet you are currently running your app with for a JAX-RS or other framework Servlet which will handle HTTP requests in a REST manner for you. It is done in web.xml. Then, you will place your html-pages in any place, where it is accesible for the remote hosts, and connect them to your REST-service with the Javascript AJAX or sth. You should take care of CORS then.
I've participated in several projects of Spring-based web-application - and have written a quantity myself. Usually we have (roughly speaking) following folders to divide our classes by categories like dao, models, web (for controllers if we use Spring MVC or backing beans for JSF for example) and also service - here we keep what we think is business-logic (even when sometimes classes here simply forward methods to dao).
Now I am faced with development of EJB application - I've learnt that I will have some web and model classes anyway. Also I may use dedicated dao layer or may put data access into facades (I prefer dedicated folder though it increases verbosity).
But I do not understand clearly whether facades are exactly the place to put business-logic in it, or I should add services folder for it and use facades more like dao (eliminating dao itself).
I also would be glad for short and comprehensive compilation of hints on EJB application architecture.
I would go with a similar setup with EJB as you have done with Spring. You have your web package (MVC stuff), then your service layer which contains most business logic and then DAO layer which contains basic CRUD operations and some database queries.
In this scenario you can test the possibly complex business logic in the session beans with fast unit tests that don't need database and you can mock the DAO access here. Then you can have relatively simple tests for your DAO layer, so the number of tests requiring database (ie. that are consirably slower) is smaller.
Normally I would call facade a set of session beans that offer simple methods for operating the system via for example Web services. These beans would use the normal service layer beans. With just a web layer and no integration layers I don't see a reason to create an extra facade layer.