spirngMVC(1)-What is SpringMVC

1Review of MVC

MVC is an abbreviation of model (Model (mapper service)), view (View (jsp)), and controller (Controller (servlet)). It is a software design specification. It
is a method of separating business logic, data, and display to organize code
1 Model The
data model provides the data to be displayed, so it contains data and behavior. The model provides functions such as model data query and model data status update, including data and business.
2 Views are
responsible for the display of the model, which is generally what we see User interface, what the customer wants to see
3 The controller
receives user requests, delegates to the model for processing (state change), and returns the returned model data to the view after processing, and the view is responsible for display. In other words, the controller did the job of a dispatcher

The project is divided into three parts, including view, control, and model.
Responsibility analysis as shown in the following figure :
Controller: controller to
obtain form data to
call business logic
to go to the specified page
Model: model
business logic to
save the state of the data
View: view to
display the page
Insert picture description here
1 the user sends a request 2
Servlet receives the requested data and calls the corresponding business logic Method
3 After the business processing is completed, return the updated data to the servlet. 4
Servlet turns to JSP, and JSP renders the page.
5 Responses to the updated page of the front end

2Review Servlet

1 Create a new Maven project as the parent project

<dependencies>
   <dependency>
       <groupId>junit</groupId>
       <artifactId>junit</artifactId>
       <version>4.12</version>
   </dependency>
   <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-webmvc</artifactId>
       <version>5.1.9.RELEASE</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>

2 Create a Moudle: springMVC-servlet, add Web app support
Insert picture description here
3 Import servlet and jsp jar dependencies

<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>

4 Write a Servlet class to process user requests

package com.zs.controller;

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 {
    
    
        //取得参数
        String method = req.getParameter("method");
        if (method.equals("add")){
    
    
            req.getSession().setAttribute("msg","执行了add方法");
        }
        if (method.equals("delete")){
    
    
            req.getSession().setAttribute("msg","执行了delete方法");
        }
        //业务逻辑
        //视图跳转
        req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req,resp);
    }
}

5 Write Hello.jsp, create a new jsp folder in the WEB-INF directory, create a new hello.jsp
Insert picture description here

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2021/1/24
  Time: 9:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${
    
    msg}
</body>
</html>

6 Register Servlet in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.zs.controller.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hellp</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

7 Configure Tomcat and start the test
http://localhost:8080/hello?method=add
Insert picture description here
execution process
Insert picture description here

3 what is SpringMVC

Spring MVC is part of the Spring Framework, lightweight Web is based on a Java implementation of the MVC framework
Spring MVC characteristics:
lightweight, easy to learn
and efficient, based on MVC request response frame
good compatibility with the Spring, seamless integration
convention over Configuration
Powerful: RESTful, data validation, formatting, localization, themes, etc.
Simple and flexible
Spring web framework is designed around DispatcherServlet [Scheduling Servlet]

3.1 Central Controller DispatcherServlet

Spring's web framework is designed around DispatcherServlet. The role of DispatcherServlet is to distribute requests to different processors (controllers), it is recommended to use annotation-based controller declaration

3.2 Explain the principle through the HelloMVC program

1 Create a new Moudle, springmvc-02-hello, add web support!

2 Make sure to import SpringMVC dependencies!

3 configure web.xml, register DispatcherServlet

<!--1.注册DispatcherServlet-->
   <servlet>
       <servlet-name>springmvc</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
       <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
       <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc-servlet.xml</param-value>
       </init-param>
       <!--启动级别-1-->
       <load-on-startup>1</load-on-startup>
   </servlet>

   <!--/ 匹配所有的请求;(不包括.jsp)-->
   <!--/* 匹配所有的请求;(包括.jsp)-->
   <servlet-mapping>
       <servlet-name>springmvc</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>

4 Write SpringMVC's configuration file springmvc-servlet.xml to explain that the name requirements here are 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">

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

    <!--视图解析器:DispatcherServlet给他的ModelAndView-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

Add processing mapper

    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

Add processor adapter

    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

Add view resolver

    <!--视图解析器:DispatcherServlet给他的ModelAndView-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

5 write the controller we want to operate the business

package com.zs.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//注意:这里我们先导入Controller接口
public class HelloController implements Controller {
    
    

    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    
        //ModelAndView 模型和视图
        ModelAndView mv = new ModelAndView();

        //封装对象,放在ModelAndView中。Model
        mv.addObject("msg","HelloSpringMVC!");
        //封装要跳转的视图,放在ModelAndView中
        mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
        return mv;
    }

}

6 Give your own class to the SpringIOC container and register the bean

    <!--Handler-->
    <bean id="/hello" class="com.zs.controller.HelloController"/>

7Write the jsp page to be jumped, display the data stored in ModelandView, and our normal page

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2021/1/24
  Time: 9:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${
    
    msg}
</body>
</html>

7 Configure Tomcat to start the test!
Insert picture description here
Insert picture description here

3.3 SpringMVC execution principle

Insert picture description here

Insert picture description here
Insert picture description here
The picture shows a more complete flow chart of SpringMVC. The solid line represents the technology provided by the SpringMVC framework and does not need to be implemented by the developer, and the dotted line represents that it needs to be implemented by the developer.
Brief analysis of the execution process
1 DispatcherServlet represents the front controller , which is the control center of the entire SpringMVC. The user sends a request, and the DispatcherServlet receives the request and intercepts the request.
We assume that the requested url is: http://localhost:8080/SpringMVC/hello,
as the url above is split into three parts:
http://localhost:8080 server domain name
SpringMVC deployed on the server web site
hello means that the controller
passes analysis, The above url is expressed as: request the hello controller of the SpringMVC site on the server localhost:8080.
2 HandlerMapping is the processor mapping . DispatcherServlet calls HandlerMapping by itself , and HandlerMapping finds Handler according to the request url .
Insert picture description here
3 HandlerExecution represents a specific Handler , its main function is to find the controller according to the url, as the above url is searched for the controller: hello.
Insert picture description here
4HandlerExecution passes the parsed information to DispatcherServlet, such as parsing controller mapping and so on.
5 HandlerAdapter represents the processor adapter , which executes the Handler according to specific rules.
Insert picture description here
6 Handler lets specific Controller execute .
Insert picture description here
7 Controller returns specific execution information to HandlerAdapter, such as ModelAndView .
Insert picture description here
8 HandlerAdapter passes the view logical name or model to DispatcherServlet.
9 **DispatcherServlet calls the view resolver (ViewResolver)** to resolve the logical view name passed by HandlerAdapter.
Insert picture description here
10 The view resolver passes the resolved logical view name to DispatcherServlet .
Insert picture description here
11 DispatcherServlet calls specific views according to the view results parsed by the view parser.
12 The final view is presented to the user.

Guess you like

Origin blog.csdn.net/zs18753479279/article/details/113066413