In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how to achieve SpringMVC, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!
Web MVC introduces the request-response model in Web development:
In the Web world, the specific steps are as follows:
1. A Web browser (such as IE) initiates a request, such as accessing http://sishuok.com
2. The Web server (such as Tomcat) receives the request, processes the request (for example, if the user is added, the user will be saved), and finally produces a response (usually html).
3. After the web server processing is completed, the content is returned to the web client (usually our browser), and the client processes the received content (for example, the web browser will render the received html content to display to the customer).
So, in the Web world:
It is the Web client that initiates the request, and the Web server receives, processes, and responds.
Generally speaking, the Web server cannot actively notify the Web client to update the content. Although there are some technologies such as server push (such as Comet), and now HTML5 websocket can enable Web servers to actively notify Web clients.
Now that we understand the request / response model during web development, let's take a look at what the standard MVC model is.
Overview of Standard MVC Model
* * MVC model: * * is an architectural model, which does not introduce new features, but only helps us to organize the developed structure more reasonably, separating presentation from model, process control logic, business logic invocation and presentation logic. As shown in figure 1-2
Figure 1-2
First, let's take a look at the concept of MVC (Model-View-Controller) triples:
* * Model (model): * * the data model provides the data to be displayed, so it contains data and behavior, which can be thought of as domain model or JavaBean components (including data and behavior), but now they are generally separated: Value Object (data) and service layer (behavior). That is, the model provides the functions of model data query and model data status update, including data and business.
* * View (view): * * is responsible for displaying the model, which is generally the user interface we see and what the customer wants to see.
* * Controller (controller): * * receive the user's request and delegate it to the model for processing (state change). After processing, the returned model data is returned to the view, which is responsible for display. In other words, the controller works as a dispatcher.
We can also see from figure 1-1 that in standard MVC, the model can actively push data to the view for update (observer design pattern, register the view on the model, and update the view automatically when the model is updated), but in Web development, the model cannot actively push to the view (cannot actively update the user interface), because in Web development is a request-response model.
Then let's take a look at what MVC looks like in Web. We call it Web MVC to distinguish standard MVC.
Overview of Web MVC
The model-view-controller concept is the same as the standard MVC concept, refer to 1.2, and let's take a look at the Web MVC standard architecture, as shown in figure 1-3:
As shown in figure 1-3
In Web MVC mode, the model cannot actively push data to the view, and if the user wants to update the view, he needs to send another request (that is, the request-response model).
The concept is almost done, so let's take a look at the evolution of Web-side development, and use code to demonstrate how Web MVC is implemented, and why use the MVC pattern?
Development process of Web end
Here we simply describe the core process, as shown in figure 1-4.
Figure 1-4
1.4.1, CGI: (Common Gateway Interface) Common Gateway Interface, a scripting technology used on the web server, written in C or Perl language, used to receive and process web user requests, and finally dynamically generate a response to the user, but each request will generate a process, heavyweight.
1.4.2. Servlet: a JavaEE web component technology, which is a web component executed on the server side, which is used to receive and process web user requests, and finally dynamically generate a response to the user. But only one thread (and thread pool) is generated per request, which is lightweight. And can use many JavaEE technologies (such as JDBC, etc.). The essence is to output the html stream in the java code. But the calls of presentation logic, control logic and business logic are mixed. As shown in figure 1-5
Figure 1-5
As shown in figure 1-5, this approach is absolutely undesirable. Control logic, performance code, and business logic object calls are mixed together. The biggest problem is to output Html directly in the Java code, so that front-end developers can not design and modify the page style, even if the modification is very troublesome, so the actual project this approach is not desirable.
1.4.3, JSP: (Java Server Page): a web component executed on the server side, is a template page technology that runs a scripting language embedded in standard HTML pages (now only Java is supported). The essence is to embed java code in html code. JSP will eventually be compiled into Servlet, but it is simpler and more convenient than pure Servlet development pages. But presentation logic, control logic and business logic invocation are still mixed. As shown in figure 1-6
Figure 1-6
As shown in figure 1-6, this approach is absolutely undesirable. Control logic, presentation code, and business logic object calls are mixed together, but it is better than outputting html directly in servlet. Front-end developers can design and modify simple page styles (but it is also difficult to modify if too many embedded java scripts are embedded), so this approach is not desirable in actual projects.
JSP is still Servlet in nature, and will eventually generate a Servlet at run time (such as tomcat, which will be generated under the tomcat\ work\ Catalina\ web application name\ org\ apache\ jsp), but this makes it easier to write html, but it is still a mix of control logic, presentation code, and business logic object calls.
* * 1.4.4, Model1:** can be thought of as an enhanced version of JSP, can be thought of as jsp+javabean as shown in figures 1-7
Features: use jsp:useBean standard actions to automatically encapsulate request parameters as JavaBean components; you must also use java scripts to execute control logic.
Figure 1-7
Here we can see that using jsp:useBean standard actions can simplify the acquisition / creation of javabean and encapsulate the request parameters into javabean, and take a look at the Model1 architecture, as shown in figure 1-8.
Figure 1-8 Model1 architecture
In Model1 architecture, JSP is responsible for controlling logic, presentation logic, and business object (javabean) calls, but it is easier to obtain and encapsulate request parameters than pure JSP. It is also bad, and it should be forbidden to be used in projects (or at most in demo).
1.4.5, Model2: in the JavaEE world, it can be thought of as the Web MVC model
In fact, the Model2 architecture can be thought of as what we call the Web MVC model, but the controller uses Servlet, the model uses JavaBean, and the view uses JSP, as shown in figure 1-9.
Figure 1-9 Model2 architecture
Specific code examples are as follows:
As can be seen from the Model2 architecture, the view and model are separated, and the control logic and presentation logic are separated.
But we also see serious shortcomings:
1. 1. Controller:
1.1.1. The control logic may be complex. In fact, according to the specification, such as the request parameter submitFlag=toAdd, we can actually call the toAdd method directly to simplify the control logic. Moreover, each module basically needs a controller, so the control logic may be very complex.
1.1.2. It is troublesome to encapsulate the request parameters to the model. If we can give it to the framework to do this, we can be liberated from it.
1.1.3. Choose the next view and rely heavily on Servlet API, so it is difficult or almost impossible to change the view.
1.1.4, transfer the model data to the view to be displayed, use Servlet API, and change the view technology, which is very troublesome.
1.2. Model:
1.2.1. The use of JavaBean in the model here may result in a large class of JavaBean components. Generally, projects now use a three-tier architecture instead of JavaBean.
1.3, View
1.3.1, now bound to JSP, it is difficult to change views, such as Velocity, FreeMarker;, for example, I want to support Excel, PDF views, and so on.
1.4.5. Service to worker: Front Controller + Application Controller + Page Controller + Context
That is, front controller + application controller + page controller (also known as action) + context, also known as Web MVC, but the responsibility is more clear. For more information, please refer to "Core J2EE Design pattern" and "Enterprise Application Architecture pattern" as shown in figure 1-10:
Figure 1-10
The running process is as follows:
Responsibilities:
* * Front Controller:** front-end controller, which is responsible for providing a unified access point for the presentation layer, so as to avoid repetitive control logic in Model2 (the front-end controller calls back the corresponding functional methods uniformly, such as transferring the login method according to submitFlag=login) And it can provide common logic for multiple requests (such as preparing context, etc.), separating the selection of specific views from specific functional processing (such as encapsulating request parameters into the model in login and invoking business logic objects).
* * Application Controller:** application controller, after the front-end controller separates the selection of specific views and specific function processing, it needs someone to manage. The application controller is used to select specific view technology (view management) and specific function processing (page controller / command object / action management). The application of a strategy design pattern can easily switch views / page controllers without affecting each other.
* * Page Controller (Command): * * Page controller / action / processor: function processing code, collect and encapsulate parameters to the model, transfer the business object processing model, return the logical view name to the front-end controller (decoupled from the specific view technology), and delegate the front-end controller to the application controller to select a specific view to display, which can be the implementation of the command design pattern. A page controller is also known as a processor or action.
* * Context:** context, remember the model data prepared for display in Model2 for the view? we put it directly in request (related to Servlet API). Once we have the context, we can place the relevant data in the context, so that protocol-independent (such as Servlet API) access / setting model data is generally implemented through ThreadLocal mode.
At this point, we have reviewed the evolution of the entire web development architecture. Different web layer frameworks may have different details, but the purpose is the same:
Clean web presentation layer:
Separation of model and view
The control logic in the controller is separated from the functional processing (collecting and encapsulating parameters to model objects, business object calls)
The view selection in the controller is separated from the specific view technology.
Frivolous web presentation layer:
Do as little as possible, thin, and should not contain extraneous code
Only responsible for collecting and organizing parameters to model objects and initiating calls to business objects
The controller only returns the logical view name and the specific view strategy is selected by the corresponding application controller.
Use framework-specific API as little as possible to make it easy to test.
At this point, we understand the development of Web MVC, and then let's understand what Spring MVC is, its architecture and how to use HelloWorld.
For the specific code of this chapter, please refer to the springmvc-chapter1 project.
What is Spring Web MVC?
Spring Web MVC is a Java-based lightweight Web framework that implements the request-driven type of Web MVC design pattern. Even if the idea of MVC architecture pattern is used, the responsibility of the web layer is decoupled, based on request-driven refers to the use of request-response model, the purpose of the framework is to help us simplify development, Spring Web MVC is also to simplify our daily Web development.
In addition, there is a component-based, event-driven Web framework that will not be introduced here, such as Tapestry, JSF and so on.
Spring Web MVC is also an implementation of the service-to-worker model, but it can be optimized. The front-end controller is the DispatcherServlet; application controller, which is actually split into processor mapper (Handler Mapping) for processor management and view parser (View Resolver) for view management; page controller / action / processor is the implementation of Controller interface (including only ModelAndView handleRequest (request, response) methods) (can also be any POJO class); supports Locale parsing, Theme parsing and file upload, etc. Provides very flexible data validation, formatting, and data binding mechanisms; provides contractual programming support with powerful conventions over configuration (convention-first principle).
What can Spring Web MVC do for us?
√ allows us to easily design clean Web layers and thin Web layers.
√ to develop a more concise Web layer
√ is inherently integrated with Spring frameworks (such as IoC containers, AOP, etc.)
√ provides powerful contractual programming support that convention is larger than configuration.
√ can easily do the unit test of Web layer.
√ supports flexible URL-to-page controller mapping
√ is very easy to integrate with other view technologies, such as Velocity, FreeMarker, etc., because the model data is not placed in a specific API, but in a Model (Map data structures are implemented, so it is easy to be used by other frameworks)
√ 's very flexible data validation, formatting and data binding mechanism enables data binding with any object without having to implement API for a specific framework.
√ provides a powerful JSP tag library to simplify JSP development.
√ supports flexible localization, theme parsing, etc.
Simpler exception handling for √
√ support for static resources
√ supports Restful style.
Spring Web MVC architecture
The Spring Web MVC framework is also a request-driven Web framework, and it is also designed using the front-end controller pattern, and then distributed to the corresponding page controller (action / processor) for processing according to the request mapping rules. First, let's take a look at the overall flow of Spring Web MVC processing requests:
The process of processing requests by Spring Web MVC
As shown in figure 2-1
Figure 2-1
The specific implementation steps are as follows:
1. First, the user sends the request-> the front-end controller, which decides which page controller to process according to the request information (such as URL) and delegates the request to it, that is, the control logic part of the previous controller; steps 1 and 2 in figure 2-1
2. After receiving the request, the page controller performs functional processing. First, it needs to collect and bind the request parameters to an object, which is called a command object in Spring Web MVC and validated, and then delegates the command object to the business object for processing. After processing, it returns a ModelAndView (model data and logical view name); steps 3, 4 and 5 in figure 2-1
3. The front-end controller takes back control, then selects the corresponding view to render according to the returned logical view name, and passes in the model data for view rendering; steps 6 and 7 in figure 2-1
4. The front-end controller takes back control again and returns the response to the user, step 8 in figure 2-1; it's all over.
Question:
1. How to send the request to the front-end controller?
2. How does the front-end controller select the page controller to process the function according to the request information?
3. How to support multiple page controllers?
4. How does the page controller use business objects?
5. How does the page controller return model data?
6. How does the front-end controller choose a specific view to render according to the logical view name returned by the page controller?
7. How do different view technologies use the corresponding model data?
First of all, we know that there are problems like the above, so how to solve these problems? Please let us go on first and answer later in turn.
Spring Web MVC architecture
1. Spring Web MVC core architecture diagram, as shown in figure 2-2
Figure 2-2
The DispatcherServlet core code corresponding to the architecture diagram is as follows:
Java Code:
/ / Front-end controller dispatch method protected void doDispatch (HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex =-1; try {ModelAndView mv; boolean errorView = false Try {/ / check whether the request is multipart (such as file upload), if it is to parse processedRequest = checkMultipart (request) through MultipartResolver; / / step 2, map the request to the processor (page controller), and map mappedHandler = getHandler (processedRequest, false) through HandlerMapping. If (mappedHandler = = null | | mappedHandler.getHandler () = = null) {noHandlerFound (processedRequest, response); return } / / step 3, processor adaptation, that is, packaging our processors into corresponding adapters (thus supporting multiple types of processors) HandlerAdapter ha = getHandlerAdapter (mappedHandler.getHandler ()) / / Not Modified cache support / / specific code is omitted here / / processor-related interceptor preprocessing (HandlerInterceptor.preHandle) / / specific code is omitted here / / step 4, The adapter executes the processor (calling the corresponding function processing method of the processor) mv = ha.handle (processedRequest Response, mappedHandler.getHandler () / / Do we need view name translation? If (mv! = null & &! mv.hasView ()) {mv.setViewName (getDefaultViewName (request)) } / / perform post-processing of processor-related interceptors (HandlerInterceptor.postHandle) / / the specific code is omitted here} catch (ModelAndViewDefiningException ex) {logger.debug ("ModelAndViewDefiningException encountered", ex); mv = ex.getModelAndView () } catch (Exception ex) {Object handler = (mappedHandler! = null? MappedHandler.getHandler (): null); mv = processHandlerException (processedRequest, response, handler, ex); errorView = (mv! = null) } / / step 5, step 6, parse the view and render the view / / step 5 parse View (viewResolver.resolveViewName (viewName, locale)) / / step 6 the view will pass Model into the rendering (view.render (mv.getModelInternal (), request, response) ) if (mv! = null & &! mv.wasCleared ()) {render (mv, processedRequest, response); if (errorView) {WebUtils.clearErrorRequestAttributes (request) }} else {if (logger.isDebugEnabled ()) {logger.debug ("Null ModelAndView returned to DispatcherServlet with name'" + getServletName () + "': assuming HandlerAdapter completed request handling") }} / / perform processor-related interceptor post-completion processing (HandlerInterceptor.afterCompletion) / / omit the specific code catch (Exception ex) {/ / Trigger after-completion for thrown exception here. TriggerAfterCompletion (mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex;} catch (Error err) {ServletException ex = new NestedServletException ("Handler processing failed", err); / / Trigger after-completion for thrown exception. TriggerAfterCompletion (mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex;} finally {/ / Clean up any resources used by a multipart request. If (processedRequest! = request) {cleanupMultipart (processedRequest);}
The specific process steps of the core architecture are as follows:
1. First, the user sends the request-- > DispatcherServlet. After receiving the request, the front-end controller does not process it by itself, but entrusts it to other parsers to handle it as a unified access point for global process control.
2. DispatcherServlet-- > HandlerMapping, HandlerMapping will map the request to a HandlerExecutionChain object (including a Handler processor (page controller) object and multiple HandlerInterceptor interceptors). Through this policy mode, it is easy to add new mapping policies.
3. DispatcherServlet-- > HandlerAdapter,HandlerAdapter will package processors as adapters to support multiple types of processors, that is, the application of adapter design patterns, so that many types of processors can be easily supported.
4. HandlerAdapter-- > the call of the processor function processing method. HandlerAdapter will call the real processor function processing method according to the adaptation result, complete the function processing, and return a ModelAndView object (including model data, logical view name).
5. The logical view name of ModelAndView-- > ViewResolver. ViewResolver will parse the logical view name into a specific View. Through this policy mode, it is easy to change other view technologies.
6. View-- > render. View will render based on the incoming Model model data. The Model here is actually a Map data structure, so it is easy to support other view technologies.
7. Return the control to DispatcherServlet, and the DispatcherServlet returns the response to the user, until the end of the process.
We only talked about the core process here, without considering interceptors, local parsing, file upload parsing, etc., which will be described in more detail later.
At this point, let's take a look at the question we raised earlier:
1. How to send the request to the front-end controller? This should be described in web.xml and explained in detail in HelloWorld.
2. How does the front-end controller select the page controller to process the function according to the request information? We need to configure HandlerMapping for mapping
3. How to support multiple page controllers? Configure HandlerAdapter to support multiple types of page controllers
4. How does the page controller use business objects? As you can expect, it will definitely take advantage of the dependency injection feature of the Spring IoC container
5. How does the page controller return model data? Use ModelAndView to return
6. How does the front-end controller choose a specific view to render according to the logical view name returned by the page controller? Parsing with ViewResolver
7. How do different view technologies use the corresponding model data? Because Model is an Map data structure, it is easy to support other view technologies
Here we can see the specific core development steps:
1. The deployment description of DispatcherServlet in web.xml to intercept requests to Spring Web MVC
2. Configuration of HandlerMapping to map the request to the processor
3. Configuration of HandlerAdapter to support multiple types of processors
4. The configuration of ViewResolver to resolve the logical view name into concrete view technology.
5. the configuration of the processor (page controller) for functional processing
The above development steps will be verified in detail in Hello World.
Spring Web MVC advantage
1, a clear division of roles: front-end controller (DispatcherServlet), request-to-processor mapping (HandlerMapping), processor adapter (HandlerAdapter), view parser (ViewResolver), processor or page controller (Controller), validator (Validator), command object (Command request parameters bound to the object is called command object), form object (the object that Form Object provides to form display and submission is called form object).
2. The division of labor is clear, and the extension point is quite flexible, so it can be easily extended, although it is almost unnecessary.
3. Because the command object is a POJO, there is no need to inherit the framework-specific API, you can use the command object directly as a business object
4. Seamless integration with other Spring frameworks, which other Web frameworks do not have.
5. Adaptable, and any class can be supported as a processor through HandlerAdapter
6. Customizable, HandlerMapping, ViewResolver and so on can be easily customized.
7. Powerful data validation, formatting and binding mechanisms
8. Using the Mock object provided by Spring, the unit test of Web layer can be done very easily.
9. Localization and theme parsing support make it easier for us to internationalize and switch themes.
10. Powerful JSP tag library makes it easier to write JSP.
. There are also support for RESTful style, simple file upload, contract programming support for conventions greater than configuration, zero configuration support based on annotations, and so on.
DispatcherServlet action
DispatcherServlet is the implementation of the front-end controller design pattern, provides a centralized access point for Spring Web MVC, is responsible for the assignment of responsibilities, and integrates seamlessly with the Spring IoC container, thus reaping all the benefits of Spring. For details, please refer to figure 2-1 in Chapter 2.
DispatcherServlet is mainly used for responsibility scheduling, and itself is mainly used to control the process. The main responsibilities are as follows:
1. File upload resolution. If the request type is multipart, file upload resolution will be performed through MultipartResolver.
2. Map the request to the processor through HandlerMapping (return a HandlerExecutionChain, which includes a processor and multiple HandlerInterceptor interceptors)
3. Support multiple types of processors (processors in HandlerExecutionChain) through HandlerAdapter
4. Parse the logical view name to the concrete view through ViewResolver
5. Localization analysis
6. Render specific views, etc.
7. If an exception is encountered during execution, it will be handed over to HandlerExceptionResolver for resolution.
From the above, we can see that DispatcherServlet is mainly responsible for the control of the process (and it is easy to extend at every key point in the process).
The above is all the content of this article "how to achieve SpringMVC". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.