MVC pattern not specific to JDBC, in regards to three tier architecture - java

In regards to the MVC-pattern and the three-layer architecture, I'm a bit confused.
I know the difference between the two, but let's take an example of a java web project. Where we have a JSP-component, Servlet, Java Bean and a connection to a Database.
Is my understanding correct, that in the MVC-pattern, the JSP-page is the view that is presented to the user, the controller is the servlet that handles the request sent to the view, and the model is the objects (for example a java bean), that is sent through the controller to display dynamic content on the JSP-page.
Where is the three-tier architecture both the JSP, and Servlet component is the presentation layer, since that is what is being processed and displayed to the user, whereas the logic-tier is the java beans, where the methods of calculations are being processed, and the data tier, is the database along with the components of the JDBC?

Three tier is simple, you have a client, a server, and a database.
In the web world its a browser, a server(An example being a java application), and some sort of data store(Like a MySql server).
MVC is a design pattern used within an application that takes data and creates a presentation of that data. You can actually have it within every layer of a three tier architecture but it is most common within the server tier. In a single page application you may have a MVC in the client code, although, most client side frameworks take different approaches when compared to classic MVC.

Related

MVC - Spring Boot and Angular - What is the View in Spring?

I created a web application using Spring Boot for Backend and Angular 8 for Frontend with the help of the JHipster framework. The frontend communicates with the backend using a REST API.
I know that both Spring and Angular use of the MVC model. As such, in the case of Spring :
the database, JPA classes, and repositories are the Model
the REST Controllers are the Controller
My question is: what is the View part in the Spring application? My guess is that the entire Angular application takes the role of the view. Is that correct?
The view part in Spring was popular due to the Spring MVC concept where the view comprised of JSP (Dynamic) and HTML (Static) pages.
As you rightly said Spring and Angular both are MVC based frameworks, but now the current trend is moving towards Microservices architecture instead of Monololithic architecture.
Microservices architecture is language independent for its operation and communicates using REST services.
Currently, the focus is on separation of concerns and how quickly the code can be delivered.
1. Angular framework handles the UI part
2. Spring framework handles the backend operations (Business logics, interactions with the database and other servers.
In spring framework the MVC means
Model - The class that carries data
View -The view page (JSP/HTML)
Controller - The class that manages the operation
As you said on the post The database, JPA classes, and repositories are the Model these are nothing but the repository pattern which is integrated with the MVC pattern to communicate with the database.
To start Angular does not use MVC, Angular uses MVVM (model-view-view-model) or MVW (model-view-whatever)
Secondly your backend uses the n-layer pattern
Service Layer: Implement business logic
Data Access Objects: These are abstractions that your service layer will call to get / update the data it needs. This layer will generally either call a Database or some other system (eg: LDAP server, web service, or NoSql-type DB)
Controller Layer: Which will receive client requests.
In other words, you have a client-server architecture, with an n-layer pattern, where the angular (view layer) uses the MVVM pattern.
Observation:
Your Model you use may or may not come from your services. You may want to take the results your service gives you and manipulate them into a Model that's more specific to your medium (eg: a web page).
differentiate between database models (dao - data access object) and transfer model (dto - data transfer object)

Webflow vs. Angular or Both?

We are developing an Enterprise application with the following technology stack:
Websphere Application Server
Spring (Webflow (Session in View pattern), JPA (Hibernate), Core)
DB2 osZ
Frontend (JSP Rendering HTML5 (CSS 2.0), Ajax in combination with webflow, JQuery)
Multiple Single Pages design combined by using webflow for supporting
subflows
Development Methodology
- Domain Driven/Component Driven Application
- Test Driven Development
Current Situation
Our domain model has very deep domain class hierarchy and therefore we decided to use webflow to allow deep class navigation in sub flows.
We are using the “session in view pattern” because there are many screens reflecting the class hierarchy of the domain model.
This worked very well because of having the backend managing session scoped data for the frontend.
What do we want to do next?
Single Page Design
Control User data in session
Control User data across screens
Support multiple instance of a browser in one user session
Want to be able to talk to the backend (Enterprise Java/Spring) to
retrieve data and persist
Support more state-of-art user experience
Technology Stack
Websphere Application Server
Spring (Webflow (Session in View pattern), JPA (Hibernate), Core)
DB2 osZ
Frontend (Angular, JQuery, Bootstrap 3)
So the discussion internally is how to integrate Angular?
Should we give up Webflow and solve everything with Angular?
Does a mix make sense?
We have taken the following chart as a reference:
http://vschart.com/compare/angularjs/vs/spring-framework
We know what both frameworks are able to do, and know how to make them work. We are interested in other teams experience on how to integrate Angular? Did someone ever mix Webflow and Angular?
We are interested to see some best practices and how teams have transitioned to either framework or keeping both?
Thanks for input,
Andrew
I suggest you to check the Java library thymeleaf in order to get directly the benefits of HTML5 which you can easily add AngularJS and build on top of it (with bootstrap if you need it), and use Spring Security for Auth & session management.
As loose coupling at all levels (front-end included) is most of the times desirable, try to avoid technology mixing (WebFlow & AngularJS in this case) where doesn't makes sense.
Last thing, you and your team can discuss the possibility to develop an Angular based single page application which consumes a server side API coded in Java.
It is too late but might be useful for someone looking for this sort of answer.
I would recommend
Angularjs SPA(single page application) and use html template instead jsp.
Implement Token based authentication rather session based and implement restful spring web mvc api.
web flow/navigation can be controlled using the Angular services or browser's localstorage. I would recommend Angular services to manage app state instead browser localstorage.
And obviously bootstrap 3 to make the UI pretty.
Example implementation: jhipster

Data persistence in Java Server Faces with Hibernate/JPA

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.

Java Hibernate and servlets with Adobe Flex + Model View Controller Pattern?

I am preparing a document for a project. The project's backend is developed in Java, frontend is adobe flex.
I am not sure about the correct way of describe the project in Model-View-Controller way.
For Model layer: Using Hibernate Java beans to implement all the business logic and persistence?
For View Layer: Using Adobe flex send post or get request to Controller layer, and get respond in XML format.
For Controller Layer: Using Java servlet to handle requests from Flex client?
Thanks
Hibernate - Model
Flex - View
Servlets - Controller
Brief lift of complete nice article follows:
Model, is the data. Manipulates the internal state and fire events when the internal state changed.
View, the visual representation for the Model’s data (controls on the screen)
Controller, is responsible for interpreting the user actions on the view and make changes to the model. (usually an event handler in flex)
In reality there is no 100% demarcation between these three layers. Is not that easy to make them completely decoupled and usually we end up making some tradeoffs.
The controller will always know about the view and the view about the controller. Controller also knows about the model. In the end I could say that the model is the only piece of the MVC that can be “100% decoupled”.
You should check out the Adobe sponsored Cairngorm Framework for your Flex application. It's arguably the entire MVC design pattern in itself. Hibernate, Servlets, and your Java Beans are your application tier. There are other Flex MVC frameworks as well. Check out this other stackoverflow article for alternatives: Flex MVC Frameworks
The basic concept of Cairngorm is this:
Model: A singleton ModelLocator which stores the data that the Model needs to read from.
View: Your MXML/AS files that render the Model above.
Controller: The singleton FrontController that registers business events to a Command. The Commands represent a specific business logic task with associated logic/processing. This is usually where your API calls go to the Application tier to execute logic, fetch data, etc. When the Command is done, the Model is updated and your view will reflect those changes in the Model.
I could go in grave detail, but all of this information is described very well in the Cairngorm article linked above.

Describe the architecture you use for Java web applications? [closed]

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

Categories