@RequestBodyと@RequestParamの違いと使用法
表示する前のヒント:
この記事では、IDEAバージョンは究極の2019.1、JDKバージョンは1.8.0_141、Tomcatバージョンは9.0.12です。
1. @ RequestBody
1.1はじめに
@RequestBodyは、requestBodyから、つまりリクエスト本文でパラメータを受け取ります。
HttpEntityによって渡されたデータの処理は、通常、非Content-Type:application / x-www-form-urlencodedエンコーディング形式のデータを処理するために使用されます。
1.2例
テストクラスTestController.java
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 测试Controller
* @author jjy
* @date 2020-07-21
*/
@Controller
@RequestMapping("/test")
public class TestController {
/**
* 测试RequestBody
* @param jsonStr
* @return
*/
@RequestMapping("/testRequestBody")
@ResponseBody
public String testRequestBody(@RequestBody String jsonStr){
System.out.println(jsonStr);
return "success";
}
}
Postmanを使用してリクエストテストを送信します。結果は次のとおりです。
2. @RequestParam
2.1はじめに
@RequestParamが受け取るパラメータは、リクエストヘッダーであるrequestHeaderからのものです。
Content-Typeの処理に使用されます:application / x-www-form-urlencoded用にエンコードされたコンテンツ。
@RequestParamは、次の3つのパラメーターを構成できます。
-
requiredは、それが必要かどうかを示します。デフォルトはtrue、mustです。
-
defaultValueは、要求パラメーターのデフォルト値を設定できます。
-
valueは、受信URLのパラメーター名です(キー値に相当)。
2.2例
テストクラスTestController.java
package com.example.controller;
import com.example.model.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 测试Controller
* @author jjy
* @date 2020-07-21
*/
@Controller
@RequestMapping("/test")
public class TestController {
/**
* 测试RequestParam
* @param name
* @return
*/
@RequestMapping("/testRequestParam")
@ResponseBody
public String testRequestParam(@RequestParam(name = "userName") String name){
System.out.println(name);
return "success";
}
}
Postmanを使用してリクエストテストを送信します。結果は次のとおりです。