SpringMVC program development

1. What is SpringMVC

Official description: https://docs.spring.io/springframework/docs/current/reference/html/web.html#spring-web

Spring Web MVC is an original Web framework based on Servlet API, which has been included in the spring framework from the beginning. Its official name "spring Web MVC" comes from the name of its source module (spring webmvc), but it is usually called "SpringMVC"

1.1 what is MVC

Model view controller is a design pattern that divides software (project) into three parts: model, view and controller

Model is the part of an application that deals with the data logic of the application. Usually, model objects are responsible for accessing data in the database

View is the part of an application that deals with data display. Usually, views are created based on model data

The controller is the part of the application that deals with user interaction. Usually, the controller is responsible for reading data from the view, controlling user input, and sending data to the model

1.2 what is the relationship between MVC and SpringMVC

MVC is a design idea, and SpringMVC is a concrete implementation framework

SpringMVC is a web framework based on MVC design pattern and Servlet API. At the same time, SpringMVC is a web module in Spring framework, which exists with the birth of Spring
Spring and SpringMVC have a long history, and Spring boot came after them

2. Spring MVC project creation

As long as we add a spring web (which uses Spring MVC) dependency based on the Spring Boot framework, the project at this time will become a Spring MVC project

We learn SpringMVC mainly from:

  1. Realize the mapping between users and programs (after the browser enters the URL address, the corresponding method can be matched in the program)
  2. The server needs to get the user's request parameters
  3. The server should return the result to the user

2.1 mapping of users and programs

2.1.1 method 1: use @RequestMapping("/xxx")

Create a UserController class to realize the interconnection between users and Spring programs:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ResponseBody // It refers to the data that returns a non static page
@RequestMapping("/user") //The RequestMapping above the class can be omitted
public class UserController {

    @RequestMapping("/sayhi")
    public String sayHi(){
        return "Hello World!";
    }
}

After startup: enter in the browser: http://localhost:8080/user/sayhi

tip:

@RequestMapping features:

  1. It can modify both classes (optional) and methods
  2. By default, both POST and GET requests are supported

You can use Postman to verify:
Postman download method: https://blog.csdn.net/chenbaifan/article/details/124850501?spm=1001.2014.3001.5501

@RequestMapping parameter extension (only certain types of request methods are supported, such as POST type request methods):

@RequestMapping(method = RequestMethod.POST,value = "/sayhi")


Only GET is supported:

@RequestMapping(method = RequestMethod.GET,value = "/sayhi")

2.1.2 method 2: use @PostMapping("/xxx")

Only POST request mode is supported
@PostMapping("/sayhi2")

2.1.3 method 3: use @GetMapping("/xxx")

Only GET request mode is supported
@GetMapping("/sayhi3")


Summary: @RequestMapping supports both GET and POST, but it can also set and specify GET or POST
@GetMapping only supports GET requests, and PostMapping only supports POST requests

2.2 get user request parameters

2.2.1 obtaining a single parameter

Object:


2.2.2 obtain multiple parameters

2.2.3 acquisition object

2.2.4 parameter rename (@requestparam annotation)

In some special cases, the parameter key passed by the front end can be different from the key received by our back end. For example, the front end passes a name to the back end, and the back end has a username field to receive it. In this case, the parameter cannot be received. If this happens, we can use @RequestParam to rename the parameter values of the front and back ends

FALSE:

Notes for using @RequestParam annotation:
If you add @RequestParam annotation to the parameter, the front end must pass this parameter, otherwise an error will be reported. If you want to solve this problem, you can add required = false to @RequestParam

Error reporting:

Modified:

2.2.5 get data in JSON format (@RequestBody)

To use the annotation @RequestBody:

Then use Postman simulation to send JSON data to the server:

2.2.6 get parameters (@PathVariable) from URL address

Note: I'm not talking about getting parameters from the parameter part of the URL address

2.2.7 uploading documents


One bad thing about this is that the storage place is written dead on this machine. If I want to save it to the server, other platforms will be difficult to do, so we can do this:

# Configuration file of development environment

# Path to save pictures
img:
  path: D:/Training/


# Configuration file of production environment

# Path to save pictures
img:
  path: /root/img/



# Set the running platform of the configuration file
spring:
  profiles:
    active: dev

Configure file settings on different operating platforms:

  1. Create a different profile:

    The naming rules for configuration files on different platforms: application platform.Yml (properties) must be named like this,
  1. Set the running profile in the main profile:

    After this operation, we only need to modify the corresponding environment of active, and we can store it at will without frequent modification

// Read the save path of the picture from the configuration file
    @Value("${img.path}")
    private String imgPath;

    @RequestMapping("/upimg")
    public boolean upImg(Integer uid, @RequestPart("img") MultipartFile file) {
        boolean result = false;
        String fileName = file.getOriginalFilename(); // Get the name of the original picture (xxx.png)
        fileName = fileName.substring(fileName.lastIndexOf(".")); // Get the picture suffix (png)
        fileName = UUID.randomUUID().toString() + fileName;
        // Save pictures to local directory
        try {
            file.transferTo(new File(imgPath + fileName));
            result = true;
        } catch (IOException e) {
            log.error("Failed to upload pictures:" + e.getMessage());
        }
        return result;
    }

2.2.8 get cookies

① Method for servlet to obtain cookies

@RequestMapping("/cookie")
    public void getCookie(HttpServletRequest request) {
        // Get all cookies
        Cookie[] cookies = request.getCookies();
        for (Cookie item : cookies) {
            log.info("Cookie Name: " + item.getName() +
                    " | Cookie Value: " + item.getValue());
        }
    }

Return result:

The disadvantage is that all cookie s are read out at one time

② Using @Cookie value annotation to read cookies

 @RequestMapping("/cookie2")
    public String getCookie2(@CookieValue("456") String cookie) {
        return "Cookie Value: " + cookie;
    }

2.2.9 get the information in the Header (request Header)

① Servlet mode

 @RequestMapping("/getua")
    public String getHead(HttpServletRequest request) {
        return "header: " + request.getHeader("User-Agent");
    }

② How to use annotation @RequestHeader

@RequestMapping("/getua2")
    public String getHead2(@RequestHeader("User-Agent") String userAgent) {
        return "header: " + userAgent;
    }


2.2.10 storage Session

Before setting (storing) Session:

After storing Session:

@RequestMapping("/setsess")
    public boolean setSession(HttpServletRequest request) {
        boolean result = false;
        // 1. Get HttpSession
        HttpSession session = request.getSession(true); // true= if there is no session, create a session
        // 2. Use setAtt to set the value
        session.setAttribute("userinfo", "Zhang San");
        result = true;
        return result;
    }

Save the SessionId and send it to the server for acquisition

2.2.11 get Session

① Servlet mode

@RequestMapping("/getsess")
    public String getSession(HttpServletRequest request) {
        String result = null;
        // 1. Get the HttpSession object
        HttpSession session = request.getSession(false); // false= if there is a session, use it. If not, no new session will be created
        // 2.getAtt gets Session information
        if (session != null && session.getAttribute("userinfo") != null) {
            result = (String) session.getAttribute("userinfo");
        }
        return "conversation: "+result;
    }

Save before retrieve:

② How to use annotation @SessionAttribute

@RequestMapping("/getsess2")
    public String getSession2(@SessionAttribute(value = "userinfo",
            required = false) String userinfo) {
        return "conversation:" + userinfo;
    }

2.3 return data

2.3.1 return to static page

Create a front page:


Note: I didn't add the @ResponseBody annotation. If I add it, I won't return to the static page:

2.3.2 return to a non static page


2.3.3 exercise: realize calculator function

Front end code

Backend code

result

2.3.4 simulate the login function

Front end code: send JSON

<!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">
    <script src="js/jquery-1.9.1.min.js"></script>
    <title>Document</title>
    <script>
        // ajax submission
        function mysub(){
            // 1. Air judgment
            var username = jQuery("#username");
            var password = jQuery("#password");
            if(jQuery.trim(username.val())==""){
                alert("Please enter the user name first!");
                username.focus(); // The cursor is reset to this element
                return;
            }
            if(jQuery.trim(password.val())==""){
                alert("Please enter the password first!");
                password.focus(); // The cursor is reset to this element
                return;
            }
            jQuery.ajax({
                url:"/login",
                type:"POST",
                contentType:"application/json",
                data:JSON.stringify({"username":username.val(),
                    "password":password.val()}),
                success:function(result){
                    alert(JSON.stringify(result));
                }
            });
        }
    </script>
</head>
<body>
<div style="text-align: center;">
    <h1>Sign in</h1>
    User:<input id="username">
    <br>
    password:<input id="password" type="password">
    <br>
    <input type="button" value=" Submit " onclick="mysub()" style="margin-top: 20px;margin-left: 50px;">
</div>
</body>
</html>

Back end code: receive JSON

 /**
     * Get json data of the front end
     *
     * @param userInfo
     * @return
     */
    @RequestMapping("/login")
    public HashMap<String, Object> login(@RequestBody UserInfo userInfo) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        int state = 200;
        int data = -1; // Equal to 1, login succeeds, otherwise login fails
        String msg = "unknown error";
        if (StringUtils.hasLength(userInfo.getUsername()) && StringUtils.hasLength(userInfo.getPassword())) {
            if (userInfo.getUsername().equals("admin") && userInfo.getPassword().equals("admin")) {
                data = 1;
                msg = "";
            } else {
                msg = "User name or password failed!";
            }
        } else { // Parameter is empty
            msg = "illegal parameter";
        }
        result.put("state", state);
        result.put("data", data);
        result.put("msg", msg);
        return result;
    }

2.3.5 request redirection and request forwarding

① Request Forward

Request forwarding is implemented by the server for users

Method 1:
The annotation should be changed to @Controller

Mode 2:

② Request Redirect

The redirected request occurs on the client (browser side), and the server side requests different users

Method 1:
Annotation should use @Controller

Mode 2:

3. Summary

3.1 combined annotation @RestController

@RestController = @Controller + @ResponseBody
Automatically identify whether to return to static page or non static page

3.2 difference between forward and redirect

In Java, there are two ways to realize jump: request forwarding and redirection, which are different:

  1. Different definitions
  2. Jump party is different
  3. Different data sharing
  4. The final URL address is different
  5. Different code implementation

1. Different definitions
Request forwarding: occurs inside the server program. When the server receives a client's request, it will first forward the request to the target address, and then forward the result returned by the target address to the client (Zhang San (client) borrows money from Li Si (server), but Li Si doesn't have that much money, so Li Si goes to Wang Wu to borrow money and gives it to Zhang San. In this process, Zhang San is equivalent to only borrowing money from Li Si.)
Request redirection: request redirection refers to that after the server receives the client's request, it gives the client a temporary response header, which contains the address of the request again (Zhang San (client) asks Li Si (server) to borrow money, but Li Si doesn't, so he tells Zhang San: "you go to Wang Wu to borrow money, I don't have money now", so Zhang San goes to Wang Wu to borrow money.)

2. Different jump methods
Request forwarding is the behavior of the server. The server sends the request instead of the client and returns the result to the client;
Requesting redirection is the behavior of the client

3. Different data sharing
Request forwarding is realized on the server side. In the whole execution process, the client only needs to send a request once, so the same request object and Response object are used in the whole interaction process, and the whole returned data is shared
The request redirection client sends two completely different requests, and the data in the two requests is different

4. The final URL address is different
Request forwarding is that the server makes the request on behalf of the client, and then returns the result to the client, so the URL address remains unchanged throughout the request process;
Request redirection is to tell the client to visit another address and make another request, so the address needs to jump

5. Different code implementation
Request forwarding

request redirections
To annotate with @Controller

3.3 IDEA hot deployment (hot loading)

This allows us to automatically detect that the code has been modified and restart the spring boot project during the process of modifying the code, so that we don't have to restart the project every time we want to view the effect
1. Add spring boot developer framework support

2. Enable automatic compilation of IDEA

3. Start the hot deployment in operation
This is the configuration method of the version of IDEA before 2021.2

Search: compiler.automake.allow.when.app.running

Version after IDEA 2021.2

4. Start the project and run it with debug instead of run
Maybe some people can click run

After this setting, you don't need to start frequently when you modify the code. If you detect a code change, you restart the project yourself

3.4 view more notes

Official API: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping

Tags: Android Interview Back-end Front-end

Posted by antoine on Fri, 05 Aug 2022 22:22:09 +0530