Create connection and use of Spring MVC

Table of contents

Foreword:

What is MVC?

1. Creation and connection of Spring MVC project:

1.1 create

 1.2 connection

2. Detailed analysis of @RequestMapping annotation usage:

2.1 Specify the request type:

2.1.1 Specify GET request

2.1.2 Specify POST request

3. Acquisition and transfer of parameters:

3.1 Passing a single parameter

3.2 passing objects

3.3 Pass multiple parameters/form parameters (non-object)

3.4 Backend parameter renaming:

Setting of optional parameters

3.5 @RequestBody receives JSON object

3.6 Get the basic parameters in the URL

3.7 Upload files

3.8 Get Cookie/Header/Session:

3.8.1 Obtaining Cookies

3.8.2 Get Header

3.8.3 Storage and Acquisition of Session

3.9 Get static pages

3.10 Request forwarding and request redirection:

the difference between the two



Foreword:

        Spring MVC, formerly known as "Spring Web MVC", is the original Web framework built on the Servlet API.

What is MVC?

        MVC, or Model View Controller, is a software architecture pattern that can divide a software system into three parts: model, view, and controller;

  • Model: the part that handles the application data logic;
  • View (view): The part of the application that handles data display;
  • Controller: The part of the application that handles user interaction. Typically the controller is responsible for reading data from the view, controlling user input, and sending data to the model.

        Therefore, it can be considered that Spring MVC is a Web framework that implements an MVC pattern and inherits the Servlet API. At the same time, the Spring MVC project can perceive the request entered by the user in the browser URL.

        Learning Spring MVC requires mastering its three main functions:

  1. Connection function: connect the browser and the java program, and call the corresponding Spring program by visiting an address;
  2. The function of obtaining parameters: obtain the parameters passed by the user in the program;
  3. The function of output data: return the execution result to the user;

1. Creation and connection of Spring MVC project:

1.1 Create:

        The creation of the Spring MVC project is the same as the creation of the Spring boot project, only need to add "Spring Web" when adding dependencies.

 1.2 Connection:

        The connection is both route mapping, and the @RequestMapping annotation is used in Spring MVC to implement route mapping with the browser URL. When accessing, you can directly access the path in the browser URL.

         


2. Detailed analysis of @RequestMapping annotation usage:

        The above is just a brief understanding of using this annotation to establish a connection. The following is an analysis of the specific usage rules of this annotation;

        @RequestMapping is used to register interface routing mapping. When a user visits a URL, the user's request is mapped to a method of a class in the program.

  •         The @RequestMapping annotation can modify [classes and methods], or directly modify [methods].
  •         @RequestMapping can specify the use of GET/POST requests;

2.1 Specify the request type:

2.1.1 Specify GET request:

        Ordinary @RequestMapping defaults to the GET request sent;

       △ Three ways of writing GET requests:

    // GET 请求的三种写法:
    // 第一种:
    @RequestMapping("/request")
    // 第二种:
    @RequestMapping(value = "/request", method = RequestMethod.GET)
    // 第三种:
    @GetMapping("/request")

2.1.2 Specify POST request:

       △ Two ways of writing POST request:

// POST 请求两种写法:
    // 第一种:
    @RequestMapping(value = "/request", method = RequestMethod.POST)
    // 第二种:
    @PostMapping("/request")

        


3. Acquisition and transfer of parameters:

3.1 Pass a single parameter:

        In Spring MVC, you can directly use the parameters in the method to pass parameters;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    // 传递参数
    @RequestMapping("/send")
    public Object sendParam(String username) {
        return "username: " + username;
    }
}

        Construct the request in postman:

3.2 Transfer objects:

         Spring MVC can automatically assign the passed parameters to the object;

@Component
@Data
public class Student {
    private int id;
    private String name;
    private int age;
}
@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    // 传递对象
    @RequestMapping("/send")
    public Object sendObject(Student student) {
        return "student 对象:" + student;
    }
}

        Construct the request in postman:

3.3 Pass multiple parameters/form parameters (non-object):

        When there are multiple parameters, the front-end and back-end use the parameter names to match the parameters, so the position of the parameters will not affect the result of the back-end getting the parameters.

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/send")
    public Object sendManyParas(String name, String pwd) {
        String user = name + " " + pwd;
        return user;
    }
}

3.4 Backend parameter renaming:

         When the parameters passed by the front-end to the back-end are different from the parameter names set in the back-end code, the back-end can match them through parameter renaming-parameter mapping.

        Use the @RequestParam annotation to rename parameters:

        In this example, the parameter passed by the front end is uid, but the corresponding renaming parameter set by the back end is: username;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/send")
    // 参数重命名
    public Object resetPara(@RequestParam(value = "uid") String username) {
        return "uid : " + username;
    }
}

Setting of optional parameters: 

 Think about it the other way around: Since the parameter name of the backend is: username, is it possible to pass a username in the frontend?

 An error 400 was reported, so it can be seen that it is not working. Because the @RequestParam annotation renaming means: the backend stipulates that the frontend must pass a parameter of "uid", which matches the username of the backend. Entering the annotation, you can see:

 So the error reported here is because we passed a username without setting required, which is not the "uid" specified by the backend. Then you can improve the flexibility of front-end parameter passing by setting the value of required, so that "uid" becomes an optional parameter:

 Note: This is only setting parameters that are not required to be passed, and does not mean that the passed parameters can be matched;


3.5 @RequestBody receives JSON object:

The backend receives the Json object:

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public Object sendJson(@RequestBody Student student) {
        return "Json 对象:" + student;
    }
}

The front end constructs the Json object:

 If you remove @RequestBody, you can get the Json object but cannot receive the value of the property in the Json object:


3.6 Obtain the basic parameters in the URL:

        Use @PathVariable to get URL inside? Previous parameters:

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    // 获取 URL 键值参数
    @PostMapping("/send/{name}/{password}")
    public Object getURLKV(@PathVariable String name, @PathVariable String password) {
        return "name:" + name + " password:" + password;
    }
}

 Notice:

  • @RequestParam: Get URL? parameters in the following parameters;
  • @PathVariable: Where to get the URL? The parameters of the previous basic part;


3.7 Upload files: 

        Upload files using the @RequestPart annotation;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/upload")
    public Object uploadFile(@RequestPart("myfile")MultipartFile file) {
        // 获取文件名
        String fileName = UUID.randomUUID() +
                file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 文件保存路径
        File savaFile = new File("D:\\MVCupload\\" + fileName);
        // 保存文件
        try {
            file.transferTo(savaFile);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

        When obtaining the file name, use UUID and substring to ensure that multiple uploads of the same file will not cause the same name to be overwritten;

        If you are worried that the uploaded file exceeds the limit size, you can set the maximum number of files that can be uploaded in the configuration file:


3.8 Get Cookie/Header/Session:

3.8.1 Get cookies:

        Use the @CookieValue annotation to get cookies:

        Here's the method used to get a single cookie:

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/cookie")
    public Object getCookie(@CookieValue(value = "load", required = false) String load) {
        return "load:" + load;
    }
}

         If you want to get all cookies, you can use the traditional method to get them with the request object:

    @RequestMapping("/cookie")
    public Object getCookies(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        return cookies;
    }

3.8.2 Get Header:

        Use the @RequestHeader annotation to get the information in the Header:

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/header")
    public Object getHeader(@RequestHeader("User-Agent") String userAgent) {
        return "User-Agent:" + userAgent;
    }
}

3.8.3 Storage and acquisition of Session:

         First store the Session according to the HttpServletRequest  , and then obtain the Session through the @SessionAttribute annotation:

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    // 存储 Session
    @RequestMapping("/setSession")
    public void setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_KEY,"张三");
    }
    private static final String SESSION_KEY = "USER_SESSION";
    // 获取 Session
    @RequestMapping("/getSession")  
    public Object getSession(@SessionAttribute(SESSION_KEY) String name) {
        return "session_name:" + name;
    }
}

         A more concise way to get session:

    @RequestMapping("/session")
    public Object getSession(@SessionAttribute(value = "session", required = false) String session) {
        return session;
    }

3.9 Get static pages:

         First create an index.html file in the static directory:

         

        When obtaining this static page, be sure to pay attention to return "/index.html" , the function of this / slash is to find the static page index.html from the root directory, because it is directly placed in the static directory; 

        If this file is placed in the index directory under the static directory, it should be written like this: return "index.html"  , and the path in the URL is: http://localhost:8080/index/index.html

@RequestMapping("/test")
public class TestController {
    @RequestMapping("/index")
    public Object getIndex() {
        return "/index.html";
    }
}


3.10 Request forwarding and request redirection:

The difference between the two:

  1. The definitions are different:
       Request forwarding (Forward) : occurs inside the server program. When the server receives a request from the client, it will forward the request to the final destination address, and then return the result of the destination address to the client.
       Request redirection (Redirect): After the server receives the client's request, it will return a temporary response header to the client. This temporary response header records the URL address that the client needs to send the request again, and the client receives this again. After receiving the new address, resend the request to the new address.
            Image example: the boss asks the second child to borrow money, the second child has no money now, but the second child goes to the third child to borrow money and then lends it to the boss, this process is "request forwarding", if the second child just asks the boss to borrow money from the third child , this process is "request redirection".
  2. The requester is different:
            request forwarding mainly means that the server is completing tasks, while request redirection mainly means that the client and server are constantly interacting to complete tasks.
  3. Data sharing is different:
            in the entire execution process of request forwarding, the server completes all interactions with the same Request and Response objects, so the request and returned data are shared; while request redirection requests and returned data each time are disagree.
  4. The final URL address is different:
    request forwarding means that the server acts as a proxy request to find the destination address, and finally brings back the result, so the final URL address remains unchanged; while request redirection URL changes every time it interacts.
  5. The implementation code is different , the specific code is as follows.
@Controller
@RequestMapping("/test")
public class TestController {
    // 请求转发
    @RequestMapping("/forward")
    public Object forward() {
        return "forward:/index.html";
    }
}

 The final address of the request forwarding is still the address of the original request:

@Controller
@RequestMapping("/test")
public class TestController {
    // 请求重定向
    @RequestMapping("/redirect")
    public Object redirect() {
        return "redirect:/index.html";
    }
}

 The final address of the request redirection is the redirected address:

Note: When requesting forwarding, if the resource and the forwarded page are not in the same directory, the external resource will be inaccessible, but the redirect can be accessed

Guess you like

Origin blog.csdn.net/m0_65190367/article/details/130992855