Spring MVC program development (three major functions)


1. What is Spring MVC?

(1) Built on top of Servlet (API).
(2) It is a web framework (HTTP)
(3) It comes from the Spring webMVC module.
Need to master:
(1) Connection function: connect the user (browser) with the Java program.
(2) The function of obtaining parameters: the user will bring some parameters when accessing, and find a way to obtain the parameters in the program.
(3) Function of outputting data: to return the result of program execution to the user.

1. MVC definition

The Model is the part of the application that handles application logic. Usually model objects are responsible for fetching 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. Typically the controller is responsible for reading data from the view, controlling user input, and sending data to the model.

2. The relationship between MVC and Spring MVC

MVC is an idea, and Spring MVC is a concrete realization of the MVC idea.

3. Creation method

(1) Create Spring MVC using Maven (obsolete).
(2) Use Spring Boot to add Spring Web modules (Spring MVC).
[Same as SpringBoot creation. ] 勾选的Spring Web框架其实就是Spring MVC框架。(https://blog.csdn.net/qq_45283185/article/details/129388891?spm=1001.2014.3001.5501)
insert image description here

2. The core functions of Spring MVC

1. Connection function

The browser obtains the front-end interface and the realization of the back-end program connection function

@RequestMapping("/xxx") can modify both classes and methods.
Performance: It supports both GET and POST requests.

	方式一:
    @RequestMapping(value = "/xxx",method = RequestMethod.POST)
    方式二:
    @PostMapping("/xxx")
    @GetMapping("/xxx")

The difference between get and post

The same:
The bottom layer of get request and post request is implemented based on TCP/IP protocol, and both can realize two-way interaction between client and server.
Difference:
The most essential difference between get and post is the difference in "contracts and specifications". In the specification, it is defined that get requests are used to obtain resources, that is, query operations, while post requests are used to transfer entity objects , so post will be used to add, modify and delete operations. According to the agreement, the parameter transmission of get and post is also different. When getting a request, the parameters are added to the url for parameter transmission, while the post is to write the request parameters into the request body for transmission.

Spring Boot Hot Deployment

Idea community version (2021.2) deployment:
(1) Add hot deployment framework;
insert image description here
(2) Set settings and new projects setup.
insert image description here
(3) Enable running hot deployment.
Both settings and new projects setup need to be checked.
insert image description here
Deployment of idea professional version:
(1) Introduce the devtools framework;
(2) Configure it through the startup file when it is running.
insert image description here
insert image description here

2. Get parameters

(1) Pass a single parameter

    //@RequestMapping(value = "/hi",method = RequestMethod.POST)
    //@PostMapping("/hi")
    @GetMapping("/hi")
    public String sayHi(String name) {
    
    
        return "hello,"+name;
    }

Note: Passing parameters in Spring Boot (Spring MVC) must be passed 包装类型, not the basic type.

(2) Transfer objects

Multiple parameters can be passed through the object.

    @GetMapping("/user")
    public String showUser(User user) {
    
    
        return user.toString();
    }

(3) Backend renaming: @RequestParam

required means that the parameter can be empty, and the default is true.

    @GetMapping("/time")
    public String showTime(@RequestParam(value = "t",required = false) String startTime,
                           @RequestParam("t2") String endTime) {
    
    
        return "开始时间:"+startTime + " | 结束时间:"+endTime;
    }

(4) Receive JSON object: @RequestBody

    @PostMapping("/json-user")
    public String showJSONUser(@RequestBody User user) {
    
    
        return user.toString();
    }

(5) Get the parameters in the URL: @PathVariable

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

(6) Upload file: @RequestPart

Fixed file save path:

    //上传文件
    @RequestMapping("/upfile")
    public String upFile(@RequestPart("myfile")MultipartFile file) throws IOException {
    
    
        String path = "D:\\Picture\\img.png";
        //保存文件
        file.transferTo(new File(path));
        return path;
    }

Variable file name:

    @RequestMapping("/myupfile")
    public String myUpFile(@RequestPart("myfile")MultipartFile file) {
    
    
        //根目录+唯一文件名+文件后缀
        String path = "D:\\Picture\\";
        path += UUID.randomUUID().toString().replace("-","");
        path += file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        return path;
    }

Use the PostMan construct to send the request.
insert image description here
insert image description here

(7) Get Cookie: @CookieValue

Method 1: Obtain through the previous servlet (all cookies are obtained)

//获取Cookie
    @RequestMapping("/getck")
    public String getCookie(HttpServletRequest req) {
    
    
        //servlet的方式是得到所有的cookie
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
    
    
            log.error(cookie.getName()+":"+cookie.getValue());
        }
        return "get cookie";
    }

Method 2: A single parameter can be obtained through @CookieValue

    //可以获得单个Cookie
    @RequestMapping("/getck2")
    public String getCookie2(@CookieValue("zhangsan") String value) {
    
    
        return "Cookie value:"+value;
    }

(8) Get the header: @RequestHeader

    //获取header
    @RequestMapping("/getua")
    public String getUA(@RequestHeader("User-Agent") String userAgent) {
    
    
        return userAgent;
    }

(9) Set and get Session: @SessionAttribute

Method 1: servlet method

    //设置和获取session
    @RequestMapping("/setsess")
    public String setSession(HttpServletRequest request) {
    
    
        HttpSession session = request.getSession();
        session.setAttribute("userinfo","userinfo");
        return "Set Session Success";
    }
    @RequestMapping("/getsess")
    public String getSession(HttpServletRequest request) {
    
    
        HttpSession session = request.getSession(false);
        if (session!=null && session.getAttribute("userinfo")!=null) {
    
    
            return (String)session.getAttribute("userinfo");
        } else {
    
    
            return "暂无 session 信息";
        }
    }

Method 2: @SessionAttribute

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

3. Output data

(1) Return to a static page

No need to add @ResponseBody

@Controller
public class SendController {
    
    
    @RequestMapping("/index")
    public String getIndex() {
    
    
        return "/index.html";
    }
}

insert image description here

(2) return text/html

@ResponseBody
insert image description here

(3) Return JSON object

    @RequestMapping("/json")
    public HashMap<String,String> jsonBean() {
    
    
        HashMap<String,String> map = new HashMap<>();
        map.put("java","new");
        map.put("mysql","数据库");
        map.put("cpp","++");
        return map;
    }

Capture packets through fiddler:
insert image description here

(4) Request forwarding or request redirection

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

The difference between forward (request forwarding) and redirect (request redirection)
:
1. Request redirection relocates the request to the resource; request forwarding server-side forwarding.
2. The request redirection address changes, but the request forwarding address does not change.
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.


Guess you like

Origin blog.csdn.net/qq_45283185/article/details/129420068