くらげになりたい。

くらげのようにふわふわ生きたい日曜プログラマなブログ。趣味の備忘録です。

SpringMVC/SpringBootのControllerチートシート[随時更新予定]

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 Boot 2 プログラミング入門

Spring Boot 2 プログラミング入門

参考にしたサイト様