Detailed explanation of SpringMVC framework

1. What is Spring MVC?

The official description of Spring MVC is as follows:

Spring Web MVC is the original web framework built on the Servlet API, 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 often called "SpringMVC".

From the above definitions we can draw two key messages:

  1. Spring MVC is a web framework.
  2. Spring MVC is built on top of the Servlet API.

However, to really understand what is Spring MVC? We must first figure out what is MVC?

1.1 What is MVC

MVC is the abbreviation of 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.

  • Model (Model) is the part of the application that is used to process application data logic. Usually model objects are responsible for accessing data in the database.
  • View (view) is the part of the application that handles the display of data. Usually views are created from model data.
  • Controller (controller) is 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.

1.2 The relationship between MVC and Spring MVC

MVC is an idea, and Spring MVC is a concrete realization of the MVC idea. In general, Spring MVC is a Web framework that implements the MVC pattern and inherits the Servlet API.

2. The first SpringMVC program

(1) Create a SpringMVC project
Spring MVC can be created based on Spring Boot, that is, create a Spring Boot project and check the Spring Web module. For details, please refer to: SpringBoot project creation and operation

(2) Create a UserController class to realize the interconnection between the user and the Spring program. The specific implementation code is as follows:

@Controller
@ResponseBody
@RequestMapping("/user")    // 路由映射
public class UserController {
    
    

    @RequestMapping("/hi")
    public String sayHi() {
    
    
        return "<h1>hi, SpringMVC<h1>";
    }
}

(3) After this implementation, start the project, and when you visit the address: http://localhost:8080/user/hi, you can print the information of "hi, SpringMVC".

2.1 @RequestMapping annotation

@RequestMappingIt is one of the most commonly used annotations in Spring web applications, and it is used to register the route mapping of the interface.

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

2.2 @ResponseBody annotation

@ResponseBodyIf the returned value is a character , it will be converted to text/html, if the returned value is an object , it will be converted to application/jsonand returned to the front end.
@ResponseBodyIt can be used to modify methods or classes. The modified class means that all methods in the class will return htmlor json, not 视图.

2.3 get and post

@RequestMappingThe default is getthe method of request, if we want to receive POST request, we can explicitly specify @RequestMappingto receive post:

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

3 ways to write get request:

// 写法1
@RequestMapping("/index") 
// 写法2
@RequestMapping(value = "/index",method = RequestMethod.GET) 
// 写法3
@GetMapping("/index")

Two ways of writing post request:

// 写法1
@RequestMapping(value = "/index",method = RequestMethod.POST) 
// 写法2
@PostMapping("/index")

3. Get parameters

3.1 Passing a single parameter

In Spring MVC, parameters in the method can be directly used to pass parameters, such as the following code:

    @RequestMapping("/showname")
    public String showName(String name) {
    
    
        return "姓名:" + name;
    }

Simulate parameter passing in postman:
insert image description here

3.2 passing objects

Spring MVC can automatically implement the assignment of parameter objects, such as Person objects:
create Person classes:

@Data
public class Person {
    
    
    private int id;
    private String name;
    private String password;
}

Pass object code implementation:

    @RequestMapping("/person")
    public Object getPerson(Person person) {
    
    
        return person;
    }

Access and pass parameters through url:
insert image description here

3.3 Form parameter passing/passing multiple parameters (non-object)

@RequestMapping("/login")
    public String login(String username, String password) {
    
    
        return "用户名:" + username + " 密码:" + password;
    }

Access and pass parameters through url:
insert image description here

3.4 Backend parameter renaming (backend parameter mapping)

In some special cases, the parameter key passed by the front end may be inconsistent with the key received by our back end. For example, the front end passes a time to the back end, and the back end has a createtime field to receive it, so parameter reception will occur. If this is not the case, we can use @RequestParamto rename the parameter values ​​of the front and back ends.

    @RequestMapping("/time")
    public String getTime(@RequestParam("time") String createtime) {
    
    
        return createtime;
    }

Enter the url to pass parameters:
insert image description here

3.5 Setting parameters is optional

Take the above example, without passing parameters to time:
insert image description here

It will report 400, why is this happening?
Look at @RequestParamthe source code:
insert image description here
It is found that the parameters are mandatory by default. If you do not pass the parameters, an error will be reported. We @RequestParamcan required=falseset the parameters to be non-required by setting in the setting. The specific implementation is as follows:

    @RequestMapping("/time2")
    public String getTime2(@RequestParam(value = "time", required = false) String createtime) {
    
    
        return createtime;
    }

Access through url does not set parameters:
insert image description here

It was found that no error was reported, indicating that the settings are valid.

3.6 Receive JSON object

    @RequestMapping(value = "getjson", method = RequestMethod.POST)
    public Object getJson(@RequestBody Person person) {
    
    
        return person;
    }

Pass a json string through postman:
insert image description here

Received successfully.

3.7 Get the parameters in the URL

    @RequestMapping("/geturl/{name}/{password}")
    public String getUrl(@PathVariable String name, @PathVariable String password) {
    
    
        return "名称:" + name + " 密码:" + password;
    }

Get parameters by url:
insert image description here

3.8 Upload files

Create a application.ymlconfiguration file, save the configuration file path:

# 图片保存路径
myfile:
  path: E:/Data/

Backend implementation code:

    @Value("${myfile.path}")
    private String filePath;    // 从配置文件中获取文件上传路径

    @RequestMapping("/upfile")
    public boolean upFile(String name, @RequestPart("myfile") MultipartFile file) {
    
    
        boolean result = false;
        try {
    
    
            // 得到原文件的名称和后缀
            String fileType = file.getOriginalFilename();
            if (fileType != null) {
    
    
                fileType = fileType.substring(fileType.lastIndexOf("."));
            }
            // 文件保存的名称
            String fileName = UUID.randomUUID().toString() + fileType;
            file.transferTo(new File(filePath + fileName));
            result = true;
            log.info(name + ":图片上传成功!");
        } catch (IOException e) {
    
    
            log.error(name + ":图片上传失败!");
        }
        return result;
    }

Note : The log is used here, and it is necessary to add @Slf4jannotations to the class.

Upload the file with postman:
insert image description here
the file is successfully saved to the path:
insert image description here
insert image description here

The console also prints the success log:
insert image description here

3.9 Get Cookie/Session/header

Get Cookie method 1:

    @RequestMapping("/getck")
    public void getCookie(HttpServletRequest request) {
    
    
        Cookie[] cookies = request.getCookies();
        Arrays.stream(cookies).forEach(cookie -> {
    
    
            log.info(cookie.getName() + ":" + cookie.getValue());
        });
    }

Method 2:

    @RequestMapping("/getck2")
    public String getCookie2(@CookieValue("bite") String bite) {
    
    
        return bite;
    }

Get Header:

    @RequestMapping("/header")
    public String getHeader(@RequestHeader("User-Agent") String userAgent) {
    
    
        return userAgent;
    }

Get session method 1:

    @RequestMapping("/getsess")
    public String getSession(HttpServletRequest request) {
    
    
        String result = "";
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("SESSION_KEY") != null) {
    
    
            result = (String) session.getAttribute("SESSION_KEY");
        }
        return result;
    }

Method 2:

    @RequestMapping("/getsess2")
    public String getSession2(@SessionAttribute(required = false, name = "SESSION_KEY") String data) {
    
    
        return data;
    }

Set session:

    @RequestMapping("/setsess")
    public boolean setSession(HttpServletRequest request) {
    
    
        boolean result = false;
        try {
    
    
            HttpSession session = request.getSession(true);
            session.setAttribute("SESSION_KEY", "java");
            result = true;
        } catch (Exception e) {
    
    
            log.error("出现异常:" + e.getMessage());
        }
        return result;
    }

4. Return data

4.1 Return to static page

Create the front-end page index.html:
insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1 style="color: blue">hello, SpringMVC</h1>
</body>
</html>

Create the controller Controller:

@Controller
public class IndexController {
    
    
    @RequestMapping("/index")
    public Object index() {
    
    
        return "/index.html";
    }
}

Enter url in browser:
insert image description here

4.2 return JSON object

    @RequestMapping("/map")
    @ResponseBody
    public HashMap<String, String> mapJson() {
    
    
        HashMap<String, String> map = new HashMap<>();
        map.put("Java", "Java Value");
        map.put("MySQL", "MySQL Value");
        map.put("Redis", "Redis Value");
        return map;
    }

insert image description here

4.3 Request forwarding or request redirection

return can not only return a view, but also realize jump. There are two ways to jump:

  • forward: request forwarding;
  • redirect: Request redirection.

Comparison of the use of request forwarding and redirection:

// 请求重定向
@RequestMapping("/index1")
public String index(){
    
    
return "redirect:/index.html"; 
}
// 请求转发
@RequestMapping("/index2") 
public String index2(){
    
    
return "forward:/index.html"; 
}

Give examples of forward and redirect.
For example, if you tell your boyfriend/girlfriend that you want to eat ice cream, if he/she says yes, I will buy it for you, that is, forward请求转发if he/she says to buy it by himself, then yes redirect重定向.

The specific differences between forward and redirect are as follows:

  • Request redirection (redirect) relocates the request to the resource; request forwarding (forward) server-side forwarding.
  • The request redirection address changes, but the request forwarding address does not change.
  • Request redirection has the same effect as direct access to the new address, and there is no inaccessibility to the original external resources; request forwarding server-side forwarding may cause the original external resources to be inaccessible.

Guess you like

Origin blog.csdn.net/m0_59140023/article/details/125799039