18.

【Spring】@RequestMappingアノテーションとは

編集
この記事の要点
  • @RequestMappingURL パスとコントローラ・メソッドを紐付ける
  • クラス全体に付与すると共通プレフィックス、メソッドに付与すると個別 URL
  • HTTP メソッド指定: @GetMapping / @PostMapping / @PutMapping / @DeleteMapping / @PatchMapping がショートカット
  • パラメータ・ヘッダ・consumes / produces でマッチ条件を絞り込み

 

基本的な使い方

@RestController
@RequestMapping("/api/users")  // ← クラスレベル:共通プレフィックス
public class UserController {

    @RequestMapping(method = RequestMethod.GET)
    public List list() { ... }   // GET /api/users

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User get(@PathVariable Long id) { ... }   // GET /api/users/123

    @RequestMapping(method = RequestMethod.POST)
    public User create(@RequestBody User user) { ... }   // POST /api/users
}

HTTP メソッド別ショートカット(推奨)

HTTP メソッドショートカット@RequestMapping 等価
GET@GetMapping@RequestMapping(method = RequestMethod.GET)
POST@PostMapping@RequestMapping(method = RequestMethod.POST)
PUT@PutMapping@RequestMapping(method = RequestMethod.PUT)
DELETE@DeleteMapping@RequestMapping(method = RequestMethod.DELETE)
PATCH@PatchMapping@RequestMapping(method = RequestMethod.PATCH)
@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping            public List list() { ... }
    @GetMapping("/{id}")   public User get(@PathVariable Long id) { ... }
    @PostMapping           public User create(@RequestBody User user) { ... }
    @PutMapping("/{id}")   public User update(@PathVariable Long id, @RequestBody User u) { ... }
    @DeleteMapping("/{id}") public void delete(@PathVariable Long id) { ... }
}

主要な属性

属性用途
value / pathURL パス(複数指定可)
methodHTTP メソッド(複数指定可)
paramsクエリパラメータ条件
headersHTTP ヘッダ条件
consumes受け付ける Content-Type
produces返す Content-Type

マッチング条件で絞り込む

① クエリパラメータ条件

// type=admin が必須
@GetMapping(value = "/users", params = "type=admin")
public List listAdmins() { ... }

// type が指定されていない
@GetMapping(value = "/users", params = "!type")
public List listAll() { ... }

// 複数条件
@GetMapping(value = "/users", params = {"status=active", "role"})
public List listActiveByRole(...) { ... }

② ヘッダ条件

@GetMapping(value = "/data", headers = "X-API-Version=2")
public DataV2 getV2() { ... }

@PostMapping(value = "/upload", headers = "Content-Type=multipart/form-data")
public Response upload(...) { ... }

③ Content-Type / Accept ヘッダ(consumes / produces)

// JSON のみ受け付ける
@PostMapping(value = "/users", consumes = "application/json")
public User create(@RequestBody User user) { ... }

// 複数の Content-Type 対応
@PostMapping(consumes = {"application/json", "application/xml"})
public User create(@RequestBody User user) { ... }

// JSON でレスポンスを返す(クライアント Accept ヘッダで判定)
@GetMapping(value = "/{id}", produces = "application/json")
public User get(...) { ... }

// CSV を返す
@GetMapping(value = "/export", produces = "text/csv")
public String exportCsv() { ... }

複数 URL を 1 つのメソッドに

@GetMapping({"/users", "/users/"})  // 末尾スラッシュあり・なし両対応
public List list() { ... }

// クラスとメソッド両方で複数
@RequestMapping({"/api/users", "/api/v2/users"})
public class UserController {
    @GetMapping
    public List list() { ... }
    // → /api/users, /api/v2/users 両方でアクセス可
}

パスパターン(ワイルドカード)

// ?: 1 文字ワイルドカード
@GetMapping("/items/?")
public Item get(@PathVariable String id) { ... }

// *: 1 セグメントワイルドカード
@GetMapping("/items/*")
public List list() { ... }

// **: 0 以上のセグメント
@GetMapping("/files/**")
public Resource serve(HttpServletRequest req) {
    String path = req.getRequestURI().substring("/files/".length());
    // ファイル配信
}

// 正規表現
@GetMapping("/items/{id:[0-9]+}")
public Item get(@PathVariable Long id) { ... }

注意: @RequestMapping と @RestController の組み合わせ

// 良い例
@RestController
@RequestMapping("/api/users")
public class UserController { ... }

// 古い例(今は @RestController + @RequestMapping のほうが明示的)
@Controller
@ResponseBody
@RequestMapping("/api/users")
public class UserController { ... }

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. @After
  2. @Autowired
  3. @Bean
  4. @Before
  5. @Column
  6. @Component
  7. @Configuration
  8. @Controller
  9. @Data
  10. @Entity
  11. @GeneratedValue
  12. @Id
  13. @Modifying
  14. @PathVariable
  15. @PropertySource
  16. @Repository
  17. @RequestBody
  18. @RequestMapping
  19. @ResponseBody
  20. @RestController
  21. @Service
  22. @SpringBootApplication
  23. @Table
  24. @Transactional
  25. @Value