SpringMVC
ssm: mybatis + Spring + spring MVC MVC three-tier architecture
JavaSE: Study hard and get started quickly
JavaWeb: Study hard and get started quickly
SSM framework: study official documents, exercise self-study ability, exercise note taking ability and exercise project ability
----------->-------->--------->---------->
SpringMVC + Vue +SpringBoot + SpringCloud + Linux
SSM integration = JavaWeb project;
Spring: IOC and AOP
Spring MVC: the execution process of spring MVC!
Spring MVC: SSM framework integration!
1. Review MVC
What is MVC?
- MVC: short for model (dao, service), view (jsp) and controller. It is a software 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, MVC is an architecture pattern. Of course, different MVCs are different
Model: data model, which provides data to be displayed, contains data and behavior. It can be considered as domain model or JavaBean component (including data and behavior), but now it is generally separated: Value Object (data Dao) and Service layer (behavior Service) In other words, the model provides functions such as model data query and model data status update, including data and business.
View: it is responsible for displaying the model, which is generally the user interface we see and what customers want to see.
Controller: receives user requests and delegates them to the model for processing (state change). After processing, the returned model data is returned to the view, which is responsible for displaying. That is, the controller does the work of a dispatcher.
The most typical MVC is the pattern of JSP + servlet +javabean.
JSP is the view layer, which is responsible for presentation. servlet is the controller, which is responsible for receiving and processing requests and returning response data to the view layer for presentation. JavaBean includes Service and Dao, which are responsible for connecting the database and updating model data. Dao is the defined interface and Service is its implementation class.
Model1 Era
- In the early development of web, model 1 is usually used.
- Model1 is mainly divided into two layers: view layer and model layer.
- Because the underlying essence of a Jsp is a Servlet
Advantages of Model1: simple architecture, more suitable for small project development;
Model1 disadvantages: JSP responsibilities are not single, responsibilities are too heavy, and it is not easy to maintain;
Model 2 era
Model 2 divides a project into three parts, including view, control and model.
- User sends request
- The Servlet receives the request 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 front-end updated page
Responsibility analysis:
Controller: controller
- Get form data
- Call business logic
- Go to the 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 Model1 model is relatively simple and suitable for rapid development of small-scale projects. The JSP page in Model1 plays two roles of View and Controller, mixing control logic and presentation logic together, resulting in very low code reuse and reduced application cost And increases the difficulty of maintenance.
Model 2 eliminates the disadvantages of model 1.
2. Review servlets
-
Create a Maven project as the parent project. Import Pom dependencies.
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.9</version> </dependency> <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>
-
Create a Module: springmvc-01-servlet (create a common project. If it is webapp, its web.xml version is given by idea, and the version is wrong)
Add web framework Support manually.
Right click the sub module just created in idea, and there is an add framework support under new... Now it is a web project
-
Import dependencies for subprojects (in fact, it can be omitted)
<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 (and register in web.xml)
-
As long as an ordinary class inherits HttpServlet, it becomes a Servlet, because the parent class of HttpServlet implements the Servlet interface.
-
Override its two methods, doget and dopost
package com.dogeleft.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1. Get front-end parameters String method = req.getParameter("method"); if(method.equals("add")){ req.getSession().setAttribute("msg","Called add method!"); } if(method.equals("delete")){ req.getSession().setAttribute("msg","Called delete method!"); } // 2. Call the business layer // 3. View forwarding or redirection req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
-
Register the servlet in web.xml and configure the mapping.
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.dogeleft.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>hello_servlet</url-pattern> </servlet-mapping>
-
Create a Jsp page in WEB-INF and forward it here by servlet.
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>My test page</title> </head> <body> <p>in order to see far away</p> <p>Take it to the next level</p> ${msg} </body> </html>
-
-
Configure tomcat and start.
- Enter the shell_servlet? Method = add in the browser's pattern
- Enter hello_servlet?method=delete in the browser's pattern
- You can forward it to the jsp through the servlet
- Enter the shell_servlet? Method = add in the browser's pattern
What does the MVC framework do
- Mapping URLs to java classes or methods of java classes
2. Encapsulate the data submitted by the user
3. Processing request -- calling related business processing -- encapsulating response data
4. Render the response data. jsp / html and other presentation layer data.
explain:
Common server-side MVC frameworks include structures, Spring MVC, ASP.NET MVC, Zend Framework and JSF; common front-end MVC frameworks include vue, angularjs, react and backbone; other models evolved from MVC: MVP, MVVM, etc
3. Get to know spring MVC
Spirng MVC is a part of the Spring Framework and a lightweight Web framework based on Java to implement MVC.
Many details can be found in the official Spring documentation. Index of /spring-framework/docs
Why should we learn spring MVC?
Features of Spring MVC:
- Lightweight, easy to learn
- Efficient, request response based MVC framework
- Good compatibility with Spring and seamless combination
- Convention over configuration
- Powerful functions: RESTful, data validation, formatting, localization, theme, etc
- Concise and flexible
Tip:
Spirng: it's a hodgepodge. We can register all beans used in Spring MVC into Spring!
Spring's web framework is designed around the dispatcher Servlet.
Dispatcher servlet is used to distribute requests to different processors. Starting from Spirng 2.5, users using Java 5 or above can develop based on annotations, which is very concise;
Because Spring MVC is good, simple, convenient and easy to learn, it is naturally seamlessly integrated with Spring (using SpringIoc and Aop), the use of conventions is better than configuration, and it can carry out simple junit testing. It supports Restful style, exception handling, local language, internationalization, data validation, type switching, interceptors, etc.. So we need to learn.
The most important point is that there are many people and companies.
RESTful style: the url does not need a question mark to pass parameters.
3.1 central controller
Spring's web framework is designed around dispatcher servlet. The dispatcher servlet is used to distribute requests to unused processors. Starting from spring 2.5, users using Java 5 or above can adopt annotation based controller declaration.
Like many other MVC frameworks, the Spring MVC framework is request driven. It distributes requests and provides other functions around a central Servlet. The dispatcher Servlet is an actual Servlet (it inherits from the HttpServlet base class).
The inheritance system of dispatcher servlet is shown in the figure below.
These two top-level abstract classes belong to the servlet level provided by java.
The five servlet s in the figure include those provided by java and spring MVC.
servlet provided by java:
- GenericServlet abstract class, which implements the Servlet interface
- HttpServlet abstract class, which inherits GenericServlet
servlet provided by Spring:
- HttpServletBean
- FrameworkServlet
- DispatcherServlet
The core method of Dispatcher is doService(req,resp). (know in advance)
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.
3.2,HelloSpringMVC
-
Create a new Module and add web support!
-
Confirm that the dependency of spring MVC is imported!
-
Configure web.xml and register DispatcherServlet.xml
-
Write the configuration file of spring MVC! Name: springmvc-servlet.xml:[servletname]-servlet.xml description. The name here is required according to the official
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
-
Add process mapper