RequestMappingとかいろいろあるので、整理がてらφ(..)メモメモ
随時更新予定。
@RequestMapping
// シンプルなの @RequestMapping(value = "/hoge", method = RequestMethod.GET) @RequestMapping(value = "/hoge", method = RequestMethod.POST) @RequestMapping(value = "/hoge", method = RequestMethod.DELETE) // URL複数 @RequestMapping(value = {"/hoge", "/fuga"}, method = RequestMethod.GET) // Method属性が複数 @RequestMapping(value = "/hoge", method = {RequestMethod.GET,RequestMethod.POST}) //コンテンツタイプを指定(例では、application/xmlを指定) @RequestMapping(value = "/hoge", produces = MediaType.APPLICATION_XML_VALUE) public String hoge()
@RequestMapping + @RequestParam
// '/hoge?value=true'のとき、引数valueにtrueが入ってくる // `required`がfalseの時は'/hoge'も許容。引数valueはnullになる @RequestMapping(value = "/hoge", method = RequestMethod.GET) public String index(@RequestParam(required = false) Boolean value){ }
@RequestMapping + @PathVariable
// '/hoge/1'の時に、引数userIdに1が入ってくる @RequestMapping(value = "/hoge/{userId}", method = RequestMethod.GET) public String index(@PathVariable(value = "userId") Long userId) {
Controller引数
// ViewにAttributeを渡すときは「Model」 public String index(Model model) { model.addAttribute("message", "this is message"); return "hoge/index"; } // リダイレクト先ににAttributeを渡すときは「RedirectAttributes + addFlashAttribute」 public String index(RedirectAttributes model) { model.addFlashAttribute("message", "this is message"); return "redirect:hoge/index"; }
Controller引数 + UserDetails
// 認証情報を取得するときには、「Principal」 public String index(Principal principal, Model model) { Authentication authentication = (Authentication) principal; UserDetails user = (UserDetails) authentication.getPrincipal(); return "hoge/index"; }
Controller引数 + Form
// Fromを使うときは「@Valid @ModelAttribute」も一緒に。@Validの結果は「BindingResult」に public String indexForm(@Valid @ModelAttribute HogeForm form, BindingResult result, Model model) { if (!result.hasErrors()) { } else { model.addAttribute("message", "has error in HogeForm"); } return "hoge/index"; }
以上!!
参考になる書籍

Spring徹底入門 Spring FrameworkによるJavaアプリケーション開発
- 作者: 株式会社NTTデータ
- 出版社/メーカー: 翔泳社
- 発売日: 2016/07/21
- メディア: 大型本
- この商品を含むブログ (1件) を見る

- 作者: 掌田津耶乃
- 出版社/メーカー: 秀和システム
- 発売日: 2017/12/20
- メディア: 単行本
- この商品を含むブログを見る

- 作者: 掌田津耶乃
- 出版社/メーカー: 秀和システム
- 発売日: 2018/01/30
- メディア: 単行本
- この商品を含むブログを見る

はじめてのSpring Boot―スプリング・フレームワークで簡単Javaアプリ開発 (I・O BOOKS)
- 作者: 槙俊明
- 出版社/メーカー: 工学社
- 発売日: 2016/09/01
- メディア: 単行本
- この商品を含むブログ (1件) を見る