Note source: Crazy God says spring MVC
Station B video: here
I review
1.1 what is MVC
- MVC is an introduction to Model, View and Controller. It is a soft solution design specification
- It is a method to organize code by separating business logic, data and display.
- The main function of MVC is to reduce the two-way coupling between view and business logic.
- MVC is not a design pattern, but an architecture pattern. Of course, different MVCs are different
Model: the data model provides the data to be displayed, so it contains data and behavior. It can be considered as a domain model or javaBean component (including data and behavior), but now it is generally separated from the Value object (data DAO) and the Service layer (behavior Service). That is, the model provides functions such as model data query and model data status update.
View: it is responsible for displaying the model, which is generally the user interface we see and what customers want to see.
Controller: accept 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 displaying it, that is, the controller does the work of the dispatcher.
The most typical MVC is (JSP+Servlet+Javabean)
1.2 model1 Era
-
In the early development of web, model 1.0 is usually used
-
Model1 is mainly divided into two layers: view layer and model layer.
-
model1 advantages: simple architecture, more suitable for small project development.
-
model1 disadvantages: JSP responsibilities are not single, the responsibilities are too heavy, and it is not easy to maintain.
1.3 Model2 Era
model2 divides a project into three parts: view, control and model
- User sends request
- The Servlet accepts the requested data and calls the corresponding business logic method.
- After the business is processed, the updated data is returned to the Servlet
- servlet turns to JSP, which renders the page
- Respond to the updated page of the front end.
Responsibility analysis:
Controller: controller
- Get form data
- Call business logic
- Forward specified page
Model: Model
- Business logic
- Status of saved data
View: View
- Display page: Model2 not only improves the reuse rate of code and the scalability of the project, but also greatly reduces the maintenance cost of the project. The implementation of Model 1 mode is relatively simple and suitable for rapid development of small-scale projects. The JSP page in Model 1 plays both the roles of View and Controller, mixing the control logic and presentation logic, resulting in very low code reusability and increasing the scalability of the application and the difficulty of maintenance. Model 2 eliminates the disadvantages of Model 1.
1.4 review Servlet
- Create a Maven project: as the parent project, import the following dependencies.
<dependencies> <!--Here is the test--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--This is WebMVC Support of--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!--The following is the same for ten thousand years Servlet of--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
-
Establish a module: springmvc-01-servlet and add webapp support!
-
Import jar packages for servlets and JSPS
<dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency>
- Write a Servlet class to handle user requests
//Implement Servlet interface public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get parameters String method = req.getParameter("method"); if (method.equals("add")){ req.getSession().setAttribute("msg","Yes add method"); } if (method.equals("delete")){ req.getSession().setAttribute("msg","Yes delete method"); } //Business logic //View jump req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Call each other doGet(req,resp); } }
- Then write hello JSP file, create a JSP folder under the WEB-INF directory, and create hello jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Kuangshen</title> </head> <body> ${msg} </body> </html>
- On the web Registering servlets in XML
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>com.kuang.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/user</url-pattern> </servlet-mapping> </web-app>
-
Configure Tomcat and start the test
localhost:8080/user?method=add
localhost:8080/user?method=delete
What does the mvc framework do
- Map the URL to a java class or method of a java class.
- Encapsulate user submitted data
- Processing request - call related business processing - wind installation response data
- Render the response data jsp/html and other presentation layer data
explain:
Common server side Mvc The frame consists of: Struts,SpringMVC,ASP.NET MVC, Zend Framework,JSF,Common front end MVC The framework includes: Vue,angularjs,react,react,backbone. from mvc Other models evolved: MVP,MVVM Mode, etc.
II What is spring MVC
2.1 general
Spring MVC is a part of the Spring Framework. It is a lightweight web framework based on java to implement MVC.
View official documents: https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-frameworkreference/web.html#spring-web
Why should we learn spring MVC?
Features of spring MVC:
- Lightweight, easy to learn.
- Efficient, request response based MVC architecture.
- Good compatibility with Spring and seamless combination
- Contract greater than configuration
- Powerful, RestFul, data validation, formatting, localization, theme, etc.
- Simple and flexible.
Spring's web framework is designed around the dispatcher Servlet
The dispatcher servlet is used to distribute requests to different processors, from spring 2 Starting from 5, users using Java 5 or above can develop based on annotations, which is very brief.
Because Spring MVC is good, simple, convenient and easy to learn, it is naturally seamlessly integrated with Spring (using Spring IOC and Aop), and the use convention is better than configuration Can carry out simple junit test Support Restful style Exception handling, localization, internationalization, data validation, type conversion, interceptors and so on... So we need to learn
2.1 central controller
spring's web framework is designed around the dispatcher servlet, which is used to forward requests to different processors. From sprig2 5, users using Java 5 or above can adopt annotation based Controller declaration.
Like many other MVC architectures, the spring MVC framework is request driven and provides requests and other functions around a Servlet. The dispatcher Servlet is an actual Servlet (it inherits the HTTP Servlet base class).
The principle of spring MVC is shown in the following figure:
When a request is initiated, the front controller intercepts the request, generates a proxy request according to the request parameters, finds the actual controller corresponding to the request, processes the request, creates a data model, accesses the database, and responds to the model to the central controller. The controller renders the view results using the model and view, and returns the results to the central controller, The result is then returned to the requester.
2.3 spring MVC implementation principle
The figure shows a relatively complete flow chart of spring MVC. The solid line indicates the technology provided by the spring MVC framework, which does not need to be implemented by developers, and the dotted line indicates that it needs to be implemented by developers.
Briefly analyze the implementation process
-
Dispatcher servlet represents the front controller and is the control center of the whole spring MVC. When the user sends a request, the dispatcher servlet receives the request and intercepts the request.
We assume that the requested url is: http://localhost:8080/SpringMVC/hello
http://localhost:8080 Server domain nameSpring MVC is a web site deployed on the server
hello indicates the controller
Through analysis, the above url is expressed as: request the hello controller of the spring MVC site located on the server localhost:8080.
-
HandlerMapping is processor mapping. DispatcherServlet calls HandlerMapping, which looks up the Handler according to the request url (in fact, the Handler can be understood as a controller).
-
HandlerExecution refers to a specific Handler. Its main function is to find the controller according to the url. The controller found by the url above is: hello.
-
HandlerExecution passes the parsed information to DispatcherServlet, such as parsing controller mapping.
-
The HandlerAdapter represents a processor adapter that executes the Handler according to specific rules.
-
The Handler lets the specific Controller execute.
-
The Controller returns the specific execution information to the HandlerAdapter, such as ModelAndView.
-
The HandlerAdapter passes the view logical name or model to the dispatcher servlet.
-
DispatcherServlet calls the view resolver to resolve the logical view name passed by the HandlerAdapter.
-
The view parser passes the parsed logical view name to the dispatcher servlet.
-
DispatcherServlet calls a specific view according to the view result parsed by the view parser.
-
The final view is presented to the user.
My understanding of the above process: first of all, we sent it. Enter in 1) browser address bar: http://localhost:8080/helo , and then go through the processing from HandlerMapper to HandlerExecution: we get the name of our hello controller
above hello Request to come here <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> All requests will be intercepted through this, and then other judgments will be made
2) After getting the name of the Controller, we call the HandlerAdapter for adaptation (in fact, we find out whether we have configured the requested Controller at the back end). If there is a hello Controller, it will find the specific Controller and enter the Hello Controller.
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!--view resolver :DispatcherServlet Give it to him ModelAndView--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!--prefix--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--suffix--> <property name="suffix" value=".jsp"/> </bean> These are the necessary configurations: the following is the focus <bean id="/hello" class="cn.mldn.springmvc.controller.HelloController"/>
3) What will you do after you go in? There will be ModelAndView and the specific business calling the business layer in the hello Controller, and then return the logic and model of the view parser.
//Note: let's import the Controller interface first //Entering this is to obtain the view, the implementation of business logic, etc public class HelloController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { //ModelAndView models and views ModelAndView mv = new ModelAndView(); //In fact, another step here is to call the business layer //Encapsulate the object and place it in ModelAndView. Model mv.addObject("msg","HelloSpringMVC!"); //Encapsulate the view to jump to and put it in ModelAndView mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp return mv; } }
4) DispatcherServlet calls a specific view according to the view result parsed by the view parser. Get a specific view and show it to the front end.
**Conclusion: we need to do very little by ourselves**
- First, we need to write the corresponding Controller to call the business and complete the implementation of business logic.
- Set the name returned by the view
2.4 spring MVC implementation principle, annotation understanding
- Create a new module, spring mvc-030 Hello annotation
- As Maven may have the problem of over utilization of resources, it should be configured as follows:
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
- In POM XML file introduces related dependencies: mainly spring framework and core library, spring MVC, servlet, JSTL, etc. We have introduced in parent dependency.
- Configure web XML file
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--1.register servlet--> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--Specified by initialization parameters SpringMVC The location of the configuration file is associated--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!-- Start sequence: the smaller the number, the earlier the start --> <load-on-startup>1</load-on-startup> </servlet> <!--All requests will be rejected springmvc intercept --> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>