SpringMVC

Table of Contents

1. Learn Spring MVC

1.1 Learning questions

1.2 Create MVC project

2. Realize the “connection” between the client and the program

2.1 @RequestMapping

2.2 @GetMapping and @PostMapping

3. Get parameters

3.1 Get a single parameter

3.2 Get multiple parameters

3.3 Passing objects

3.4 Passing parameters from a single table

3.5 Backend parameter renaming

?edit

3.5.1 Required parameter @RequestParam

3.5.2 No parameters are passed unless required

3.6 @RequestBody Get JSON object

3.7 Get parameters in URL @PathVariable

3.8 Upload files @RequestPart

3.9 Get Cookie/Session/header

3.9.1 @CookieValue Get Cookie

3.9.2 @SessionAttribute Get Session

3.9.3 @RequestHeader Get Header

4. Return data

4.1 Return to static page

4.2 @ResponseBody returns text/html

4.3 Request forwarding or request redirection (high frequency in interviews)


Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring framework since ? Its official name “Spring Web MVC” comes from the name of its source module (Spring-webmvc), but it is often referred to as “Spring MVC”.

1Spring MVC is a web framework

2Spring MVC is built on Servlet API

MVC: MVC is the abbreviation of Model View Controller. It is a software architecture pattern in the software process. It divides the software system into three basic parts: model, view and controller.

  • Model: It is the part of the application where the user handles application data logic. Usually the model object is responsible for accessing data in the database
  • View: is the part of the application that handles data display. Usually views are created based on model data
  • Controller: The part of the application that handles user interaction. Usually the controller is responsible for reading data from the view, controlling user input, and sending data to the model.

MVC and Spring MVC relationship:

  • MVC is an idea, and Spring MVC is a specific implementation of the MVC idea.
  • Spring MVC is a web framework that implements the MVC pattern and inherits the Servlet API. Since it is a web framework, when the user enters the url in the browser, our Spring MVC project can sense the user’s request

1.Learn Spring MVC

Most Java projects now are based on Spring (or Spring Boot), and the core of Spring is Spring MVC

Next we need to master the three major functions of Spring MVC:

1Connection: Connect the user (browser) and Java program, that is, accessing this address can call our Spring program

2Getting parameters: Users will bring some parameters when they visit. You must find a way to get the parameters in the program.

3.Output data: After executing the business logic, the program execution results must be returned to the user.

1.1 Learning Questions

1. How to realize the connection between the client and the program? Use @RequestMapping in Spring MVC to implement URL routing mapping, which is the role of the browser connection program; the next function to be implemented is the access address: http://localhost:8080/user/hi , can print “hello, spring mvc” information.

2.Does @RequestMapping support all request types?

3. In addition to @ResquestMapping, is there any other way to achieve the connection between the client and the program?

1.2 Create MVC project

Then select Maven to run the project

2. Realize the “connection” between the client and the program

2.1 @RequestMapping

@RequestMapping can modify both classes and methods (Note that the slash cannot be omitted)

package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test") //Note that the slash cannot be omitted
public class TestController {

    //Client to server connection
    @RequestMapping("/sayhi")
    public String sayHi() {
        return "Hello Spring MVC";
    }
}

Start the project: Visit http://localhost:8080/test/sayhi The final effect is as follows:

?Question: Is @RequestMapping a post or a get request

We can test it through postman

By default, the annotation @RequestMapping is used to receive GET and POST requests.

In fact, we can specify @RequestMapping to receive either GET or POST:

1GET request (method = RequestMethod.GET):

@RestController
@RequestMapping("/test") //Note that the slash cannot be omitted
public class TestController {

    //Client to server connection
    @RequestMapping(value = "/sayhi", method = RequestMethod.GET)
    public String sayHi() {
        return "Hello Spring MVC";
    }
}

Only accept GET requests

2POST request (method = RequestMethod.POST):

@RestController
@RequestMapping("/test") //Note that the slash cannot be omitted
public class TestController {

    //Client to server connection
    @RequestMapping(value = "/sayhi", method = RequestMethod.POST)
    public String sayHi() {
        return "Hello Spring MVC";
    }
}

Only accept POST requests

2.2 @GetMapping and @PostMapping

  • @GetMapping: Implements HTTP connection, but only supports GET type requests
  • @PostMapping: Implements HTTP connections, but only supports POST type requests
@RestController
@RequestMapping("/test") //Note that the slash cannot be omitted
public class TestController {

    @GetMapping("/sayhi2")
    public String sayhi2() {
        return "Hello Spring MVC2";
    }

    @PostMapping("/sayhi3")
    public String sayhi3() {
        return "Hello Soring MVC3";
    }
}

3. Get parameters

3.1 Get a single parameter

@RestController
@RequestMapping("/test2")
public class TestController2 {
    @RequestMapping("/getname2")
    public String getName(String name) {
        return "Name: " + name;
    }

}

3.2 Get multiple parameters

@RestController
@RequestMapping("/test2")
public class TestController2 {

    @RequestMapping("/getname3")
    public String getName(String name, Integer age) {
        return "Name: " + name + " age: " + age;
    }

}

For the above-mentioned multi-parameter passing, it is ok to use multi-parameter passing when the parameters remain unchanged; if these attributes can be contained by an object, it is recommended to change to object

Using multi-parameter passing, if I add a password and need to change the method, etc. (the requirements change, the method also changes), it will not apply.

3.3 Transfer object

Create object (User class):

//Create object
@Data
public class User {
    private int id;
    private String name;
    private int age;
    private String password;
}

Pass object (UserController class):

package com.example.demo.controller;
import com.example.demo.model.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//pass object
@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/add")
    public User add(User user) {
        return user;
    }
}

3.4 Single table transfer parameters

//Transfer object
@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/add")
    public User add(User user) {
        return user;
    }
}

Open postman test:

3.5 Backend parameter renaming

Use @RequestParam to rename the parameter values of the front and back ends.

//Transfer object
@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/add")
    public User add(User user) {
        return user;
    }

    @RequestMapping("/name")
    public String name(@RequestParam("n") String name) {

        return name;
    }
}

3.5.1 Required parameter @RequestParam

Open the @RequestParam source code and we can see: There is a required which means necessary, and the default value is true, so if no parameters are passed, a 400 error will be reported

3.5.2 Do not pass parameters unless necessary

We can avoid errors if not passed by setting required=false in @RequestParam

@RequestMapping("/name")
public String name(@RequestParam(value = "n", required = false) String name) {
    return name;
}

3.6 @RequestBody Get JSON Object

//Transfer object
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * Get the JSON object of the front end
     * @param user
     * @return
     */
    @RequestMapping("/add_json")
    public User addByJson(@RequestBody User user) {
        return user;
    }
}

Open postman test:

3.7 Get the parameters in the URL @PathVariable

@PathVariable(“Get variable name”) – The name itself is the same as the parameter name and can be omitted

//Transfer object
@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/detail/{aid}")//{dynamic parameter variables} must be added when passing parameters
    public Integer detail(@PathVariable("aid") Integer aid) { //@PathVariable("Get variable name")
        return aid;
    }

    @RequestMapping("/detail2/{aid}/{name}")//{dynamic parameter variable} must be added when passing parameters
    //@PathVariable("Get variable name") - the name itself is the same as the parameter name and can be omitted
    public String detail2(@PathVariable("aid") Integer aid, @PathVariable String name) {
        return "aid: " + aid + " name: " + name;
    }
}

3.8 Upload files @RequestPart

Use the POST method to upload files; because the GET method has restrictions on the length of parameters and the file stream is very large, POST is used.

//Transfer object
@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/upload")
    public String upload(@RequestPart("myfile")MultipartFile file) throws IOException {
        String path = "E:\springboot_log\img.png";
        //save document
        file.transferTo(new File(path));
        return path;
    }
}

Each upload generates a new file for saving: 1 Generate a unique id (UUID) 2 Get the source file suffix name

//Transfer object
@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/upload")
    public String upload(@RequestPart("myfile")MultipartFile file) throws IOException {
        //1. Generate a unique ID --- UUID = Globally Unique ID -> MAC + Random Seed + Encryption Algorithm
        String name = UUID.randomUUID().toString().replace("-", "");
        //2. Get the suffix name of the source file
        name + = (file.getOriginalFilename().
                substring(file.getOriginalFilename().lastIndexOf(".")));//Equivalent to cat.png interception. The following
        String path = "E:\springboot_log\" + name;
        //save document
        file.transferTo(new File(path));
        return path;
    }
}

3.9 Get Cookie/Session/header

//Transfer object
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * Get Cookie
     * @param ck
     * @return
     */
    @RequestMapping("/getcookie")
    public String getCookie(@CookieValue(value = "java", required = false) String ck) {
        return ck;
    }
}

Simulate cookies:

3.9.2 @SessionAttribute Get Session

 /**
     * Get Session
     * @param name
     * @return
     */
    @RequestMapping("/getsession")
    public String getSession(@SessionAttribute(value = "session_key", required = false) String name){
        return name;
    }

3.9.3 @RequestHeader Get Header

 /**
     * Get Header
     * @param name
     * @return
     */
    @RequestMapping("/header")
    public String getHeader(@RequestHeader(value = "header_key", required = false) String name) {
        return name;
    }

4. Return data

4.1 Return to static page

@Controller
public class TestController3 {

    @RequestMapping("/index")
    public String index() {
        return "hello.html";
    }

}

Create the front-end page index.htm

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>hello, I'm hello page</h1>
</body>
</html>

4.2 @ResponseBody returns text/html

@Controller
@ResponseBody
public class TestController3 {

    @RequestMapping("/index")
    public String index() {
        return "hello.html";
    }

}

4.3 Request forwarding or request redirection (high frequency interview)

1forward: request forwarding 2redirect: request redirection

Not only can you return to the view, but you can also jump

Understanding of “forwarding” and “redirecting”: forwarding is forwarded by the server. Redirect is when the browser re-requests another address

Difference:

  • Request redirection redirects the request to a resource; request forwarding is server forwarding
  • The request redirection address changes, but the request forwarding address does not change.
  • Request redirection is the same as direct access to a new address. The original resource is not inaccessible; request forwarding is server forwarding, which may cause external resources to be inaccessible.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138446 people are learning the system