SpringMVC学习笔记-11 RestFul风格

RestFul就是一个资源定位及资源操作的风格,既不是标准,也不是协议。基于这种风格的软件

可以更简洁、更有层次、更易于实现缓存机制。

传统操作互联网的方式是通过不同的参数来实现的,请求方式有post、get。对于不同的请求,我们需要使用不用的请求路径:

localhost:8080/item/query?id=1
localhost:8080/item/add
localhost:8080/item/update
localhost:8080/item/delete?id=1

而使用RestFul风格,我们可以保持请求路径不变,通过不同请求方式来调用不同的方法,实现不同的功能:

localhost:8080/item/1   GET请求
localhost:8080/item     POST请求
localhost:8080/item     PUT请求
localhost:8080/item/1   DELETE请求

先看看传统请求方式:uri?参数1=值1&参数2=值2...

package com.zzt.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RestFulController {
    @RequestMapping("/add")
    public String test(int a, int b, Model model){
        model.addAttribute("msg",a+b);
        return "test";
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${msg}
</body>
</html>

@PathVariable注解:用于实现RestFul风格

package com.zzt.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RestFulController {
    @RequestMapping("/add/{a}/{b}")
    public String test(@PathVariable int a,@PathVariable int b, Model model){
        model.addAttribute("msg",a+b);
        return "test";
    }
}

以上述代码为例,@PathVariable规定了 参数-int a 的值来自于uri中的 {a} ,参数-int b 的值来自于uri中的 {b}

此时用传统方式访问会出错,必须使用RestFul风格接收参数:

还记得我们之前提到过@RequestMapping可以设置请求方式吗?是的,再配合上这个属性就可以。(当然了,SpringMVC也提供了子注解,@GetMapping、@PostMapping等)。

    @GetMapping("/add/{a}/{b}")
    public String testGet(@PathVariable int a,@PathVariable int b, Model model){
        model.addAttribute("msg","get请求到达 : " + (a + b));
        return "test";
    }

    @PostMapping("/add/{a}/{b}")
    public String testPost(@PathVariable int a,@PathVariable int b, Model model){
        model.addAttribute("msg","post请求到达 : "+ (a+b));
        return "test";
    }
<body>
    <a href="add/1/2">get提交方式
    <form action="add/3/4" method="post">
        <input type="submit" value="提交">
    </form>
</body>

RestFul的优势:简洁(省去使用参数名的问题)、高效(缓存机制)、安全(因为请求不会携带参数名)

猜你喜欢

转载自blog.csdn.net/qq_39304630/article/details/113094840