RestFulは、リソースの配置と操作のスタイルであり、標準でもプロトコルでもありません。このスタイルに基づくソフトウェア
より簡潔で、より階層的で、キャッシュメカニズムの実装がより簡単になります。
インターネットを操作する従来の方法は、さまざまなパラメーターを介して実現され、リクエストメソッドはpostとgetです。リクエストごとに、異なるリクエストパスを使用する必要があります。
localhost:8080/item/query?id=1
localhost:8080/item/add
localhost:8080/item/update
localhost:8080/item/delete?id=1
RestFulスタイルを使用すると、リクエストパスを変更せずに、さまざまなリクエストメソッドを介してさまざまなメソッドを呼び出して、さまざまな機能を実現できます。
localhost:8080/item/1 GET请求
localhost:8080/item POST请求
localhost:8080/item PUT请求
localhost:8080/item/1 DELETE请求
まず、従来のリクエストメソッドを見てください:uri?parameter 1 = value 1&parameter 2 = value 2 .. ..
package com.zzt.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestFulController {
@RequestMapping("/add")
public String test(int a, int b, Model model){
model.addAttribute("msg",a+b);
return "test";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
@PathVariableアノテーション:RestFulスタイルを実装するために使用されます
package com.zzt.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestFulController {
@RequestMapping("/add/{a}/{b}")
public String test(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("msg",a+b);
return "test";
}
}
上記のコードを例にとると、@ PathVariableは、パラメーター-int aの値がuriの{a}に由来し、パラメーター-intbの値がuriの{b}に由来することを指定します。
現時点では、従来の方法でアクセスするのは誤りであり、パラメータを受け取るにはRestFulスタイルを使用する必要があります。
@RequestMappingがリクエストメソッドを設定できると述べたことを覚えていますか?はい、この属性と組み合わせることができます。(もちろん、SpringMVCはサブアノテーション、@ GetMapping、@ PostMappingなども提供します)。
@GetMapping("/add/{a}/{b}")
public String testGet(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("msg","get请求到达 : " + (a + b));
return "test";
}
@PostMapping("/add/{a}/{b}")
public String testPost(@PathVariable int a,@PathVariable int b, Model model){
model.addAttribute("msg","post请求到达 : "+ (a+b));
return "test";
}
<body>
<a href="add/1/2">get提交方式
<form action="add/3/4" method="post">
<input type="submit" value="提交">
</form>
</body>
RestFulの利点:簡潔(パラメーター名の使用の問題を排除)、効率的(キャッシングメカニズム)、および安全(リクエストにパラメーター名が含まれていないため)