In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the example analysis of Spring MVC, which is very detailed and has certain reference value. Friends who are interested must finish it!
Overview
Sping MVC, officially known as Spring Web MVC, is one of the modules in the Spring Framework framework, which is based on Servlet API and uses the architecture pattern of MVC. It is mainly used to simplify the traditional Servlet + JSP for web development.
MVC architecture model
Spring MVC is based on the MVC schema, so understanding Spring MVC requires some understanding of the MVC schema.
Traditional MVC architecture model
MVC (Model-View-Controller) is a commonly used architecture model in software development, which divides the software system into three layers: Model, View and Controller. Each part is separated according to its responsibilities, which makes the structure of the program more intuitive and increases the expansibility, maintainability and reusability of the program. The following figure can be used to show the relationship between the three.
Model (Model): the model encapsulates the data and the operation of the data, and can access the database directly without relying on the view and controller, that is to say, the model does not care about how the data is displayed, but is only responsible for providing data. Changes in data in the GUI program model are generally notified to the view through the observer mode, which is not the case in web.
View: the view pulls data from the model and is only responsible for presentation. There is no specific program logic.
Controller (Controller): the controller is used to control the flow of the program, displaying the data in the model to the view.
Java Web MVC architecture model
In the 1990s, with the development of the Internet, the browser-based Bripple S mode became popular. at first, the browser requested some static resources from the server, such as HTML,CSS, etc. In order to support the dynamic acquisition of resources according to the user's request, Java put forward the Servlet specification.
At this time, Servlet can be said to be a hodgepodge, browsers receive HTML through the output of Servelt, which is more tedious, and programmers who write back-end code are also familiar with front-end technology. In order to solve this problem, sun Company also draws lessons from ASP to put forward JSP.
JSP is similar to HTML, except that Java code can be embedded in JSP files, reducing the amount of redundant code generated by using Servlet directly. At this time, JSP acts as the model, view and controller at the same time. In order to solve the problem that the front and back end code is still kneaded together, the Java Web MVC pattern is later proposed. JavaBean acts as the model, JSP acts as the view, and Servlet acts as the controller. The process is shown in the following figure.
Browser requests first control the whole process through Servlet,Servlet, query and store data using JavaBean, and then bring the data from JavaBean to the JSP page, which is the early Web MVC schema in Java.
Spring MVC architecture model
The Spring MVC architecture pattern extends the MVC architecture pattern in Java Web, splitting the controller into front-end controller DispatcherServlet and back-end controller Controller, dividing Model into business layer (Service) and data access layer (Respository), and supporting different views, such as JSP, FreeMarker, etc., the design is more flexible, and the request processing flow is as follows.
The request of the browser is first distributed through DispatcherServlet,DispatcherServlet, so DispatcherServlet is also called front-end controller. The Controller after DispatcherServlet is also called back-end controller. Controller can selectively call Service and Repository to implement business logic. After DispatcherServlet gets the model and view provided by Controller, it renders it and returns it to the browser. Of course, this is just to make it easier to understand the general process described by Spring MVC, which will be described later.
Hello,Spring MVC
Although SpringBoot has become mainstream now, I still want to start with pure Spring MVC, because SpringBoot only adds some automated configurations to Spring Framework, which will make us ignore the technical principles behind it.
Several years of Spring tutorials have suggested that to use Spring MVC, you first need to go to the Spring website to download a lot of dependencies, and now you no longer have to deal with these messy dependencies and their dependencies with maven. If you don't know maven, it is recommended to learn about maven before looking back at the following.
Spring MVC dependency introduction
Create a new maven project and introduce Spring MVC dependencies. Note that the version number introduced here is 5.2.6. Spring Framework 5 starts with a requirement of 1.8 or above for JDK version. The complete pom content is as follows.
4.0.0 com.zzuhkp mvc-demo 1.0-SNAPSHOT war UTF-8 1.8 1.8 org.springframework spring-webmvc 5.2.6.RELEASE javax.servlet javax.servlet-api 4.0.1 provided Mvc-demo DispatcherServlet statement
Traditional Java Web projects use Servlet to handle requests. Spring MVC follows the Servlet specification and provides a Servlet class named DispatcherServlet. To use Spring MVC, you need to declare this Servlet.
DispatcherServlet integrates the IOC container, where all components that process Web requests are stored in the IOC container, and then use these bean processes to control the entire request process.
There are two ways to declare DispatcherServlet. The first is to configure it directly in the / WEB-INF/web.xml file under the classpath.
Dispatcher org.springframework.web.servlet.DispatcherServlet 1 dispatcher /
The second method is based on the ServletContainerInitializer interface proposed by Servlet 3.0. the Servlet container will find the class that implements this interface from the classpath and call back the methods in this interface when starting. Spring MVC has implemented this interface as SpringServletContainerInitializer and called the WebApplicationInitializer API internally to complete initialization, so it is possible to implement the WebApplicationInitializer API and add DispatcherServlet. The java code equivalent to the above xml is as follows.
Public class MvcXmlInitializer implements WebApplicationInitializer {@ Override public void onStartup (ServletContext servletContext) throws ServletException {XmlWebApplicationContext context = new XmlWebApplicationContext (); DispatcherServlet dispatcher = new DispatcherServlet (context); Dynamic dynamic = servletContext.addServlet ("dispatcher", dispatcher); dynamic.addMapping ("/"); dynamic.setLoadOnStartup (1);}}
In addition to the above user-defined WebApplicationInitializer,Spring, an abstract implementation class AbstractAnnotationConfigDispatcherServletInitializer that supports annotated configuration is customized, which automatically registers DispatcherServlet with the Servlet context, implements the class, and then specifies the configuration class.
Public class MvcAnnotationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {@ Override protected Class [] getRootConfigClasses () {return null;} @ Override protected Class [] getServletConfigClasses () {return new Class [] {MvcConfig.class};} @ Override protected String [] getServletMappings () {return new String [] {"/"};}}
Here we demonstrate using the web.xml configuration, where the mapping path declared by our configured DispatcherServlet is /, so all requests will reach the DispatcherServlet and then be dispatched to different processors for processing.
Spring context configuration
Spring MVC uses the IOC container to store components that process requests, and all custom components related to Web requests, including processors, need to be added to the configuration of Spring.
Spring context profile specifies
The default container used for initialization of DispatcherServlet is XmlWebApplicationContext. Although Spring reserves extension points to modify the container type, it is not recommended to modify it unless necessary. By default, this container uses the / WEB-INF/ {servlet-name}-servlet.xml file under the classpath as the container configuration file. The DispatcherServlet we declare is dispatcher, so we create / WEB-INF/dispatcher-servlet.xml file as the container configuration. You can also use the initialization parameter configLocation of Servlet to specify the Spring container configuration file path.
Dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation / WEB-INF/dispatcher-servlet.xml 1 Spring context profile content
The contents of the Spring configuration file are as follows.
A bean of type HelloSpringMVCHttpRequestHandler is declared here, and its id is the request path / hellohandler, which is defined as follows.
Public class HelloSpringMVCHttpRequestHandler implements HttpRequestHandler {@ Override public void handleRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.getWriter () .write ("Hello,HelloSpringMVCHttpRequestHandler");}}
The purpose of this configuration is to be able to use the HelloSpringMVCHttpRequestHandler we provide to process the request when the / hellohandler request arrives.
At this point, publish the project to Tomcat. I use the Tomcat version number 9.0.54 here, and you can see the effect as follows.
HandlerMapping configuration
So why can the processor be used for processing by configuring the processor's bean id to the request path? Spring MVC uses HandlerMapping to map requests to processors for flexible lookup processors. By default, Spring uses BeanNameUrlHandlerMapping mapping requests, which use the request path as the id lookup processor. In addition to the mapper used by default, we can also configure the SimpleUrlHandlerMapping mapper, and the equivalent Spring configuration above is as follows.
Processor configuration
See here, careful friends may have questions, it is agreed that DispatcherServlet will dispatch the request to Controller? There is no hurry here. Controller is actually one of the processor types of Spring MVC, and HttpRequestHandler here is also the processor of Spring MVC.
Spring supports a variety of processors, specifically adapting processors using HandlerAdapter. Some adapters have been defaulted within Spring MVC, and HttpRequestHandler adapters are supported by HttpRequestHandlerAdapter,Controller 's adapter SimpleControllerHandlerAdapter and Spring MVC by default.
The default HandlerAdapter is sufficient to support daily needs, and HandlerAdapter is generally not customized.
Let's try to use Controller as the processor to handle the request. The HelloSpringMVCController class that implements the Controller interface is defined as follows.
Public class HelloSpringMVCController implements Controller {@ Override public ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws Exception {ModelAndView modelAndView = new ModelAndView (); modelAndView.setViewName ("/ WEB-INF/view/welcome.jsp"); modelAndView.addObject ("hello", "HelloSpringMVCController"); return modelAndView;}}
Then add this class as bean in the Spring configuration file.
At this point, you can finally see Controller, which processes the request and returns an object of type ModelAndView.
ModelAndView contains the model and views, where the property hello is added to the model, and the / WEB-INF/view/welcome.jsp file is specified as the view name, which is as follows.
Hello,$ {requestScope.hello}
Starting Tomcat access / hellocontroller has the following effect.
Successfully display the data in the model to the view.
ViewResolver configuration
In order to support different views, such as JSP, FreeMarker, etc., the view name in ModelAndView is designed to be virtual, and the specific view is parsed by the view parser ViewResolver. By default, the view parser is InternalResourceViewResolver, which parses the view based on URL. You can also configure your own view parser in the application context. Add a custom InternalResourceViewResolver to the Spring profile.
Then you can ignore the path prefix / WEB-INF/view and suffix .jsp when setting the view name, and HelloSpringMVCController in the above example can simplify the view name from / WEB-INF/view/welcome.jsp to welcome after configuring the prefix suffix.
Default configuration of DispatcherServlet components
Many components used by DispatcherServlet are used in the above example. Spring MVC already provides some by default. If you need customization, it is very convenient to add custom components to the context configuration, so which components does Spring use to handle requests by default?
These default configurations are defined in the org/springframework/web/servlet/DispatcherServlet.properties file under the spring-webmvc module classpath, as shown below.
Annotation-based Spring WebMVC
Profile-based Spring Web MVC projects were really popular a few years ago, but now annotations have become the mainstream of Spring development. The above example is modified by pure annotations below.
The pom file does not need to be changed, the first step is to provide the Spring configuration class.
@ ComponentScan ("com.zzuhkp.mvc") public class MvcConfig {}
Only the component scanning capability has been added here, and Spring will treat the classes labeled @ Component under a given package as bean. You can then set this class as the configuration class, which you can see here using the second declaration method of DispatcherServlet provided above.
An annotation-based controller is then provided.
@ Controllerpublic class HelloSpringMVCAnnotationController {@ GetMapping ("/ helloAnnotationController") public String helloMVC (@ RequestParam ("hello") String hello, Model model) {model.addAttribute ("hello", hello); return "/ WEB-INF/view/welcome.jsp";}}
The annotation-based controller does not need to implement a specific interface, but can simply add @ Controller annotation to the class. Here, a method is defined to handle the GET request in the / helloAnnotationController path, and the hello parameter is received, stored in model, and the view name is returned. The view in the above example is directly reused here. The final effect is as follows.
Annotation-based controller is the most flexible part of Spring MVC design. Here we can first consider how Spring adapts to user-defined controllers. How are the parameters in the controller method assigned? How do I resolve the return value of the controller method to a view? How does Spring support RESTFUL-style interfaces? A few articles will be written later to continue the analysis.
DispatcherServlet request processing flow
The DispatcherServlet request processing process has been interspersed with the previous example, and it may not be intuitive to look at the previous description directly. Here is a summary of a diagram to sort out the whole process.
The whole process is strung together as follows.
DispatcherServlet handles requests initiated by browsers.
DispatcherServlet uses HandlerMapping to find processors that can handle requests based on the user or default configuration.
DispatcherServlet gets the processor chain HandlerExecutionChain returned by HandlerMapping. The entire processor chain includes interceptors and processing.
DispatcherServlet adapts the processor to HandlerAdapter.
DispatcherServlet uses interceptors for request preprocessing.
DispatcherServlet uses a processor for request processing.
DispatcherServlet uses interceptors for request post-processing.
DispatcherServlet extracts the model and view ModelAndView from the interceptor or processor.
DispatcherServlet uses the view parser ViewResolver to parse the view out of the view View.
DispatcherServlet renders the view to respond to the request.
The above is all the content of this article "sample Analysis of Spring MVC". Thank you for reading! Hope to share the content to help you, more related 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: 218
*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.