用Spring Intitlizr新建一个工程,Project SDK选择你的JDK8根目录,Dependicies勾选Spring Web
新建一个类,例如叫controller.RequestTest.java,编辑内容如下:

@RestController // 没加这个会直接404
public class RequestTest {
    @GetMapping("/car/{id}/owner/{username}")
    public Map<String,Object> getCar(
         @PathVariable("id") Integer id,
         @PathVariable("username") String name,
         @PathVariable Map<String,String> pv, // 获取所有PathVariable
         @RequestHeader("User-Agent") String userAgent,
         @RequestHeader Map<String,String> header, // 获取所有RequestHeader
         @RequestParam(value = "age", defaultValue = 0) Integer age, // 可以配置缺省时的默认值
         @RequestParam("inters") List<String> inters,
         @RequestParam Map<String,String> params // 获取所有RequestParam
    ){
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("name",name);
        map.put("userAgent",userAgent);
        map.put("age",age);
        map.put("inters",inters);
        return map; // 返回的Content-Type为application/json
    }

    @PostMapping("/save")
    public Map postMethod(@RequestBody String content){
        Map<String,Object> map = new HashMap<>();
        map.put("content",content);
        return map;
    }
}

resources里新建文件夹public,然后新建index.html,编辑内容如下

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>请求测试</title>
</head>
<body>
    <p><textarea id="textarea" style="height: 100px; width: 100%;" placeholder="请求的返回结果将显示在这里"></textarea></p>
    <p><a href="javascript: getRequest()">GET请求</a></p>
    <p><a href="javascript: postRequest()">POST请求</a></p>
    <script>
        function getRequest() {
            fetch('/car/123/owner/zhangsan?age=23&inters=football&inters=basketball').then(res=>res.json()).then(json=>{
                document.getElementById('textarea').value = JSON.stringify(json)
            })
        }
        function postRequest() {
            fetch('/save',{
                method: 'POST',
                body: 'body, string'
            }).then(res=>res.json()).then(json=>{
                document.getElementById('textarea').value = JSON.stringify(json)
            })
        }
    </script>
</body>
</html>

DELETE、PUT和POST差不多,只需更改请求的method即可,详情可看bilibili.com/video/BV19K4y1L7MT

运行项目即可进行测试

添加新评论