Spring MVC study notes-01 preliminary use

1. Three-tier architecture model (MVC)

A. Traditional development model Model1

       In the early Java Web development, JSP was responsible for the request and response, and called the database-related methods in JavaBean, which was called Model1 mode. The architecture of this approach is simple enough, but the functional responsibilities of JSP are not single, and it is difficult to achieve code reuse. At the same time, there is a serious coupling between JSP and JavaBean, which is not conducive to maintenance.

B. Traditional development model Model2

       In order to solve the above problems, Servlet technology came into being. All user requests will be intercepted by the Servlet first, then the corresponding Java Bean will be selected according to the request, and the result will be displayed by the JSP.

       The development architecture is generally based on two architectures, B/S (browser/server) and C/S (client/server). In JavaEE development, almost all are based on the B/S architecture. The standard three-tier architecture includes: presentation layer, business layer, and persistence layer.

Presentation layer : It is the web layer we often say, responsible for receiving client requests including request parameters, and responding to the results to the client. Usually the client uses the http protocol to request the web layer, and the web layer needs to receive the http request and respond to the customer service through the http response.

The presentation layer can be further divided into a control layer and a display layer: the control layer is responsible for receiving requests and their parameters, and the display layer is responsible for displaying results.

Business layer : the service layer we often say, responsible for business logic processing. The business layer may rely on the persistence layer during business processing. If you want to persist data, you need to ensure the consistency of things (transactions should be placed in the business layer to control).

Persistence layer : it is the dao layer we often say, responsible for data persistence operations.

MVC development model:

M: Model model is actually the JavaBean object we use to store data in development.

V: View view, used to display the results, such as JSP, HTML.

C: Controller controller, responsible for interacting with users and receiving requests, such as Servlet.

C. Spring MVC

        Spring MVC is a lightweight web framework based on the request-driven type of the MVC pattern implemented by Java. A simple Java class can be used as a controller for processing requests through a set of annotations without having to implement any interfaces. It also supports RESTful style request. And because it is a follow-up product of the Spring framework, it is very easy to use Spring integration. Simply understand that Spring MVC is a spring-based framework, which is an upgrade and extension of servlet. (The bottom layer of web development is servlet)

         Spring MVC can create controller objects to receive user requests and return processing results, and put them in the Spring MVC container. The controller object we created using the @Controller annotation is just an object of an ordinary class instead of a servlet (servlet must inherit HttpServlet), but Spring MVC gives the controller object the functions of receiving parameters and returning results.

         The entrance of Spring MVC is DispatcherServlet, and all requests are forwarded to the Controller object responsible for processing via DispatcherServlet.

Use experience:

0. Create a new web maven project

If you use maven to build automatically, you can modify the maven configuration file (settings.xml) to use Alibaba Cloud mirroring:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">

      <mirrors>
        <mirror>  
            <id>alimaven</id>  
            <name>aliyun maven</name>  
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
            <mirrorOf>central</mirrorOf>          
        </mirror>  
      </mirrors>
</settings>

After the automatic build is completed, we also need to manually add main/java, main/resource, the project structure is as follows:

1. Import dependencies

Since the automatically built projects are often different from our use environment, we need to manually adjust the pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>SpringMVC-01</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!--JDK版本-->
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!--servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <!--springmvc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
  </dependencies>
</project>

2. Register DispatcherServlet in web.xml

The web project built automatically by maven uses a low web-app version, so we changed it to 4.0.

The DispatcherServlet front controller (also called the central dispatcher) is a servlet inherited from HttpServlet; it is used to receive user requests, call the controller object responsible for processing the request, and return the processing results; in the init() method of DispatcherServlet , Created a SpringMVC container object and put it into ServletContext.

<?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">
    <!--注册DispatcherServlet,配置Tomcat启动后就创建-->
    <servlet>
        <!--SpringMVC容器创建时,读取的配置文件默认为<servlet-name>-servlet.xml-->
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>
            <!--自定义SpringMVC读取的配置文件的位置-->
            <param-name>contextConfigLocation</param-name>
            <!--类路径下的springmvc.xml文件(resources目录就是类路径)-->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>

        <!--Tomcat启动后,创建对象的顺序-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <!--配置DispatcherServlet拦截哪些请求-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
            使用框架时,url-pattern可以使用两种
            1. 扩展名  *代表通配符,匹配任意长度的路径  只看扩展名  *.do *.action 等
            2. 使用 "/"
        -->
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

3. Create a page index.jsp to initiate the request

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <p>第一个项目</p>
    <a href="some.do">发起请求</a>
</body>
</html>

4. Create Class Controller

1) Use @Controller to declare that this is a controller object and inject it into the Spring MVC container.

2) Use @RequestingMapping to declare the request path. The methods modified with @RequestingMapping are called processor methods or controller methods, which are used to process requests, similar to the doGet, doPost, and service methods in servlets.

3) Model: After the storage request is processed, the data to be returned to the user

    View: store the view used to display the data, such as jsp

package com.zzt.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {

    @RequestMapping("/some.do")
    public ModelAndView doSome(){
        ModelAndView modelAndView = new ModelAndView();

        // 存放数据 框架会自动将数据放到request作用域
        modelAndView.addObject("msg","hello-word");

        // 指定视图的路径 框架会自动通过forward进行请求转发 request.getRequestDispatcher("/show.jsp").forward(..)
        modelAndView.setViewName("/show.jsp");

        return modelAndView;
    }

}

5. Create a page to display the results

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <p>请求的参数为:${requestScope.get("msg")}</p>
</body>
</html>

6. Create SpringMVC configuration file

Since we use the @Controller annotation to annotate the controller class, we need to configure the scanner to scan the package and automatically inject the entity class into the container

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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-3.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.1.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <!--声明组件扫描器-->
    <context:component-scan base-package="com.zzt.Controller"/>

</beans>

 

Guess you like

Origin blog.csdn.net/qq_39304630/article/details/112604515