RestFull风格(SpringMVC学习笔记六)

定义:

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,仅仅是一种风格,基于这个风格设计的软件可以更加简洁、更有层次、更容易实现缓存机制。

常见于url中的方法和参数是用/分隔就是用RestFul风格,如果看到?***=***就是没有用这种风格优化的url。

功能:

    资源:互联网所有资源可以被抽象为资源 资源操作方式:POST(增)、DELETE(删)、PUT(改)、GET(查)

新增和更新如何区分?

通过@RequestMapping注解下的method枚举方法限定格式

method = RequestMethod.GET 如果格式不同会报405错

注意这里使用的是value,因为value一般作为请求路径,name一般作为方法名

@Controller
public class RestFullController {

    //http://localhost:8080/add             报500错误,a和b没有传递参数
    //http://localhost:8080/add?a=4&b=5     通过这样可以传递参数(老方式)
    //http://localhost:8080/add/4/5     restFull方式(分隔符用/代替,省去形参和=号,直接是实参)

    @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.DELETE)
    public String test(@PathVariable int a,@PathVariable String b, Model model){
        String result = a + b;
        model.addAttribute("msg1","结果为:"+result);
        return "test";
    }
}

 测试:

1、传统方式:

@Controller
public class RestFullController {
        
    //http://localhost:8080/add             报500错误,a和b没有传递参数
    //http://localhost:8080/add?a=4&b=5     通过这样可以传递参数(老方式)

    @RequestMapping("/add")
    public String test(int a,int b,Model model){
        int result = a + b;
        model.addAttribute("msg1","结果为:"+result);
        return "test";
    }

2、可以使用@PathVariable注解,让方法参数的值对应绑定到一个url模板变量上。

@Controller
public class RestFullController {

    //http://localhost:8080/add             报500错误,a和b没有传递参数
    //http://localhost:8080/add?a=4&b=5     通过这样可以传递参数(老方式)
    //http://localhost:8080/add/4/5     restFull方式(分隔符用/代替,省去形参和=号,直接是实参)

    @RequestMapping("/add/{a}/{b}")
    public String test(@PathVariable int a,@PathVariable int b, Model model){
        int result = a + b;
        model.addAttribute("msg1","结果为:"+result);
        return "test";
    }
}
经验分享 程序员 微信小程序 职场和发展