简体   繁体   English

何时在 spring 中使用不同的请求方法

[英]When to use different request methods in spring

I've been tasked with creating a simple REST API, where a single double is provided, and another one is derived from it according to some rules.我的任务是创建一个简单的 REST API,其中提供了一个双精度,另一个是根据一些规则从它派生的。

When creating a controller, I made the method for parsing said base double in two ways.在创建 controller 时,我以两种方式制作了解析所述 base double 的方法。

@GetMapping("calculate/{income:.+}")
public ResponseEntity<?> calculateEAT(@PathVariable double income){
  return ResponseEntity.ok(TaxDAO.addResult(income));
}
@PostMapping("calculate/{income:.+}")
public ResponseEntity<?> calculateEAT(@PathVariable double income){
  return ResponseEntity.ok(TaxDAO.addResult(income));
}

The only difference is the type of mapping used.唯一的区别是使用的映射类型。 The only difference I noticed was that I could type income in the browser address bar with GET mapping - and it worked.我注意到的唯一区别是我可以使用 GET 映射在浏览器地址栏中输入收入——而且它有效。 With post mapping, I could only get results using Postman.使用后期映射,我只能使用 Postman 获得结果。

I'm assuming it's possible to write an entire controller using GET mapping.我假设可以使用 GET 映射编写整个 controller。 I don't really feel like it's a good practice though.不过,我真的不觉得这是一个好习惯。 Are there any rules for using Request Methods in controllers?在控制器中使用请求方法有什么规则吗?

GET and POST requests are different HTTP methods. GET 和 POST 请求是不同的 HTTP 方法。 The browser will do a GET request when you type something in the browser address bar, that is why you can only make it work in Postman (where you can select which HTTP method to use).当您在浏览器地址栏中键入内容时,浏览器将执行 GET 请求,这就是为什么您只能使其在 Postman 中工作(您可以在 select 中使用 Z293C9EA246FF9985DC6F62A650F78986 方法)。

You should use GET when you want to retrieve something from the REST API.当您想从 REST API 检索某些内容时,您应该使用 GET。 You should use POST when you want to submit something to the REST API, usually creating a resource or triggering some kind of process.当您想向 REST API 提交内容时,您应该使用 POST,通常是创建资源或触发某种进程。 You can read more about each HTTP method in the following online resources:您可以在以下在线资源中阅读有关每种 HTTP 方法的更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM