问题
As we define view,controller,service and Dao layer in application then how data flow in between them.
e.g. suppose we add struts,spring,hibernate,etc. jars in project then how they work together?回答1:
The MVC pattern itself does not describe how should you implement your web application. What it describes is how your components should interact with each other in order to achieve a modular architecture with replaceable components.
The pattern is explained in details in Martin Fowler's POEAA and in Wikipedia. More info about MVC can be found in Wikipedia
A simple example using Java, Spring and Hibernate
In this case Spring MVC provides a pluggable framework where you can define your models , controllers and views without coupling them together too tightly (this is achieved through IOC/DI).
The first thing to notice is the DispatcherServlet which is a regular servlet that serves as an entry point by handling all the incoming HTTP requests and routing them to their respective controllers. The appropriate controller is looked up by their mappings, eg. via @RequestMapping annotations.
The controller's responsibility is to determine what actions should be performed as a response to the incoming request. This is usually done by checking headers, parameters, session info, path for information what the user wanted to do. Here is an extremely simple example:
if (session.getAttribute("authenticated") == false) {
// we need to redirect to the login page
} else {
// everything was fine, so we do some business logic in the model
importantService.doSomethingReallyImportant(productOrder)
}
Then the control is passed to the model layer where business logic happens. This may include any operation that changes the model's state, like updating a password, registering a booking, clearing transactions, and so on. In web applications these operations often involve the use of a persistence API, eg. Hibernate.
public class ImportantService {
public void doSomethingVeryImportant(final ProductOrder order) {
// Here we define the business operation
getCurrentBasket().add(order);
// An additional pseudo-persistence operation
getSession().update(order);
}
}
In practice when the model has finished then control is returned to the controller which decides how to update the view (eg. redirecting the browser or just simply display a result page) where the user sees the result of his/her action.
来源:https://stackoverflow.com/questions/21159580/how-mvc-web-application-works-in-java