Basic knowledge of Spring MVC

Create a SpringMVC project

The SpringMVC project is actually similar to the SpingBoot project, and only one more SpringWeb project has been introduced.

You can read this blog and create a SpringMVC project --Create a project blog

 What is Spring MVC

I believe everyone knows what Spring is. What is MVC? MVC is the abbreviation of Model View Controller. Let's look at these three words separately Model (model), View (view), and Controller (controller)

The picture searched on Baidu is very vivid

MVC is a form, and SpringMVC is a specific implementation, just like the specific implementation of the jvm method area is the permanent generation and metaspace, that is to say, SpringMVC implements the MVC software engineering architecture pattern

By the way, SpringMVC is still stuffed with the servelet API

connect

It is to connect with the browser. When I was learning serverlet, I was dying to report 404 403 500 errors. I really vomited

Let's create a class UserController under the demo directory

Then write a bunch of code like this

package com.example.demo;

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

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("sayhi")
    @ResponseBody
    public Object Sayhi(){
        return "hi!SpringMVC";
    }
}

Then visit this in your browser

127.0.0.1 is a fixed intranet address

8080 is the port number defined in the configuration file

user and sayhi are...

operation result:

 

@Controller means that this class is a controller, which should be loaded and registered when Spring starts, pay attention! Other annotations with five major annotations will report errors!

@RequestMapping("/user") means that this class can be accessed in "/user" (setting routing)

@RequestMapping("/sayhi") Access this method in the class (the class in the previous @RequestMapping) (can be understood as a multi-level directory) @RequestMapping on the class can be omitted, but not on the method

@ResponseBody If there is no such annotation, an error will still be reported, and the type returned by return will be recognized in the form of View. This annotation can tell the compiler that the returned object is not a view

@RestController annotation is equivalent to @Controller + @ResponseBody

That is to say, this code can also be written like this

        package com.example.demo;

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

@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("sayhi")
    public Object Sayhi(){
        return "hi!SpringMVC";
    }
}

@R equestMapping annotation and @GETMapping

In addition to the above considerations,

@R equestMapping supports a variety of requests, like our common Get, Post, Put... all support, we specify that it can only be accessed with a certain request by controlling its parameter "method")

 (Remember to add the "/user" parameter) Add such a parameter after the method (RequestMethod. is the default request type). If we specify that it can only be accessed by Post.. Then write like this 

Another way of writing is @GETMapping("") (specifying Post is @POSTMapping) which is equivalent to @RequestMapping(value="",mathod="")

@GETMapping only needs to write a value parameter

But note that @RequestMapping can annotate classes, method annotations @GETMapping can only annotate methods

 Pass (get) a single parameter

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping(value="/user",method = RequestMethod.POST)
public class UserController {
    @PostMapping("/sayhi")
    @ResponseBody
    public void get(String name){
        System.out.println("传递的参数"+name);
    }
}

Build a Post request with postman

 

 (os: When I enter this key-value, the url expands by itself)

operation result

 

 You may think (I think anyway) that there is no method or annotation, why just receive it directly, and Servelet uses this API and that dependent.....

Right here, the method name can be customized (anyway, the access route is also commented above)  Srting name Just make sure that the variable name is consistent with the key in the request

Pass (get) multiple parameters 

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping(value="/user",method = RequestMethod.POST)
public class UserController {
    @PostMapping("/sayhi")
    @ResponseBody
    public void get(String name,int age){
        System.out.println("name="+name);
        System.out.println("age="+age);
    }
}

build request

 

It is consistent with the passing of a single parameter, but this method inputs multiple parameters

Parameter Mapping (Renaming)

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping(value="/user",method = RequestMethod.POST)
public class UserController {
    @PostMapping("/sayhi")
    @ResponseBody
    public void get(@RequestParam("myname")String name,@RequestParam("myage")int age){
        System.out.println("name="+name);
        System.out.println("age="+age);
    }
}

Just add a @RequestParam annotation in front of the method parameter and put the name you want to change it into. 

One thing to note is that if this annotation is not added, the program will return null if it does not receive the corresponding parameters, and no error will be reported.

If this parameter is added, it becomes a required parameter, and if it is not received, an error will be reported

@RequestParame("myname",requird=false)

Adding a required parameter will not become a required parameter

 pass (get) object

First build an object yourself

package com.example.demo;

import lombok.Data;

@Data
public class Student {
    String name;
    int age;


    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

@Data is equivalent to giving a Getter (the transfer of the object needs to write the Getter) and no error will be reported

@Override is not mandatory, I rewritten it for printing convenience

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping(value="/user",method = RequestMethod.POST)
public class UserController {
    @PostMapping("/sayhi")
    @ResponseBody
    public void get(Student student){
        System.out.println(student);
    }
}

build request

 Defining a class is equivalent to the name of the variable in a single parameter passing is consistent with the name of the key, but what is required here is that the attributes in the class are consistent with the key in the request

Pass (get) the form form

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Controller
@RequestMapping(value="/user",method = RequestMethod.POST)
public class UserController {
    @PostMapping("/sayhi")
    @ResponseBody
    public void get(@RequestBody Student student){
        System.out.println(student);
    }
}

 

 Add @RequestBody in front of the parameter, otherwise it will not be received

@RequestBody : Function: Mainly used to receive the data in the json string passed from the front end to the back end (the data in the request body)

Get the parameters in the URL

@Controller
@RequestMapping(value="/user",method = RequestMethod.POST)
public class UserController {
    @PostMapping("/sayhi/{name}/{age}")
    @ResponseBody
    public void get(@PathVariable String name, @PathVariable int age){
        System.out.println("name="+name);
        System.out.println("age="+age);
    }
}

build request

 

 The parameters in this /{} should be consistent with the parameter names in the method

This /{} represents the correspondence with the data in the url

Also add @PathVariable before each parameter

Indicates that this parameter receives a path value

get file 

@Controller
@RequestMapping(value="/user")
public class UserController {
    @RequestMapping("/file")
    @ResponseBody
    public String File(@RequestPart("myfile") MultipartFile file) throws IOException {
        file.transferTo(new File("img.png"));
        return "success";
    }

}

Annotate the MultipartFile object with @RequestPart 

 

 These two must be consistent

 

Get Cookie/Header

Cookie

@Controller
@RequestMapping(value="/user",method = RequestMethod.POST)
public class UserController {
    @PostMapping("/sayhi")
    @ResponseBody
    public void get(@CookieValue("bug") String cookie){
        System.out.println(cookie);
    }
}

 Annotate with @CookieValue Note that the following parameters should correspond to the prefix in Value

Header

@Controller
@RequestMapping(value="/user",method = RequestMethod.POST)
public class UserController {
    @PostMapping("/sayhi")
    @ResponseBody
    public void get(@RequestHeader("header") String header){
        System.out.println(header);
    }
}

 

The difference is that the Header is annotated with @RequestHeader

Then the following parameters correspond to KEY 

 

return html static page

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/get")
    public Object Return(){
        return "index.html";
    }
}

 

In fact, these @RequestMapping annotations can be omitted

Anyway, it can only be accessed in this way, directly a / file name 

returns a JSON object

@Controller
@RequestMapping("/user")
@ResponseBody
public class UserController {
    @RequestMapping("/get")
    public HashMap<String,Integer> getJson(){
        HashMap<String,Integer> map = new HashMap<>();
        map.put("张三",18);
        map.put("李四",19);
        return map;
    }
}

 

 tips:@RestController == @Controller+@ResponseBody

Request Forwarding & Request Redirection

@Controller
@RequestMapping(value="/user")
public class UserController {
    @RequestMapping("/forward")
    public String index1(){
        //请求转发
        return "forward:/index.html";
    }
    @RequestMapping("/redirect")
    public String index3(){
        //请求重定向
        return "redirect:/index.html";
    }
}

Note: @ResponseBody is useless here because it returns a View, otherwise it returns a string

The difference between forwarding and redirection is:

Forward

 redirect

Both of them turned out to be

But the redirected URL becomes

 

 

 

Guess you like

Origin blog.csdn.net/chara9885/article/details/130649104