SpringBoot开发的接口实现RESTFull的设计风格

一、RESTFull概念解读:

一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

传统的接口地址风格为:http://127.0.0.1:8080/allUser?id=2&age=20&name=winson,比较繁琐,而RESTFull接口的访问简单化了:http://127.0.0.1:8080/allUser/2/20/winson,省去了问号、属性名、&号。

二、开发的接口格式:使用@PathVariable注解接收http请求的参数id。

@GetMapping("/allUser/{id}")
    public User getUser(@PathVariable("id") String id) {
        return userService.getUserById(id);
    }

完整代码为:

package cn.com.winson.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import cn.com.winson.domin.User;
import cn.com.winson.service.UserService;

@RestController
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/allUser/{id}")
    public User getUser(@PathVariable("id") String id) {
        return userService.getUserById(id);
    }
}
View Code

三、运行程序,访问结果为:

总结:

RESTFull就是一种接口风格,没有使用其他技术。只是在接口中使用了一个@PathVariable注解就可以实现。

原文地址:https://www.cnblogs.com/elnimo/p/10085422.html