Quick start SpringMVC learning

Table of contents

Spring MVC definition

MVC definition

Create a SpringMVC project

SpringMVC master function

1. Connection function

@RequestMapping (request mapping)

@GetMapping and @PostMapping

2. Get parameter function

pass single parameter/multiple parameters

important point:

@RequestParam (front-end and back-end parameter mapping)

Front-end and back-end parameter mapping

@RequestParam feature: setting parameters must be passed

 @RequestParam feature: set parameters as optional

transfer object 

@RequestBody receives JSON object

Get the parameter @PathVariable in the URL

Upload file @RequestPart

Get Cookie/Session/header

@CookieValue

@RequestHeader

@SessionAttribute

3. Return data function

Return to static page

Request redirection and request forwarding

The difference between request redirection and request forwarding

request forwarding

request redirection

front-end interaction

Use the form form to pass parameters

Use ajax to pass parameters to the backend


Spring MVC definition

SpringMVC is a web framework built on the Servlet API.

MVC definition

MVC is the abbreviation of Model, View and Controller, representing model, view and controller respectively.

  • Controller (controller) is the part of the application that handles user interaction. Usually the controller is responsible for reading data from the view,
        Control user input and send data to the model.
  • Model (Model) is the part of the application that is used to process application data logic. Usually the model object is responsible for accessing data in the database
  • A View is the part of an application that handles the display of data. Usually views are created from model data

Create a SpringMVC project

The SpringMVC project is created based on the foundation created by the SpringBoot project

When creating a SpringBoot project, check SpringWeb to create a SpringMVC project.

SpringMVC master function

1. Connection function: the user (browser) establishes a connection with the project program, that is, enters a URL to access the results of our program code

2. Obtaining parameter function: the background program can obtain the parameters input by the user (transferred by the front end)

3. Output data function: the background program receives the data entered by the user, and after processing the business logic, it needs to pass the processed data result to the front end and return it to the user.

1. Connection function

        The connection function needs to establish routing mapping to realize the connection between the user and the program. Here you need to use the annotation @RequestMapping (request mapping)

@RequestMapping (request mapping)

This annotation can implement routing mapping, and access our project program by entering a URL.

 The smallest request unit of @RequestMapping is a method.

        Therefore, using this annotation must be added to the method. At the same time, this annotation can also be added to the class as the first-level directory, and added to the method as the second-level directory (the method can also be directly modified).

        Usually, when users get the results of our program, they also need to use two annotations to cooperate with @RequestMapping. These two annotations are:

@ResponseBody (tell the program to return data instead of the front-end page) 

@Controller (to load the current class when the framework starts, only the loaded class can be accessed by the user)

These two annotations can also be replaced by a combined annotation @RestController

  @RestController = @ResponseBody + @Controller

The sample code is as follows:

@RequestMapping("/hello") // 一级路由目录
@Controller // 让框架启动的时候加载当前类
@ResponseBody //告诉程序返回的是数据而非页面
public class UrlSpringMVC {

    @RequestMapping("/hi") // 二级路由目录
    public String func(){
        return "你好,SpringMVC";
    }
}

@GetMapping and @PostMapping

        The @RequestMapping annotation can support both Get requests and Post requests. By default, only Get requests are supported.

        If you need to specify that only Get requests or Post requests are supported, you can modify the method in @RequestMapping to define that only Get requests or Post requests are supported.

The modification method is as follows:

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

        Method 2: You can use @GetMapping or @PostMapping directly

Note: @GetMapping and @PostMapping need to be loaded directly on the method

@GetMapping("/hi")

@PostMapping("/hi")

2. Get parameter function

pass single parameter/multiple parameters

The user returns parameters from the front end to the back end, and the back end receives the data input by the user for processing

@RequestMapping("/hello") // 一级路由目录
@Controller // 让框架加载的时候启动当前类
@ResponseBody //告诉程序返回的是数据而非页面

public class UrlSpringMVC {

    @GetMapping("/hi")
    public String func(String name,String password){
        return "名字:" + name + "  密码:"+ password;
    }
}

important point:

1) The parameters received by the backend are matched according to the parameter name, which has nothing to do with the parameter order

Examples are as follows:

 2) When the back-end receives the parameters returned by the front-end, it needs to use the wrapper class to receive them, so as to prevent the front-end from not receiving the parameters and causing program exceptions.

(The important thing is said three times: use the wrapper class to pass parameters, use the wrapper class to pass parameters, use the wrapper class to pass parameters)

The sample code is as follows:

@RequestMapping("/hello") // 一级路由目录
@Controller // 让框架加载的时候启动当前类
@ResponseBody //告诉程序返回的是数据而非页面

public class UrlSpringMVC {

    @GetMapping("/hi")
    public String func(int  number){

        return  "前端传入参数:"+number;
    }
}

Case 1: The front end returns parameters normally, and the back end uses basic data types to receive the passed parameters

Case 2: When the front end does not pass in parameters, the back end uses basic data types to receive the passed parameters. At this time, the back end does not receive the parameters and a program exception occurs

 

 Solution : The backend receives parameters using a wrapper class to receive parameters to prevent the front end from passing in parameters.

                When the front end does not pass in parameters, the back end can output the result as null , and the program will not be abnormal

Corrected code to run:

@GetMapping("/hi")
    public String func(Integer  number){  //使用包装类来接收传入参数
       return  "前端传入参数:"+number;
    }

   

 

@RequestParam (front-end and back-end parameter mapping)

Front-end and back-end parameter mapping

        Sometimes the key value of the parameter passed in the previous section is different from the key value of the parameter received by the backend. For example, the frontend passes in two digital key values ​​using number1 and number2, while the key values ​​received by the backend are number3 and number4. When the parameter cannot be received, it will happen.

        At this point, you need to use the annotation @RequestParam for front-end and back-end parameter mapping 

 @RequestMapping("/m1")

    //前端传入参数key值是number1、number2,后端接收参数key值是number3和number4
    //使用@RequestParam 将number1映射成number3,将number2映射成number4

     public String test(@RequestParam("number1") Integer number3,
                       @RequestParam("number2") Integer number4){

          return "后端接收参数number3为:"+ number3 +", number4:"+ number4;

    }

    }

 

@RequestParam feature: setting parameters must be passed

 Looking at the source code, we can see that @RequestParam sets parameters by default as required. If the front end does not pass parameters, a program exception will occur.

 @RequestParam feature: set parameters as optional

        The parameters we pass in the project are not necessary to pass parameters. At this time, we need to modify the @RequestParam attribute, and change required to false to set the parameter as non-essential.

  @RequestMapping("/m1")
    public String test(@RequestParam(value="number1",required = false) Integer number3,
                   @RequestParam(value = "number2",required = false) Integer number4){

        return "后端接收参数number3为:"+ number3 +", number4:"+ number4;

    }

transfer object 

define object code

import lombok.Data;

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

Backend return parameter code

  @RequestMapping("/n1")
    public String people(Student student){
        return "id号:"+ student.getId()+" 姓名:"
            + student.getName()+" 密码:"+ student.getPassword();
    }

@RequestBody receives JSON object

@RequestBody can be used to receive the JSON object from the front end, the usage is similar to passing the object, the example is as follows:

Note: @RequestBody must require a post mapping

@Data
public class Student {
    private int id;
    private String name;
    private String password;
}
  @PostMapping("/n11")  //@RequestBody 必须要求是post映射
    public String method(@RequestBody Student student){
        return student.toString();
    }

Get the parameter @PathVariable in the URL

Use @PathVariable to get parameters from URL more concisely

 @RequestMapping("/n2/{username}/{password}")
    public String people1(@PathVariable String username,@PathVariable String password){
        return username + " : "+ password ;
    }

 Where {username}{password} is a parameter that must be passed , otherwise 404 will appear when accessing

Upload file @RequestPart

 @RequestMapping("/upFile")
    public String myupFile(@RequestPart("file")MultipartFile file) throws IOException {
        //根目录
        String path = "F:\\upFile\\";
        //根目录 + [唯一的文件名]
        path += UUID.randomUUID().toString().replace("-","");
        // 根目录 + [唯一的文件名] + 【文件的后缀】 ex:.png
        path += file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        file.transferTo(new File(path));
        return path;
    }

 

Get Cookie/Session/header

@CookieValue

To get cookies, you need to use this annotation @CookieValue

@RequestMapping("/cookie")
    public String getMyCookie(@CookieValue("cookies") String getCookie){
        return "Cookie :" + getCookie;
    }

@RequestHeader

Use this annotation to get Header information

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

@SessionAttribute

Store Session

@RequestMapping("/cunSession")
    public String setsess(HttpServletRequest request) {
      // 获取 HttpSession 对象,参数设置为 true 表示如果没有 session 对象就创建⼀个 session

        HttpSession session = request.getSession(true);
        if(session!=null){
            session.setAttribute("username","SpringMVC"); //SpringMVC为创建的Session
        }
        return "session 存储成功";
    }

A concise way to get session, directly use @SessionAttribute

   @RequestMapping("/Session")
    public String getSession(@SessionAttribute(value = "username" ,required = false) 
                                String userSession){
                        return "获取Session:" + userSession;
    }

 

3. Return data function

Return to static page

        In the first function: the connection function has explained the function of the annotation about @ResponseBody : telling the program to return data instead of the front-end page

        Using @ResponseBody returns a data instead of a front-end page. If this annotation is not used, a front-end page is returned

Create the test.html front-end file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    这是前端页面HTML !!!
</body>
</html>

Use @ResponseBody effect:

@RequestMapping("/yemian")
    @ResponseBody //告诉程序返回的是数据而非页面
    public String func(){
        return "test.html";
    }

Without @ResponseBody effect:

@RequestMapping("/yemian")

    public String func(){
        return "test.html";
    }

Request redirection and request forwarding

Request redirection: forward

Request forwarding: redirect

The understanding of "forwarding" and "redirecting": the less official content in China, the bigger the problem, and the same is true for "forwarding" and "redirecting": the fewer words, the greater the responsibility. Forwarding is done by the server, and redirection is to make the browser request another address again.

The difference between request redirection and request forwarding

1. Request forwarding: Request forwarding means that the client sends a request to the server, and the server forwards the request, and the execution object is the server

2. Request redirection: Request redirection is when the client sends a request to the server, the server tells the client a new resource address, and the client completes it, and the execution object is the client

3. 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.

request forwarding

 @RequestMapping("/re")
    public String func1(){
        return "redirect:test.html";
    }

Request forwarding means that the client asks the server to forward the address, and the address does not change

request redirection

  @RequestMapping("/fo")
    public String func2(){
        return "forward:test.html";
    }

Request redirection means that the client resends a new address, and the address has changed

front-end interaction

Use the form form to pass parameters

Example: Implementing a calculator function

Front-end code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>计算器</title>
</head>
<body>
    <form action="http://localhost:8080/hello/jishuang">
        <h1>计算器</h1>
        数字1:&nbsp;&nbsp;<input name="num1" type="text"><br>
        数字2:&nbsp;&nbsp;<input name="num2" type="text"><br>
        <input type="submit" value=" 点击相加 ">
        </form>
    
</body>
</html>

Backend code:

 @RequestMapping("/jishuang")
  @RestController
    public String func(Integer num1,Integer num2){

            if(num1 == null || num2 == null){
                   return "数据不可为空,请重新输入<a href='javascript:history.go(-1);'>返回</a>";
            }else{

                 return "<h2>计算结果为:"+(num1+num2)+"</h2><a href='javascript:history.go(-1);'>返回</a>";
            }
    }

 

Guess you like

Origin blog.csdn.net/qq_73471456/article/details/130967077
Recommended