What is Spring MVC

Spring’s Web MVC framework, like many other Web MVC frameworks, is request-driven. The Spring Web Model-View-Controller (MVC) framework is designed around dispatcherServlets, which dispatch requests to handlers, There is configurable handler mapping, view resolution, locale and topic resolution, as well as support for uploading files. The default handler, based on the @Controller and @RequestMapping annotations, provides a variety of flexible processing options.

Spring MVC request handling mechanism

This diagram depicts the basic logic of Spring MVC for handling Web requests

  1. The request first goes to the Front Controller (DipatcherServlet), where the front controller assigns the request to the corresponding controller.
  2. Handle the request using the logic in the specific controller and return a model to the Front controller
  3. The front Controller gives the model to the view template to render the view and gives the result to the Front Controller

Statement of the controller

Spring MVC provides an annotation-based programming pattern where the @Controller,@RestController elements handle request mapping, request input, and exception Handle.

  • @Controller
  • @restController equals @Controller + @responseBody

Map request handling methods

@requestMapping is a method used to map Web requests to request processing classes. Provides parameters that limit requests for mapping:

  • Path,value Mapping request URI,String array, can map multiple URIs, can ignore the parameter name, for example: @requestMapping (“/foo”).
  • Method Specifies the allowed HTTP request methods. The OPTIONS are GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, and TRACE, for example: Method = requestmethod. GET, which has no default value. If method is not specified, requests that use GET, POST, PUT, PATCH, or DELETE methods can be mapped to this method.
  • Params maps request parameters, 1. Request parameters must contain the set value to map to the method (eg. params = “myParam=myValue”,), 2. The request parameter must not have this parameter to map to the method (eg. params = “! Name “), 3. Request parameters must contain the specified parameters to map to the method (eg. params = “name”)
  • Headers specifies whether to map the headers of a request. (eg. headers = “content-type=text/*”, headers = “text/ HTML” or text/plain can be mapped to this method.)
  • As consumes, it limits the Content-type of requests. The consumes are used to represent the media types in the requests. You can use the consumes command. Consumes = {“text/plain”, “application/*”})
  • Produces accepts the request (The Accept field in the request lets the server know which media types are acceptable to the client.) “, you can use “! Produces = {“text/plain”, “application/*”}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

Other annotations

  • @getMapping = @requestMapping + (method = requestmethod.get)
  • @PostMapping
  • @PutMapping

URL patterns

  • “/resources/ima? e.png” – match one character in a path segment
  • “/resources/*.png” – match zero or more characters in a path segment
  • “/resources/**” – match multiple path segments
  • “/projects/{project}/versions” – match a path segment and capture it as a variable
  • “/projects/{project:[a-z]+}/versions” – match and capture a variable with a regex

The captured URI variable can be accessed with @pathvariable For example:

@GetMapping("/owners/{ownerId}/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
    // ...
}
Copy the code

URL variables can be declared at the class or method level,

@Controller
@RequestMapping("/owners/{ownerId}")
public class OwnerController {

    @GetMapping("/pets/{petId}")
    public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
        // ...}}Copy the code

handle method

The method parameters

The following table describes the method parameters that support controller, none of which support response types.

Controller method argument Description
WebRequest Access request parameters and session properties.
@PathVariable Access URI template variables
@MatrixVariable Used to access name-value pairs in the URI Path fragment
@RequestParam To access servlet request parameters,
@RequestHeader Used to access the servlet request header
@CookieValue To access cookies
@RequestBody Access the HTTP Request Body and convert the body into a parameter object for this method

Overview Map and Model Spring MVC internally USES a org. Springframework. UI. The Model interface data storage Model.

Spring MVC creates an implicit model object as a storage container for model data before invoking a method. If method inputs are of type Map or Model, Spring MVC passes a reference to the implicit Model to those inputs. Within the method body, the developer can access all the data in the model through this input object, and can also add new attribute data to the model.

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

import com.ricky.codelab.webapp.ch2.model.User;

@Controller
@RequestMapping("model")
public class ModelController {

    @RequestMapping("register")
    public String register(User user, Model model){

        model.addAttribute("user", user);

        return "home";
    }

    @RequestMapping("register2")
    public String register(User user, Map<String, Object> map){

        map.put("user", user);

        return "home"; }}Copy the code

Return Value

The method annotated by @responsebody returns data that is bound to the ResponseBody. The return value can be a String or an object

@GetMapping("/accounts/{id}")
@ResponseBody
public Account handle(a) {
    // ...
}
Copy the code

reference

Docs. Spring. IO/spring – fram…