One of the foundations of spring MVC - > brief introduction and use

Keywords: Java Spring mvc

1. What is MVC?

MVC is the abbreviation of model, view and controller. It is a software design specification. It is 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, there are differences between different MVCs.

* * 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: Value Object (data Dao) and Service layer (line is Service). That is, the Model provides functions such as Model data query and Model data status update, including data and business.

* * View: * * is responsible for displaying the model, which is generally the user interface we see and what customers want to see.

* * Controller: * * receives the user's request and delegates 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. In other words, the Controller does the work of a dispatcher.

In fact, in the earliest days, there were design models of model1 and model2
The most typical MVC is the pattern of JSP + servlet + javabean.

Code display:

HelloServlet.java

package com.mashibing.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 {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if (method.equals("add")){
            request.getSession().setAttribute("msg","add");
        }else if(method.equals("sub")){
            request.getSession().setAttribute("msg","sub");
        }
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

web.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.mashibing.controller.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/user</url-pattern>
    </servlet-mapping>
</web-app>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  ${msg}
  </body>
</html>

Enter web address: http://localhost:8080/servlet_demo_war_exploded/user?method=add

2,SpringMVC

1. Introduction to spring MVC
Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, "Spring Web MVC," comes from the name of its source module (spring-webmvc), but it is more commonly known as "Spring MVC".
Spring Web MVC Is built on Servlet API Original on Web Framework, included from the beginning Spring Framework Yes. Official name“ Spring Web MVC," From its source module(spring-webmvc)But it is usually called“ Spring MVC". 

In short, Spring MVC is a part of the Spring framework and a lightweight web framework based on java implementation.

The core of learning spring MVC framework is the design of DispatcherServlet. Mastering DispatcherServlet is the core key to mastering spring MVC.

2. Advantages of spring MVC

1. Clear role division: controller, validator, command object, form object, model object, Servlet distributor, handler mapping, view resolver, etc. each role can be implemented by a special object.

2. Powerful and direct configuration method: both framework classes and application classes can be configured as JavaBean s, supporting references across multiple context s, such as references to business objects and validators in web controllers.
3. Adaptable and non intrusive: you can select a controller subclass (simple, command, from, wizard, multi action or custom) according to different application scenarios, rather than a single controller (such as Action/ActionForm) to inherit.
4. Reusable business code: existing business objects can be used as command or form objects without extending the base class of a specific framework.
5. Customizable binding and validation: for example, take type mismatch as an application level validation error, which can ensure the wrong value. For example, localized date and number binding, etc. in some other frameworks, you can only use string form objects, which need to be manually parsed and converted to business objects.
6. Customizable handler mapping and view resolution: Spring provides from the simplest URL mapping to complex and dedicated customization strategies. Compared with some web MVC frameworks that force developers to use a single specific technology, Spring is more flexible.
7. Flexible model transformation: in the spring web framework, Map based key / value pairs are used to easily integrate with various view technologies.
8. Customizable localization and theme parsing: support the optional use of Spring tag library in JSP, JSTL, velocity (no additional middle tier), etc.
9. Simple and powerful JSP tag library: it supports many functions such as data binding and theme. It provides maximum flexibility in tagging.
10.JSP form tag library: the form tag library introduced in spring 2.0 makes it easier to write forms in JSP.
11. The life cycle of spring bean: it can be limited to the current HTTp Request or HTTp Session. To be exact, this is not a feature of the Spring MVC framework itself, but should belong to the WebApplicationContext container used by Spring MVC.

3. Implementation principle of spring MVC

mvc mode of spring mvc:

Specific implementation process of spring MVC:

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 result using the model and view, returns the result to the central controller, and then returns the result to the user The seeker.

1. DispatcherServlet represents the front controller and is the control center of the whole spring MVC. When the user sends a request, the DispatcherServlet receives the request and intercepts the request.
2. HandlerMapping is a processor mapping. The DispatcherServlet calls HandlerMapping, which looks up the Handler according to the request url.
3. Return to the processor execution chain, find the controller according to the url, and pass the parsed information to the dispatcher servlet
4. The HandlerAdapter represents a processor adapter that executes the Handler according to specific rules.
5. Execute handler to find the specific processor
6. The Controller returns the specific execution information to the HandlerAdapter, such as ModelAndView.
7. The HandlerAdapter passes the view logical name or model to the dispatcher servlet.
8. DispatcherServlet calls the view resolver to resolve the logical view name passed by the HandlerAdapter.
9. The view parser passes the parsed logical view name to the dispatcher servlet.
10. DispatcherServlet calls a specific view according to the view result parsed by the view parser to attempt rendering
11. Return the response data to the client

3. XML based hello_spring MVC

1. Add pom dependency

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
    </dependencies>

2. Write a 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">
    <!--to configure DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--relation springmvc Configuration file for-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <!--matching servlet Your request,/Identity matches all requests-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--/*and/Blocking all requests,/The request that will be intercepted does not contain*.jsp,and/*It has a larger range and will intercept*.jsp These requests-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3. Write the spring configuration file required by spring MVC, applicationContext.xml

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

    <!--Process mapper-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
    <!--Processor adapter-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>

    <!--view resolver -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--Configure prefix-->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!--Configuration suffix-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="/hello" class="com.mashibing.controller.HelloController"></bean>
</beans>

4,HelloController.java

package com.mashibing.controller;


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

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

public class HelloController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //Create model and view objects
        ModelAndView mv = new ModelAndView();
        //Pass the required value into the model
        mv.addObject("msg","helloSpringMVC");
        //Set the view to jump to,
        mv.setViewName("hello");
        return mv;
    }
}

5. Create a hello.jsp page

<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/3/5
  Time: 20:25
  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. Configure tomcat and send request

http://localhost:8080/hello

4. Annotation based Hello_SpringMVC

1. Add pom dependency

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
    </dependencies>

2. Write a 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">
    <!--to configure DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
		relation springmvc Configuration file for
		-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <!--matching servlet Your request,
    /: The identity matches all requests but does not jsp page
    /*: Block all requests, block jsp page
    -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3. Write the applicationContext.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--Auto scan package, by IOC Control and management of containers-->
    <context:component-scan base-package="com.mashibing"></context:component-scan>
    <!-- view resolver  -->
    <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>
</beans>

4. Write HelloController.java

package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController{
    /*
    * @RequestMapping It is used to identify what requests this method is used to process, in which / can be cancelled
    * After canceling, the default is to start searching from the root directory of the current project. Generally, it depends on personal habits when writing
    * At the same time, @ RequestMapping can also be added to the class,
    * */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","hello,SpringMVC");
        return "hello";
    }
}

5. Write hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

6. Input request http://localhost:8080/hello

5. Pay attention to details

1,springmvc_helloworld running process:

Through the above code, we can summarize the specific operation process:

1. The client sends a request http://localhost:8080/hello

2. tomcat receives the corresponding request

3. DispatcherServlet, the front-end controller of spring MVC, receives all requests

4. Check which match between the request address and the @ RequestMapping annotation to find the processing method of the specific class

5. After the front-end controller finds the target processing class and method, execute the target method

6. After the method is executed, there will be a return value, which will be parsed and spliced into a complete page address by the view parser by spring MVC

7. After getting the page address, the dispatcher servlet forwards it to the specific page

2. Spring MVC configuration file

web.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">
    <!--to configure DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
		relation springmvc Configuration file for
		The properties of this profile may not be added, but they need to be WEB-INF Create the front-end controller name under the directory of-servlet.xml file
		-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
3. URL pattern of DispatcherServlet

web.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">
    <!--to configure DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
		relation springmvc Configuration file for
		The properties of this profile may not be added, but they need to be WEB-INF Create the front-end controller name under the directory of-servlet.xml file
		-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <!--matching servlet Your request,
    /: The identity matches all requests but does not jsp page
    /*: Block all requests, block jsp page

     However, it should be noted that when configured to index.html You will find that the request cannot be received
     The reason is, tomcat There's another one under web.xml File, under all items web.xml All files need to inherit this web.xml
     On the server web.xml There is one in the file DefaultServlet Used to handle static resources, but url-pattern yes/
     And if we add url-pattern=/Overrides the in the parent class url-pattern,At the time of request
     DispatcherServlet Will go controller If no match is found, report 404 directly
     And on the server web.xml The file contains a JspServlet Processing, so it's just interception jsp request
    -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
4,@RequestMapping

@ RequestMapping is used to match the requests sent by the client. It can be used on methods or classes.

Method: used to match the request to be processed

On class: means to add a pre path for the request addresses of all methods of the current class. This path must be added when accessing

package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/mashibing")
public class HelloController{

    /*
    * @RequestMapping It is used to identify what requests this method is used to process, in which / can be cancelled
    * After canceling, the default is to start searching from the root directory of the current project. Generally, it depends on personal habits when writing
    * At the same time, @ RequestMapping can also be added to the class,
    * */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","hello,SpringMVC");
        return "hello";
    }
}

Note: you cannot include the same @ RequestMapping value on different methods throughout the project

In addition, the @ RequestMapping annotation can add many additional attribute values to accurately match requests

package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/mashibing")
public class HelloController{

    /*
    * @RequestMapping It is used to identify what requests this method is used to process, in which / can be cancelled
    * After canceling, the default is to start searching from the root directory of the current project. Generally, it depends on personal habits when writing
    * At the same time, @ RequestMapping can also be added to the class,
    * */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","hello,SpringMVC");
        return "hello";
    }

    /**
     * Request Other attribute values for
     *  value:Requests to match
     *  method:Limit how requests are sent: POST GET
     *  params:Indicates the parameter to be accepted by the request. If this attribute is defined, the parameter must be added when sending
     *         params There are several matching rules
     *          1,Write the name of the parameter directly, param1,param2
     *              params = {"username"}
     *          2,Indicates that the request cannot contain parameters,! param1
     *              params = {"!username"}
     *          3,Indicates the parameters to be included in the request, but the limit value Param1 = values Param1= value
     *              params = {"username=123","age"}
     *              params = {"username!=123","age"}
     *  headers:Fill in request header information
     *          chrome: User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
     *          firefox:User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0
     *
     *  consumers:Only accepting requests for content type is equivalent to specifying content type
     *  produces:Content type returned: text/html;charset=utf-8
     *
     * @return
     */
    @RequestMapping(value = "/hello2",method = RequestMethod.POST)
    public String hello2(){
        return "hello";
    }

    @RequestMapping(value = "/hello3",params = {"username!=123","age"})
    public String hello3(String username){
        System.out.println(username);
        return "hello";
    }

    @RequestMapping(value = "/hello4",headers = {"User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0"})
    public String hello4(){
        return "hello";
    }
}

@ RequestMapping also includes many complex matching functions and provides wildcard support:

package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/mashibing")
public class HelloController{

    /*
    * @RequestMapping It is used to identify what requests this method is used to process, in which / can be cancelled
    * After canceling, the default is to start searching from the root directory of the current project. Generally, it depends on personal habits when writing
    * At the same time, @ RequestMapping can also be added to the class,
    * */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","hello,SpringMVC");
        return "hello";
    }

    /**
     * Request Other attribute values for
     *  value:Requests to match
     *  method:Limit how requests are sent: POST GET
     *  params:Indicates the parameter to be accepted by the request. If this attribute is defined, the parameter must be added when sending
     *         params There are several matching rules
     *          1,Write the name of the parameter directly, param1,param2
     *              params = {"username"}
     *          2,Indicates that the request cannot contain parameters,! param1
     *              params = {"!username"}
     *          3,Indicates the parameters to be included in the request, but the limit value Param1 = values Param1= value
     *              params = {"username=123","age"}
     *              params = {"username!=123","age"}
     *  headers:Fill in request header information
     *          chrome: User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36
     *          firefox:User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0
     *
     *  consumers:Only accepting requests for content type is equivalent to specifying content type
     *  produces:Content type returned: text/html;charset=utf-8
     *
     * @return
     */
    @RequestMapping(value = "/hello2",method = RequestMethod.POST)
    public String hello2(){
        return "hello";
    }

    @RequestMapping(value = "/hello3",params = {"username!=123","age"})
    public String hello3(String username){
        System.out.println(username);
        return "hello";
    }

    @RequestMapping(value = "/hello4",headers = {"User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0"})
    public String hello4(){
        return "hello";
    }

    /**
     * @Request There are three fuzzy matching methods:
     *  ?: Can replace any character
     *  *: It can replace any number of characters and a layer of path
     *  **: Can replace multi-layer path
     * @return
     */
    @RequestMapping(value = "/**/h*llo?")
    public String hello5(){
        System.out.println("hello5");
        return "hello";
    }
}

6,@PathVariable

How should I use the parameters in the request path as parameters? You can use the @ PathVariable annotation, which provides support for placeholder URLs, that is, binding placeholder parameters in URLs to parameters of controller processing methods.

package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/mashibing")
public class HelloController{

    @RequestMapping(value = "/pathVariable/{name}")
    public String pathVariable(@PathVariable("name") String name){
        System.out.println(name);
        return "hello";
    }
}

7,REST

REST, i.e. Representational State Transfer (REST) is a concept put forward by Dr. Roy Fielding in his doctoral thesis in 2000 Software architecture Style. It is aimed at network application The design and development method can reduce the complexity of development and improve the scalability of the system.

In three mainstream Web Services In the implementation scheme, because the REST mode of Web services is complex SOAP and XML-RPC In contrast, it is obviously more concise. More and more web services are designed and implemented in the REST style. For example, Amazon.com provides a REST style web service for book search; Yahoo The Web services provided are also REST style.

REST, translated as presentation layer state transformation, is the most popular Internet software architecture at present. Its architecture is clear, conforms to standards, easy to understand and easy to expand.

Presentation layer: the form in which resources are concretely presented, so it is called presentation layer.

Resource: a specific information, text, picture, audio and video on the network can be called a resource. If you want to access a resource on the Internet, you must use a URL to uniquely obtain the modified resource. In other words, the URL is the unique identifier of each resource.

State Transfer: when the client sends a request, it represents an interactive process between the client and the server. HTTP is a stateless protocol, that is, all States are saved on the server. Therefore, if the client wants to operate the server, it must use some means to convert the state of the server, This transformation is based on the expression level, which is the origin of the name (non-human words)

Human words: when we obtain resources, we add, delete, modify and query. If it is the original architecture style, we need to send four requests, namely:

Query: localhost:8080/query?id=1

Add: localhost:8080/insert

Delete: localhost:8080/delete?id=1

Update: localhost:8080/update?id=1

It is troublesome to send requests in this way, and multiple requests need to be defined. In the HTTP protocol, there are different ways to send requests, such as GET, POST, PUT, DELETE, etc. if we can make different request methods represent different request types, we can simplify our query

GET: GET resource / book/1

POST: new resource / book

PUT: update resource / book/1

DELETE: DELETE resource / book/1

Everything looks very beautiful, but you should note that when we send a request, we can only send post or get. There is no way to send put and delete requests. So what should we do? Let's start the code phase:

RestController.java

package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Controller
public class RestController {

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String add(){
        System.out.println("add to");
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        System.out.println("Delete:"+id);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.PUT)
    public String update(@PathVariable("id") Integer id){
        System.out.println("to update:"+id);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String query(@PathVariable("id") Integer id){
        System.out.println("Query:"+id);
        return "success";
    }
}

web.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">
    <!--to configure DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
        relation springmvc Profile for:
        The properties of this profile may not be added, but they need to be WEB-INF Create the front-end controller name under the directory of-servlet.xml file
        -->

        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <!--matching servlet Your request,
    /: The identity matches all requests but does not jsp page
    /*: Block all requests, block jsp page

     However, it should be noted that when configured to index.html You will find that the request cannot be received
     The reason is, tomcat There's another one under web.xml File, under all items web.xml All files need to inherit this web.xml
     On the server web.xml There is one in the file DefaultServlet Used to handle static resources, but url-pattern yes/
     And if we add url-pattern=/Overrides the in the parent class url-pattern,At the time of request
     DispatcherServlet Will go controller If no match is found, report 404 directly
     And on the server web.xml The file contains a JspServlet Processing, so it's just interception jsp request
    -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>hiddenFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

rest.jsp

<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/3/6
  Time: 23:01
  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>
    <form action="/user" method="post">
        <input type="submit" value="increase">
    </form>
    <form action="/user/1" method="post">
        <input name="_method" value="delete" type="hidden">
        <input type="submit" value="delete">
    </form>
    <form action="/user/1" method="post">
        <input name="_method" value="put" type="hidden">
        <input type="submit" value="modify">
    </form>
    <a href="/user/1">query</a><br/>
</body>
</html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
666
</body>
</html>

Posted by paha77 on Tue, 21 Sep 2021 16:15:03 -0700