4 essential knowledge points for learning SpringMVC

1. What is SpringMVC

We learned about Spring and SpringBoot earlier, so what is Spring MVC? Regarding the three, we can understand it this way: Spring MVC is the core module of the Spring framework, and Spring Boot is the scaffolding of Spring.

Spring MVC, also known as Spring Web MVC, is an original web framework built on the Servlet API. Spring MVC has been included in the Spring framework from the beginning and is a core module of the Spring framework.

MVC is an idea, and Spring MVC is a specific implementation of the MVC idea.

2. MVC architecture pattern

Previously, we have had enough understanding of Spring, so what is MVC?
MVC stands for Model View Controller. It is a software architecture pattern in software engineering. It divides the software system into three basic parts: model, view and controller.

  1. Model: The model layer represents the application's data and business logic. It is responsible for obtaining data from databases or other data sources, processing and managing the data.
  2. View: The view layer is the presentation layer of the user interface and is responsible for displaying and rendering data to the user.
  3. Controller: The controller layer is responsible for receiving and processing user requests, and scheduling appropriate models and views for processing according to the requests.

The business execution process in MVC mode is shown in the figure below:

  1. First, the user's request reaches the Controller first.
  2. The Controller then dispatches the Model layer based on the request
  3. The Model layer processes the request information and returns the data results to the Controller layer
  4. The Controller dispatches the View layer based on the returned results
  5. View processes the result data and presents the final generated page to the user

3. SpringMVC core functions

1. Route mapping

Route mapping: The so-called route mapping refers to the process of mapping the user's request to a method of a certain class in the program when the user accesses a URL. It's called route mapping.

Note: @RequestMapping can be used in SringMVC to register the route mapping of the interface. @RequestMapping can modify classes or methods. When modifying classes and methods at the same time, the accessed URL needs to carry the routes of both classes and methods.

Usage example:

// @RestController 是一个组合注解,作用是设置响应主体,后续介绍
@RestController
@RequestMapping("/test")
public class TestController {
    
    
    @RequestMapping("/hello")
    public String sayHello() {
    
    
        return "hello SpringMVC!";
    }
    @PostMapping("/hello2")
    public String sayHello2() {
    
    
        return "hello SpringMVC2!";
    }
}

Visit the url of "hello SpringMVC!": 127.0.0.1:8080/test/hello

Visit the url of "hello SpringMVC2!": 127.0.0.1:8080/test/hello2

Additional instructions:

  1. The route registered using @RequestMapping can handle all HTTP requests.
  2. can set the value of method in the @RequestMapping annotation to process a single request. For example: @RequestMapping(value = “/hello2”, method = RequestMethod.GET)
  3. SpringMVC also provides some mapping annotations that specify request types, such as @GetMapping, @PostMapping, etc.

2. Get parameters

(1) Get a single parameter

    @RequestMapping("/getname")
    public void getName(String name) {
    
    
        System.out.println("name:"+name);
    }

When accessing 127.0.0.1:8080/test/getname?name=lihua, or there is a parameter named name in the form, the value of the parameter can be obtained in the method. If there is no parameter with the same name, it will be empty.

(2) Get multiple parameters

    @RequestMapping("/getname")
    public void getName(String name,String pwd) {
    
    
        System.out.println("name:"+name+";pwd:"+pwd);
    }

When accessing 127.0.0.1:8080/test/getname?name=lihua&pwd=123, or using the form to submit parameters with the same name, the value of the parameter can be obtained in the method. If there is no parameter with the same name, it will be empty.

When we pass multiple parameters, we can also use 对象 to receive:

    @RequestMapping("/getuser")
    public void getName(User user) {
    
    
        System.out.println(user.toString());
    }

Note: When there are multiple parameters, when matching parameters, the parameters are matched according to 名称, so the position of the parameters It does not affect the result of the backend obtaining parameters. Unmatched parameters default to null.

(3) Backend parameter renaming
In some scenarios, the parameters used by our backend may be different from those passed by the frontendkey The key value of the parameter. At this time we can use @RequestParam to rename the parameter name.

    @RequestMapping("/getname")
    public void getUser(@RequestParam("n") String name, String pwd) {
    
    
        System.out.println("name:"+name+";pwd:"+pwd);
    }

Note: When the front-end passes parameters at this time, there must be a parameter named n, otherwise an error will be reported. This is because there is a parameter required in the @RequestParam annotation that defaults to required = true, which means that the parameter must be passed. If it is set to false, it defaults to null if it cannot be obtained.

(4) Receive JSON object

    @RequestMapping("/getjson")
    public void getJson(@RequestBody User user) {
    
    
        System.out.println(user.toString());
    }
  1. The front-end submits data through JSON, and the back-end must use @RequestBody to receive it.
  2. Using the @RequestBody annotation allows Spring MVC to automatically convert the contents of the request body into the object or type required for the method parameters.

(5) Get the parameters in the URL

    @RequestMapping("/geturlpart/{name}/{pwd}")
    public void getUrlpart(@PathVariable("name") String name
    ,@PathVariable("pwd") String password) {
    
    
        System.out.println("name: "+name+" ;password: "+password);
    }
  1. where {name} and {pwd} are path parameters used to obtain the corresponding values ​​from the request URL.
  2. @PathVariableAnnotations indicate binding path parameters to method parameters.
  3. There is a required parameter in @PathVariable, which defaults to true, which means it must be passed. Can be set to false as an optional parameter. @PathVariable(value = “pwd”, required = false)

(6) Get uploaded files

    @RequestMapping("/upload")
    public String upload(@RequestPart("myfile")MultipartFile file) throws IOException {
    
    
        // 1.生成一个唯一 id
        String id = UUID.randomUUID().toString().replace("-","");
        // 2.获取源文件后缀名
        String suffix = file.getOriginalFilename().
        substring(file.getOriginalFilename().lastIndexOf("."));
        // 3.设置文件完整保存路径
        String path = "D:/resource/"+id+suffix;
        file.transferTo(new File(path));
        return path;
    }

  1. @RequestPart("myfile")The annotation is used to bind the binary data part named "myfile" in the request to the method parameter file of type MultipartFile.
  2. UUID.randomUUID().toString().replace("-", "")What this line of code does is generate a random string ID that does not contain hyphens.
  3. transferTo(File dest)The method will copy the contents of the file represented by the current File object to the target file dest. If the target file already exists, this method will overwrite the contents of the target file. If the target file does not exist, this method will automatically create the target file and write the contents into it.

(7) Get Header
@CookieValue annotation is used to bind the Header value of the specified name to the method parameter.

    @RequestMapping("/getheader")
    public void header(@RequestHeader("User-Agent") String userAgent) {
    
    
        System.out.println("userAgent:"+userAgent);
    }

(8) Get Cookie
@CookieValue The annotation is used to bind the cookie value of the specified name to the method parameter.

    @RequestMapping("/getcookie")
    public void getCookie(@CookieValue(value = "mycookie",required = false) String mycookie) {
    
    
        System.out.println("mycookie: "+mycookie);
    }

(9) Get Session
@SessionAttribute annotation can be used to get the attribute value of the specified name from the session and bind it to the parameters of the controller method.

    @RequestMapping("/getsession")
    public void sess2(@SessionAttribute(value = "username",required = false) String username) {
    
    
        System.out.println("username:"+username);
    }

3. Return data

@ResponseBodyThe mark method will return the return value of the mark method directly to the client as the response body. During the return process, Spring MVC will automatically convert the return value of the method into the appropriate format.

	@ResponseBody
    @RequestMapping("/get1")
    public String get1(){
    
    
        return "<h1>标题1</h1>";
    }

	@ResponseBody
    @RequestMapping("/get2")
    public User get2(){
    
    
        return new User();
    }

  1. @ResponseBodyCan be used to modify methods or classes. If you modify the class, it means that the return values ​​of all methods in the class are directly returned to the client as the response body.
  2. @ResponseBody marked method, if the returned value is a string, it will be converted to text/html, or ordinary 字符串 according to the string content. If an object is returned, it will be converted into application/json and returned to the front end.
  3. @RestController= @Controller + @ResponseBody. Used to modify classes.

4. Request forwarding and request redirection

1. Request forwarding

Request forward (forward): Request forwarding means that after receiving the client's request, the server forwards the request to another resource in the server for processing, and then processes the request. The results are returned to the client. During the request forwarding process, the client browser does not know that the server has forwarded the request. It thinks it is still interacting with the original URL. Request forwarding uses an internal jump within the server, and the URL in the URL address bar will not change.

Specific implementation methods:

Get the forwarder request.getRequestDispatcher(“/要跳转到地址”)
Call the forwarder method: forward(request, response)

Complete method:

request.getRequestDispatcher(/url”).forward(request, response);

Features of request forwarding:

  1. Request forwarding is a server behavior and does not support cross-domain access. It can only jump to resources in the current application.
  2. The entire request forwarding process involves only one request and one response. After the request is forwarded, the URL in the browser's address bar will not change, so the browser does not know that forwarding occurred within the server, let alone the number of forwardings.
  3. Web resources participating in request forwarding share the same request object and response object.

2. Request redirection

Request redirection (redirect): Request redirection means that after the server receives the client's request, it sends an HTTP response to the client to tell it that it needs to resend a new one. Request to the specified URL. After receiving the response, the client will immediately send a new request to the specified URL. During the request redirection process, the URL address bar will display the redirected URL.

Specific implementation methods:

response.sendRedirect(“访问的地址”);

Features of request redirection:

  1. Request redirection is a client behavior, and a major feature is that it supports cross-domain access.
  2. Request redirection involves two requests and two responses. The first request returns a 302 redirect response. After the client receives the 302 response, the redirected URL receives the second response.
  3. Request redirection and two request responses respectively correspond to different request/response objects.

3. Summary

the difference Forward Redirect
behavior type server behavior client behavior
Has the URL in the browser address bar changed? no yes
Whether to support cross-domain jump no yes
Number of requests and responses One request and one response Two requests and two responses
To enjoy the good or not request to share response to share yes no
speed relatively fast relatively slow

Guess you like

Origin blog.csdn.net/LEE180501/article/details/132711308