このページに書いてあること
Spring MVCの@RequestMappingは、URL・HTTPメソッド・パラメータ・ヘッダーなどの条件で、呼び出すControllerメソッドを選びます。同じURLでも、paramsで指定した値や、headersで指定した独自ヘッダーが違えば、行き先を分けられます。
この記事では、先にJSON・フォームを送る例で405・415・406の直す条件を確かめ、次にparamsとheadersで同じGETの呼出先を分けます。@RequestParamで値を受け取ることと、呼ぶメソッドを選ぶことの違いも、400・404を含む実行結果で確認します。
「JSONを返すControllerで、出力用の1メソッドだけテキストにしたら406になった」というときは、クラスとメソッドのproducesが重なったときの確認手順から読めます。 取引先の注文用+jsonで415になる場合は、同じJSONを送り分ける実習で確認します。 URLの末尾だけが違って404になる場合は、末尾スラッシュの実行結果を確認します。
前提
- サンプルはJava 17、Spring Boot 3.5.16(Spring Framework 6.2.19)のMockMvcで検証しています。Spring MVCの標準的な例外処理を前提にします。
- ZIPのテストはMockMvcで実行でき、HTTPサーバーは起動しません。本文のcurl例を試す場合だけ、ControllerをSpring Web入りのアプリへ配置し、
packageをコンポーネントスキャン対象に合わせます。Spring Securityや独自の例外処理が先に応答する場合、その結果を分けて調べます。
同じURLの条件選択と405・415・406を27件で再現する
Controller 4本、基本14件・条件選択9件・producesの優先順位4件の計27テスト、pom.xmlを収録しています。JDK 17とMaven 3.9系でZIPを展開し、mvn clean testを実行してください。MockMvcを使うため、HTTPサーバーの起動は不要です。params・headersの例はConditionSelectionTest.java、クラスとメソッドのproducesはProducesOverrideTest.javaで確認できます。
405だけを確かめるなら、展開したフォルダでmvn -Dtest='RequestMappingTest#unsupportedMethodIs405WithAllowPost' testを実行します。POST専用のSampleControllerにGET /sampleを送り、405とAllow: POSTを検証する1件です。separateGetExampleDoesNotNeedContentTypeではGET専用のGetOnlyControllerを別に登録するため、同じGET /sampleでも200になります。
実際のステータスとヘッダーを端末に表示するなら、手元のRequestMappingTest.javaの405テストで、mvc.perform(...)と最初の.andExpect(...)の間に.andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print())を一時的に追加して、同じコマンドを再実行します。MockHttpServletResponseのStatusが405、HeadersにAllowのPOSTが出ます。
同じコマンドの#以降をjsonRequestSelectsJsonHandlerに替えるとJSON送信の200、wrongContentTypeIs415なら送信形式の不一致による415、jsonRequestCannotDemandXmlResponseなら応答形式の不一致による406を、1件ずつ検証できます。
RequestMappingTest.javaの全文を見る
package com.example.demo;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.http.converter.HttpMessageNotReadableException;
class RequestMappingTest {
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new SampleController()).build();
}
@Test
void jsonRequestSelectsJsonHandler() throws Exception {
mvc.perform(post("/sample").contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content("{\"message\":\"hello\"}"))
.andExpect(status().isOk())
.andExpect(handler().methodName("receiveJson"))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json("{\"receivedBy\":\"json\"}"));
}
@Test
void formRequestSelectsFormHandler() throws Exception {
mvc.perform(post("/sample").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_XML).param("message", "hello"))
.andExpect(status().isOk())
.andExpect(handler().methodName("receiveForm"))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_XML))
.andExpect(content().string("<result>form</result>"));
}
@Test
void unsupportedMethodIs405WithAllowPost() throws Exception {
mvc.perform(get("/sample").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isMethodNotAllowed())
.andExpect(header().string("Allow", "POST"))
.andExpect(result -> assertInstanceOf(HttpRequestMethodNotSupportedException.class,
result.getResolvedException()));
}
@Test
void wrongContentTypeIs415() throws Exception {
mvc.perform(post("/sample").contentType(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON).content("<message>hello</message>"))
.andExpect(status().isUnsupportedMediaType())
.andExpect(result -> assertInstanceOf(HttpMediaTypeNotSupportedException.class,
result.getResolvedException()));
}
@Test
void jsonRequestCannotDemandXmlResponse() throws Exception {
mvc.perform(post("/sample").contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_XML).content("{\"message\":\"hello\"}"))
.andExpect(status().isNotAcceptable())
.andExpect(result -> assertInstanceOf(HttpMediaTypeNotAcceptableException.class,
result.getResolvedException()));
}
@Test
void formRequestCannotDemandJsonResponse() throws Exception {
mvc.perform(post("/sample").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON).param("message", "hello"))
.andExpect(status().isNotAcceptable());
}
@Test
void unknownPathIs404() throws Exception {
mvc.perform(post("/missing").contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content("{\"message\":\"hello\"}"))
.andExpect(status().isNotFound());
}
@Test
void missingContentTypeIs415ForThisController() throws Exception {
mvc.perform(post("/sample").accept(MediaType.APPLICATION_JSON)
.content("{\"message\":\"hello\"}"))
.andExpect(status().isUnsupportedMediaType());
}
@Test
void malformedJsonIs400AfterMatchingMediaTypes() throws Exception {
mvc.perform(post("/sample").contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content("{invalid}"))
.andExpect(status().isBadRequest())
.andExpect(result -> assertInstanceOf(HttpMessageNotReadableException.class,
result.getResolvedException()));
}
@Test
void absentAcceptAllowsJson() throws Exception {
mvc.perform(post("/sample").contentType(MediaType.APPLICATION_JSON)
.content("{\"message\":\"hello\"}"))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON));
}
@Test
void wildcardAcceptAllowsJson() throws Exception {
mvc.perform(post("/sample").contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.ALL).content("{\"message\":\"hello\"}"))
.andExpect(status().isOk());
}
@Test
void omittingConsumesAndProducesDoesNotDisableJsonConversion() throws Exception {
MockMvc automatic = MockMvcBuilders.standaloneSetup(new AutomaticController()).build();
automatic.perform(post("/automatic").contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON).content("{\"message\":\"hello\"}"))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json("{\"message\":\"hello\"}"));
}
@Test
void separateGetExampleDoesNotNeedContentType() throws Exception {
MockMvc getOnly = MockMvcBuilders.standaloneSetup(new GetOnlyController()).build();
getOnly.perform(get("/sample")).andExpect(status().isOk())
.andExpect(handler().methodName("execute1"))
.andExpect(content().string("success"));
getOnly.perform(get("/sample2")).andExpect(status().isOk())
.andExpect(handler().methodName("execute2"));
}
@Test
void postToSeparateGetExampleIs405() throws Exception {
MockMvc getOnly = MockMvcBuilders.standaloneSetup(new GetOnlyController()).build();
getOnly.perform(post("/sample")).andExpect(status().isMethodNotAllowed());
}
@org.springframework.web.bind.annotation.RestController
static class AutomaticController {
@org.springframework.web.bind.annotation.PostMapping("/automatic")
java.util.Map<String, String> echo(
@org.springframework.web.bind.annotation.RequestBody SampleController.SampleRequest request) {
return java.util.Map.of("message", request.message());
}
}
}pom.xmlの全文を見る
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.5.16</version><relativePath/></parent>
<groupId>info.syachiku.blog</groupId><artifactId>requestmapping-609</artifactId><version>1.0.0</version>
<properties><java.version>17</java.version></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>
</project>まずは結論とサンプル
package com.example.demo;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SampleController {
@RequestMapping(method = RequestMethod.POST, value = "/sample",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, String> receiveJson(@RequestBody SampleRequest request) {
return Map.of("receivedBy", "json");
}
@RequestMapping(method = RequestMethod.POST, value = "/sample",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_XML_VALUE)
public String receiveForm(@RequestParam("message") String message) {
return "<result>form</result>";
}
public record SampleRequest(String message) { }
}どちらもPOST /sampleですが、Content-Type: application/jsonならreceiveJson()、application/x-www-form-urlencodedならreceiveForm()が選ばれます。JSONは@RequestBody、フォームの値は@RequestParamで受けています。
受信値は保存せず、到達したメソッドを固定のJSON/XMLで返します。JSON側はMapを変換し、XML側は固定文字列を返す例です。producesを付けるだけで、任意のJavaオブジェクトをXMLへ変換できるわけではありません。
リクエスト:Content-TypeとAcceptを別々に指定する
Content-Typeは「いま送る本文は何形式か」、Acceptは「どの形式の応答を受け取れるか」です。次はmacOS・Linuxなどのシェルで使えるcurl例です。レスポンス先頭のステータスと、応答のContent-Typeも確認してください。
# JSONを送り、JSONの応答を求める → 200 / {"receivedBy":"json"}
curl -i -X POST http://localhost:8080/sample \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
--data '{"message":"hello"}'
# フォームを送り、XMLの応答を求める → 200 / <result>form</result>
curl -i -X POST http://localhost:8080/sample \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'Accept: application/xml' \
--data 'message=hello'405・415・406は、直す条件が違う
| 結果 | このサンプルで合っていない条件 | まず確認・修正するもの |
|---|---|---|
| 404 Not Found | /missingなど、対応するパスがない | URL、コンテキストパス、Controllerの登録 |
| 405 Method Not Allowed | GET /sample。このURLはPOSTだけ | API仕様とHTTPメソッド。応答のAllow: POSTも確認 |
| 415 Unsupported Media Type | POSTの本文をapplication/xmlで送った | 本文とContent-Type、受け側のconsumes |
| 406 Not Acceptable | JSONを送る入口にAccept: application/xmlを要求した | Acceptと、その入口のproduces |
# 405:/sampleはあるが、GETを受けるメソッドがない
curl -i http://localhost:8080/sample
# 415:POSTは合っているが、XMLを受ける入口がない
curl -i -X POST http://localhost:8080/sample \
-H 'Content-Type: application/xml' \
-H 'Accept: application/json' \
--data '<message>hello</message>'
# 406:JSONの入口は、XMLの応答を返す条件になっていない
curl -i -X POST http://localhost:8080/sample \
-H 'Content-Type: application/json' \
-H 'Accept: application/xml' \
--data '{"message":"hello"}'405なら正しい操作のPOSTで送る、415なら受け側が対応する本文とContent-Typeをそろえる、406なら受け取れる応答形式をAcceptで指定する、という順に切り分けます。ヘッダだけJSONへ偽装してXML本文を送っても解決しません。
これらはこのControllerを標準のSpring MVCで動かした場合の結果です。JSONの形式自体が壊れていれば、条件が合っていても読み取り時に400になります。また、415や406は変換器の不足でも発生するため、ヘッダが一致している場合は例外名とメッセージまで確認します。
@RequestMappingの使い方
指定する条件と、実際のリクエストで見る場所を対応させます。@GetMappingや@PostMappingでも、params・headers・consumes・producesを指定できます。
| 指定する属性 | 要求のどこを見るか | 条件の例 |
|---|---|---|
path / value | URLのパス | /sample |
method | HTTPメソッド | GET、POST |
params | リクエストパラメータの有無・値 | mode=preview |
headers | リクエストヘッダーの有無・値 | X-Client=internal |
consumes | 送られた本文のContent-Type | application/json |
produces | 要求されたAcceptと返せる形式 | application/json |
@RequestMapping はControllerのクラスとメソッドに付けられます。クラスに @RequestMapping("/orders")、参照メソッドに @GetMapping("/{id}") を付けると、両方のパスを合わせて GET /orders/42 のようなリクエストに対応します。下のサンプルはクラス側の共通パスを付けず、メソッド側に /sample を指定しています。
ここからはGETだけを受ける別の例です。先ほどのPOST用Controllerと併用せず、置き換えて確認してください。/sampleと/sample2を用意します。
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class GetOnlyController {
@RequestMapping(method = RequestMethod.GET, value = "/sample")
@ResponseBody
public String execute1() {
return "success";
}
@RequestMapping(method = RequestMethod.GET, value = "/sample2")
@ResponseBody
public String execute2() {
return "success";
}
}このコードでは@RequestMappingにより以下のことをしています。
- GETメソッドを受信
- URLは/sampleと/sample2が使用可能
このようになっています。
「method=XX」で受信可能なHTTPメソッドを指定します。このGET専用例へPOST /sampleを送ると、パスは存在していても405 Method Not Allowedです。対応するパス自体がない場合の404と区別してください。GETは@GetMapping、POSTは@PostMappingでも表せます。
「value=xxx」はリクエストのパスを指定します。この例ならGET /sampleでexecute1()が実行されます。URLだけで決まるのではなく、HTTPメソッドや後述のメディアタイプなど、指定した条件が合う必要があります。
末尾に「/」を付けたときだけ404になる
画面のリンクから開くと404になり、自分で入力したURLは開ける場合は、Networkに残ったパスの末尾まで照合します。たとえばGET /sampleが成功していても、リンク先が/sample/だと結果が変わります。Spring Framework 6.2.19の既定で、末尾の/は自動では補いません。
| リクエスト | /sampleだけ登録 | 両方を登録 |
|---|---|---|
GET /sample | 200 | 200 |
GET /sample/ | 404 | 200 |
左の設定で/sample/を送ったときは、実習のMockMvcでNoHandlerFoundExceptionになり、Controllerは呼ばれませんでした。404の要因は構成によって変わるので、手元の調査では実際に送ったパスと登録されているパスを照合します。
URLを1つに揃える仕様なら、画面のリンクや呼び出し元を/sampleに直します。既存クライアント向けに両方を受け付ける仕様なら、次のように同じメソッドへ2つのパスを登録します。どちらからもexecuteが呼ばれ、本文にsuccessが返ります。
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TrailingSlashController {
@GetMapping({"/sample", "/sample/"})
public String execute() {
return "success";
}
}同じGETで末尾の1文字だけを変える
Java 17とMavenで、展開先のmvn -Dtest=TrailingSlashMappingTest testを実行すると追加4件を再現できます。mvn testでは既存27件を含めて31件です。ZIPにControllerとMockMvcテスト、実行設定、手順を収録しています。
既定の動作はSpring Framework 6.2のPathPatternParserで確認できます。
同じGETを、paramsとheadersで分ける
次はConditionalControllerだけを登録する別の例です。先ほどのPOST専用SampleController、GET専用GetOnlyControllerとは併用しません。クラスの/sampleに各メソッドのパスを合わせます。
ConditionalController.java(全文)
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/sample")
public class ConditionalController {
@GetMapping(params = "mode=preview")
public String preview(@RequestParam(name = "name", defaultValue = "guest") String name) {
return "preview:" + name;
}
@GetMapping(params = "mode=confirm")
public String confirm(@RequestParam(name = "name", defaultValue = "guest") String name) {
return "confirm:" + name;
}
@GetMapping(path = "/headers", headers = "X-Client=internal")
public String internal() {
return "internal";
}
@GetMapping(path = "/headers", headers = "X-Client=external")
public String external() {
return "external";
}
}GET /sample?mode=preview&name=Aliceはpreview()、mode=confirm&name=Bobはconfirm()へ進みます。paramsが呼ぶメソッドを選び、@RequestParamが選ばれたメソッドの引数へnameを渡します。nameを省略するとguestになりますが、modeの指定は省略できません。confirmは分岐名で、到達したメソッド名とnameを文字列で返すだけです。保存や状態更新は行いません。
GET /sample/headersでは独自ヘッダーX-Clientの値でメソッドを選びます。internalならinternal()、externalならexternal()です。送る本文と応答の形式は、この独自ヘッダーへまとめず、後述のconsumesとproducesで指定します。
ZIPを展開したフォルダーで、次を実行すると条件選択の9件だけを試せます。ConditionSelectionTestがMockMvcへこのControllerだけを登録するため、HTTPサーバーの起動やcurlは不要です。
mvn -Dtest=ConditionSelectionTest test| 送る要求 | 選ばれるメソッド | HTTPと応答 |
|---|---|---|
GET /sample?mode=preview&name=Alice | preview() | 200 / preview:Alice |
GET /sample?mode=confirm&name=Bob | confirm() | 200 / confirm:Bob |
GET /sample?mode=preview | preview() | 200 / preview:guest |
GET /sample?name=Alice(modeなし) | 呼ばれない | 400 |
GET /sample?mode=unknown | 呼ばれない | 400 |
GET /sample/headers + X-Client: internal | internal() | 200 / internal |
GET /sample/headers + X-Client: external | external() | 200 / external |
GET /sample/headers(X-Clientなし) | 呼ばれない | 404 |
GET /sample/headers + X-Client: partner | 呼ばれない | 404 |
modeがない・値が未知の場合は、パラメータ条件を満たさず400になり、UnsatisfiedServletRequestParameterExceptionが解決されます。X-Clientがない・値がpartnerの場合は、条件に合う入口がなく404になり、NoHandlerFoundExceptionが解決されます。どちらもControllerメソッドには入っていません。
各テストはINPUT・STATUS・HANDLER・EXCEPTION・BODYを表示します。表はJava 17・Spring Framework 6.2.19のこのControllerでの結果です。別の入口、Spring Security、独自例外処理があれば結果は変わります。404だけを見てURLの誤りと決めつけず、headersの条件も照合します。
ConditionSelectionTest.javaの全文を見る(追加9件)
package com.example.demo;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.method.HandlerMethod;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.servlet.NoHandlerFoundException;
class ConditionSelectionTest {
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new ConditionalController()).build();
}
@Test
void previewParameterSelectsPreview() throws Exception {
mvc.perform(get("/sample").param("mode", "preview").param("name", "Alice"))
.andDo(result -> observe("mode=preview&name=Alice", result))
.andExpect(status().isOk())
.andExpect(handler().methodName("preview"))
.andExpect(content().string("preview:Alice"));
}
@Test
void confirmParameterSelectsConfirm() throws Exception {
mvc.perform(get("/sample").param("mode", "confirm").param("name", "Bob"))
.andDo(result -> observe("mode=confirm&name=Bob", result))
.andExpect(status().isOk())
.andExpect(handler().methodName("confirm"))
.andExpect(content().string("confirm:Bob"));
}
@Test
void requestParamDefaultDoesNotReplaceModeCondition() throws Exception {
mvc.perform(get("/sample").param("mode", "preview"))
.andDo(result -> observe("mode=preview (name omitted)", result))
.andExpect(status().isOk())
.andExpect(handler().methodName("preview"))
.andExpect(content().string("preview:guest"));
}
@Test
void missingModeIs400BeforeCallingController() throws Exception {
mvc.perform(get("/sample").param("name", "Alice"))
.andDo(result -> observe("mode omitted", result))
.andExpect(status().isBadRequest())
.andExpect(result -> assertNull(result.getHandler()))
.andExpect(result -> assertInstanceOf(UnsatisfiedServletRequestParameterException.class,
result.getResolvedException()));
}
@Test
void unknownModeIs400BeforeCallingController() throws Exception {
mvc.perform(get("/sample").param("mode", "unknown"))
.andDo(result -> observe("mode=unknown", result))
.andExpect(status().isBadRequest())
.andExpect(result -> assertNull(result.getHandler()))
.andExpect(result -> assertInstanceOf(UnsatisfiedServletRequestParameterException.class,
result.getResolvedException()));
}
@Test
void internalHeaderSelectsInternal() throws Exception {
mvc.perform(get("/sample/headers").header("X-Client", "internal"))
.andDo(result -> observe("X-Client=internal", result))
.andExpect(status().isOk())
.andExpect(handler().methodName("internal"))
.andExpect(content().string("internal"));
}
@Test
void externalHeaderSelectsExternal() throws Exception {
mvc.perform(get("/sample/headers").header("X-Client", "external"))
.andDo(result -> observe("X-Client=external", result))
.andExpect(status().isOk())
.andExpect(handler().methodName("external"))
.andExpect(content().string("external"));
}
@Test
void missingHeaderIs404ForThisController() throws Exception {
mvc.perform(get("/sample/headers"))
.andDo(result -> observe("X-Client omitted", result))
.andExpect(status().isNotFound())
.andExpect(result -> assertNull(result.getHandler()))
.andExpect(result -> assertInstanceOf(NoHandlerFoundException.class,
result.getResolvedException()));
}
@Test
void unknownHeaderIs404ForThisController() throws Exception {
mvc.perform(get("/sample/headers").header("X-Client", "partner"))
.andDo(result -> observe("X-Client=partner", result))
.andExpect(status().isNotFound())
.andExpect(result -> assertNull(result.getHandler()))
.andExpect(result -> assertInstanceOf(NoHandlerFoundException.class,
result.getResolvedException()));
}
private static void observe(String input, MvcResult result) throws Exception {
String selected = result.getHandler() instanceof HandlerMethod method
? method.getMethod().getName() : "none";
String exception = result.getResolvedException() == null
? "none" : result.getResolvedException().getClass().getSimpleName();
System.out.printf("INPUT=%s STATUS=%d HANDLER=%s EXCEPTION=%s BODY=%s%n",
input, result.getResponse().getStatus(), selected, exception,
result.getResponse().getContentAsString());
}
}レビューでは「modeは入口を選ぶ条件、nameは選ばれた処理へ渡す値です。modeの欠落は400、独自ヘッダーの不一致はこの構成で404まで確認しました」のように、どの要求がどの処理へ進むかを説明します。なおX-Clientはクライアントが送れる値なので、この例の分岐を認証・権限の証明には使いません。
本文を送らない普通のGETでは、送信本文の形式を表すconsumesを付ける必要はありません。返してほしい形式を指定する場合はAcceptを使います。次に、POSTで本文を送る例へ戻ってconsumesとproducesを見ます。
consumes:送る本文のContent-Typeで入口を分ける
consumesは、リクエストのContent-Typeを使って、どのメソッドで受け付けるかを絞る条件です。ここではJSON本文のPOSTを受け付けます。
@RequestMapping(method = RequestMethod.POST, value = "/sample",
consumes = MediaType.APPLICATION_JSON_VALUE)Content-Type: application/jsonを送ると、この条件に一致します。今回のサンプルでXML本文を送ると、XMLを受けるメソッドがないため415になります。本文がJSONでもContent-Typeを省略すると、このサンプルでは415です。
ただし、consumesが本文を変換するわけではありません。JSONを@RequestBodyのJava型へ読むのはHttpMessageConverterです。対応する変換器・Java型・正しい本文が必要です。
どんなときに役立つか
同じ登録機能をJSONのAPIとHTMLフォームの両方から呼ぶ場面です。JSONとPOSTは対になる分類ではありません。POSTはHTTPメソッドで、JSONとフォームは本文の形式です。どちらもPOSTで送れます。
consumesを書かなくても、Springの本文変換は使えます。「指定しないと自分でJSONを解析する必要がある」という意味ではありません。指定する目的は、APIが受け付ける形式を契約として明示し、必要なら入口を分けることです。
最初の例はJSONを@RequestBody SampleRequest、フォームを@RequestParam("message")で受けています。形式ごとに受け取った後の業務処理が同じなら、共通のServiceへ渡し、登録処理そのものは重複させません。
入口を分けると、次の対応になります。URLとHTTPメソッドは同じでも、送る本文とヘッダは別です。
| POST /sampleに送るもの | 選ばれるメソッド | 値の受け方 |
|---|---|---|
JSON本文+Content-Type: application/json | receiveJson() | @RequestBody |
フォーム本文+Content-Type: application/x-www-form-urlencoded | receiveForm() | @RequestParam |
レビューでは「JSONとフォームの入口を分け、受信後は同じServiceへ渡します。XMLは仕様に含めないので415です」のように、受け付ける形式と、受け付けない理由を説明できれば十分です。
415を消すためだけにconsumesを削除せず、まずAPI仕様を確認します。送信側のヘッダが間違っているのか、受信側で新しい形式に対応する必要があるのかを決めてから直します。
POST /orders/previewに、同じ本文{"orderId":"ORD-42","quantity":2}を送ります。Accept: application/jsonも固定します。比較するのは送信側のContent-Typeと、受信側のconsumesです。
変更前。 標準のJSONだけを受け付けるControllerメソッドです。
@PostMapping(path = "/orders/preview", consumes = MediaType.APPLICATION_JSON_VALUE)
public OrderPreview preview(@RequestBody OrderRequest request) {
return service.preview(request);
}注文用の型も受け付ける場合。 同じメソッドのconsumesに、仕様で決めた型を1つ追加します。サンプルのテストでは2つのControllerを比較ごとに一方だけ登録します。
@PostMapping(path = "/orders/preview", consumes = {
MediaType.APPLICATION_JSON_VALUE, "application/vnd.example.order+json"
})
public OrderPreview preview(@RequestBody OrderRequest request) {
return service.preview(request);
}- 変更前に
application/jsonを送ると200。Serviceが1回呼ばれ、注文番号と個数を返します。 - 変更前に
application/vnd.example.order+jsonを送ると415。Controllerが選ばれず、Serviceは0回です。 - 注文用の型を明示した後に同じ注文を送ると200。Serviceは1回です。
- 変更後も、
application/vnd.example.invoice+jsonなら415。Serviceは0回です。
5件目で、既定のJackson変換器が注文用・請求用のどちらの型も読み取り対象にできることを確認します。Spring MVCはconsumesとContent-Typeを先に照合します。入口を通った本文は、その後で@RequestBodyの型へ変換されます。この例の415ではHttpMediaTypeNotSupportedExceptionが解決され、Controllerは選ばれていません。
仕様が標準JSONなら送信側のContent-Typeを揃えます。注文用の型を受け付ける仕様なら、その型をconsumesに追加し、請求用の型は引き続き415になることまでテストします。
produces:返せる形式をAcceptと照合する
producesは、そのメソッドが返せるメディアタイプの条件です。リクエストのAcceptと照合してメソッドを絞ります。リクエスト本文のContent-Typeと混同しないでください。
最初の例でJSONを受けるメソッドはproduces = application/jsonです。そこへAccept: application/xmlを指定すると、受け付ける本文の形式は合っていても、返せる形式が合わず406になります。
@RequestMapping(method = RequestMethod.POST, value = "/sample",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)どんなときに役立つか
APIがJSONだけを返すと明示したい場合や、同じパスからJSONと別形式の表現を返したい場合に使います。クライアントがAcceptを省略したり*/*を指定したりした場合、このサンプルではJSONの応答を返せます。
クラスにもメソッドにもproducesの指定がない場合、@RestControllerや@ResponseBodyの戻り値は、利用可能な変換器とAcceptなどに基づいてレスポンスへ変換されます。
クラスとメソッドの両方にproducesを書くと、メソッドの指定が優先される
レポートAPIはふだんJSONを返し、出力用のGET /reports/exportだけプレーンテキストを返す仕様にします。出力用メソッドにも既定のJSONが適用されていると、Accept: text/plainで呼んだときに406になります。Spring MVCが応答形式の条件を照合する段階で処理が止まります。
修正するのは出力用メソッドの宣言です。@GetMappingにproduces = MediaType.TEXT_PLAIN_VALUEを指定すると、そのURLの応答形式条件はtext/plainになります。クラスの/reportsとメソッドの/exportは従来どおり合成されます。既定の/reports/defaultはクラスのJSON指定を引き継ぎます。
package com.example.demo;
import java.util.Map;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/reports", produces = MediaType.APPLICATION_JSON_VALUE)
public class ProducesOverrideController {
@GetMapping("/default")
public Map<String, String> defaultReport() {
return Map.of("status", "ready");
}
@GetMapping(value = "/export", produces = MediaType.TEXT_PLAIN_VALUE)
public String export() {
return "status=ready";
}
}冒頭のZIPを展開し、pom.xmlのある場所でmvn -Dtest=ProducesOverrideTest testを実行します。各URLにJSONとテキストの両方を要求し、ステータスのほか、成功時はレスポンスの形式と本文、406のときはメソッドへ届いていないことをテストで確認します。下は実行ログから要求と結果を並べ直したものです。
GET /reports/default
Accept: application/json → 200
application/json
GET /reports/default
Accept: text/plain → 406
HttpMediaTypeNotAcceptableException
GET /reports/export
Accept: text/plain → 200
text/plain; charset=ISO-8859-1
GET /reports/export
Accept: application/json → 406
HttpMediaTypeNotAcceptableExceptionProducesOverrideTest.javaの全文を表示する
package com.example.demo;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
class ProducesOverrideTest {
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new ProducesOverrideController()).build();
}
@Test
void defaultInheritsClassJsonProduces() throws Exception {
mvc.perform(get("/reports/default").accept(MediaType.APPLICATION_JSON))
.andDo(result -> observe("/reports/default", "application/json", result))
.andExpect(status().isOk())
.andExpect(handler().methodName("defaultReport"))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().json("{\"status\":\"ready\"}"));
}
@Test
void inheritedJsonRejectsPlainAccept() throws Exception {
mvc.perform(get("/reports/default").accept(MediaType.TEXT_PLAIN))
.andDo(result -> observe("/reports/default", "text/plain", result))
.andExpect(status().isNotAcceptable())
.andExpect(result -> assertNull(result.getHandler()))
.andExpect(result -> assertInstanceOf(HttpMediaTypeNotAcceptableException.class,
result.getResolvedException()));
}
@Test
void exportOverridesClassJsonWithPlainProduces() throws Exception {
mvc.perform(get("/reports/export").accept(MediaType.TEXT_PLAIN))
.andDo(result -> observe("/reports/export", "text/plain", result))
.andExpect(status().isOk())
.andExpect(handler().methodName("export"))
.andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN))
.andExpect(content().string("status=ready"));
}
@Test
void overriddenPlainDoesNotKeepClassJsonAsAlternative() throws Exception {
mvc.perform(get("/reports/export").accept(MediaType.APPLICATION_JSON))
.andDo(result -> observe("/reports/export", "application/json", result))
.andExpect(status().isNotAcceptable())
.andExpect(result -> assertNull(result.getHandler()))
.andExpect(result -> assertInstanceOf(HttpMediaTypeNotAcceptableException.class,
result.getResolvedException()));
}
private static void observe(String path, String accept, MvcResult result) {
Exception failure = result.getResolvedException();
System.out.printf("PRODUCES path=%s accept=%s status=%d contentType=%s exception=%s%n",
path, accept, result.getResponse().getStatus(), result.getResponse().getContentType(),
failure == null ? "none" : failure.getClass().getSimpleName());
}
}原因を同じURLで確かめるには、export()の@GetMappingからproducesだけを外し、value = "/export"を残して4件を再実行します。Accept: text/plainは200から406に変わり、Accept: application/jsonは406から200に変わります。既定の/reports/defaultの2件はそのまま通ります。指定を戻すと4件とも通ります。
現場で406を調べるときは、まず対象メソッドのproducesを確認し、未指定ならクラスの設定を見ます。APIの仕様がテキスト出力なら、出力用メソッドの条件と実際の戻り値をそろえます。仕様がJSONなのに呼び出し元だけがテキストを求めているなら、呼び出し元のAcceptを直します。producesはマッピングの条件を指定する属性です。レスポンスの本文は戻り値とHTTPメッセージ変換器で決まるため、修正後はContent-Typeと本文まで照合します。
一次資料 Spring Framework 6.2のproducesの仕様
修正前に確認すること
API仕様と、ブラウザの開発者ツールやcurlで確認した実際のリクエストを並べます。ソースコードの見た目だけで判断しないことが大切です。
- パスとHTTPメソッドは一致しているか。405なのにURLだけを直そうとしていないか。
- 送信本文とContent-Typeは同じ形式か。フォームなのにapplication/jsonを付けていないか。
- 406が出たURLの
Acceptを確認したか。Controllerクラスと対象メソッドのproducesから、そのURLで有効な形式を特定できるか。 paramsで求める値とheadersの条件は、実際の要求にあるか。@RequestParamで引数を受け取ることと、メソッドの選択条件を満たすことを混同していないか。- 条件が合うのに失敗する場合、JSONの構文、引数型、変換器、Security、独自の例外処理を確認したか。
405・415・406を切り分けたら、次はControllerに届いた後の処理を追います。注文APIの例で、HTTPの応答とDBの状態をどのように照合するか確かめられます。
根拠:Spring公式のRequest Mapping、標準例外とHTTPステータス、@RequestBody・@ResponseBody。

