SpringBoot 处理HTTP 请求的方法

RequestMapping 的 method 类型有 GET、HEAD、POST、PATCH、DELETE、OPTIONS、TRACE。可以通过这些 method 来处理前端用不同方法提交的数据

GET

GET 方法是最常用的方法。用 GET 方法可以获取资源。比如,以下代码用 GET 方法获取所有图书

    @RequestMapping("/select")
    @ResponseBody
    public List<Bookshelf> select1() {
        return bookService.selectBook();
    }

等同于

    @GetMapping("/select")
    @ResponseBody
    public List<Bookshelf> select2() {
        return bookService.selectBook();
    }

DELETE

如果需要删除一个数据,根据 Restful 风格则需要使用 DELETE 方法。在使用 DELETE 方法删除资源的时候,要注意判断是否成功,因为 返回的是 VOID 类型。

一般有以下三个方法判断。

  • 使用 try catch exception :如果不发生异常,则默认为成功,但这样并不好。
  • 通过存储过程返回值来判断是否正确执行:如果执行成功,则返回 1 或 大于 0 的值;如果执行失败,则返回 0。
  • 在执行 DELETE 方法前首先查询是否有数据:在执行 DELETE 方法后返回值是 0,所以,一般先查询一下是否有数据

后端 :

    @DeleteMapping("/delete")
    //(同上)@RequestMapping(value = "/delete", method = RequestMethod.DELETE) 
    @ResponseBody
    public int delete2(@RequestParam(value = "id", required = true) int id) {
        return bookService.deleteById(id);
    }

 前端 AJAX 请求:

<body>
    <input type="text" id="deleteTest">
    <button id="delete2">delete2</button>
</body>
<script>
    $("#delete2").on('click', function () {
        const deleteTest = $("#deleteTest").val();
        $.ajax({
            url: "http://localhost:8080/delete",
            type: 'DELETE',
            dataType: 'json',
            data: {'_method': 'DELETE', 'id': deleteTest},
            success: function (data) {
                console.log(data)
            },
            error: function (e) {
            }
        });
    });
</script>

POST

如果需要添加对象,那一般会使用 POST 的方法传递一个 Model 对象

GET 和 POST 的区别:

  1. GET 在浏览器中可以回退,而 POST 访问同一个地址时也是再次提交请求。
  2. GET 请求会被浏览器主动缓存,而 POST 则不会。
  3. GET 中的参数会被完整地保留在浏览器历史记录里,而 POST 中的参数则不会被保留。
  4. GET 只能进行 URL 编码,而 POST 支持多种编码方式。
  5. GET 只接收ASCII字符,而POST没有限制。
  6. GET 的安全性相比 POST 低,因为参数直接暴露在 URL 上,所以不能用它递敏感信息。
  7. GET 的参数是通过 URL 传递的,而 POST 的参数是放在request body中的。但是,以上这些都不是绝对的,比如 POST 也可以通过 URL 路径提交参数。

后端:

    @PostMapping("/add")
//   (同上) @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public int add(@ModelAttribute("bookshelf") Bookshelf bookshelf) {
        return bookService.add(bookshelf);
    }

前端 form 表单

<body>
    <form action="http://localhost:8080/add" method="post">
        id:<input type="text" name="bkno">
        输入1:<input type="text" name="bklocation">
        输入2:<input type="text" name="bcategory">
        <input type="submit" value="提交">
    </form>
</body>

PUT

如果对象需要更新,则用PUT方法发送请求。

后端:

    @PutMapping("/update")
//   (同上) @RequestMapping(value = "/update" ,method = RequestMethod.PUT)
    @ResponseBody
    public String update2(@RequestParam(value = "id", required = true) int id) {
        Bookshelf bookshelf = new Bookshelf();
        bookshelf.setBkno(id);
        bookshelf.setBcategory("更改1");
        bookshelf.setBklocation("更改2");
        bookService.updateById(bookshelf);
        return "ok";
    }

前端 AJAX 请求:

<body>
    <input type="text" id="updateTestOfPUT">
    <button id="update2">updateTestOfPUT</button>
</body>
<script>
    $("#update2").on('click', function () {
        const updateTestOfPUT = $("#updateTestOfPUT").val();
        $.ajax({
            url: "http://localhost:8080/update",
            type: 'PUT',
            dataType: 'json',
            data: {'_method': 'PUT', 'id': updateTestOfPUT},
            success: function (data) {
                console.log(data)
            },
            error: function (e) {
            }
        });
    });
<script>

PATCH

PATCH是个新引入的方法,是对PUT方法的补充,用来对已知资源进行局部更新。

很多人对这个方法不太理解,因为使用PUT和PATCH方法都能成功,导致不太理解什么是局部更新。下面以更新 pojo 对象来理解它们的区别。

比如:User对象有id、name、password. sex 等属性。如果只需要修改name的值,则此时的更新操作就可以用 PATCH 方法。

但是在大多数的应用程序中,很多人都会使用 PUT 方法提交完整的 pojo 对象给后端。这种值法虽然在功能上是可以实现的,但对资源是一种浪费——提交的数据过多了。 如果遇到文章类型的对象,为了改一个标题,而要同时提交很多的内容实在是不划算(一篇文章一般由标题和内容等构成,内容往往很多)。

后端:

    @PatchMapping("/update")
//     @RequestMapping(value = "/update" ,method = RequestMethod.PATCH)
    @ResponseBody
    public String update3(@RequestParam(value = "id", required = true) int id) {
        Bookshelf bookshelf = new Bookshelf();
        bookshelf.setBkno(id);
        bookshelf.setBcategory("更改1");
        bookService.updateById(bookshelf);
        return "ok";
    }

前端 AJAX 请求:

<body>
    <input type="text" id="updateTestOfPATCH">
    <button id="update3">updateTestOfPATCH</button>
</body>
<script>
    $("#update3").on('click', function () {
        const updateTestOfPATCH = $("#updateTestOfPATCH").val();
        $.ajax({
            url: "http://localhost:8080/update",
            type: 'PATCH',
            dataType: 'json',
            data: {'_method': 'PATCH', 'id': updateTestOfPATCH},
            success: function (data) {
                console.log(data)
            },
            error: function (e) {
            }
        });
    })
</script>

局部更新可使用 Mybatis-plus 实现 

OPTIONS

该方法用于获取当前URL。若请求成功,则会在 HTTP ( HyperText Transfer Protocol,超文本传输协议) 头中包含一个名为 “Allow" 的头,其值是所支持的方法,如值为“GET、POST"。它还允许客户端查看服务器的性能。如果遇到“500错误”,则OPTIONS不进行第二次请求。

TRACE

它显示服务器收到的请求,主要用于测试或诊断。
 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中封装HTTP请求可以使用RestTemplate或者Feign来实现。下面分别介绍这两种方式的使用: 1. 使用RestTemplate: RestTemplate是Spring提供的一个HTTP客户端工具,可以发送HTTP请求处理响应。以下是一个简单的封装示例: ```java import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; public class HttpUtils { private static final RestTemplate restTemplate = new RestTemplate(); public static <T> T sendGetRequest(String url, Class<T> responseType) { HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(headers); ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, responseType); return responseEntity.getBody(); } public static <T> T sendPostRequest(String url, Object request, Class<T> responseType) { HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); HttpEntity<Object> entity = new HttpEntity<>(request, headers); ResponseEntity<T> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, responseType); return responseEntity.getBody(); } } ``` 上述代码中,我们定义了一个HttpUtils类,提供了sendGetRequest和sendPostRequest两个方法,分别用于发送GET和POST请求,并且可以指定返回结果的类型。 2. 使用Feign: Feign是一个声明式的Web服务客户端,可以通过注解方式定义和实现HTTP请求。以下是一个简单的封装示例: 1)首先,在Spring Boot的启动类上添加@EnableFeignClients注解: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 2)然后,创建一个Feign客户端接口: ```java import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @FeignClient(name = "example", url = "http://example.com") public interface HttpClient { @GetMapping("/api/get") String get(); @PostMapping("/api/post") String post(@RequestBody Object request); } ``` 在上述代码中,我们使用@FeignClient注解指定了服务名和请求URL。 3)最后,在需要使用HTTP请求的地方注入HttpClient接口并调用相应的方法: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { private final HttpClient httpClient; @Autowired public MyService(HttpClient httpClient) { this.httpClient = httpClient; } public String doHttpRequest() { String response = httpClient.get(); // 处理响应 return response; } } ``` 在上述代码中,我们通过@Autowired注解将HttpClient接口注入到MyService中,并调用需要的方法来发送HTTP请求。 以上是在Spring Boot中封装HTTP请求的两种常用方式,你可以根据具体需求选择使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值