SpringBoot入門


5-4 掲示板へのバリデーション機能の追加

④コントローラを修正します。

import org.springframework.validation.annotation.Validated; import org.springframework.validation.BindingResult; (途中略) /* 更新処理 */ @PostMapping("/create") @Transactional(readOnly=false) public ModelAndView save( @ModelAttribute("bbs") @Validated BulletinBoard bbs, BindingResult result) { if (result.hasErrors()) { ModelAndView mav = new ModelAndView(); mav.setViewName("bbs/new"); return mav; } Date date = new Date(); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd"); bbs.setDate(sdf1.format(date)); repos.saveAndFlush(bbs); return new ModelAndView("redirect:bbs/list"); }

@Validated エンティティの値をバリデーションチェックをします。 BindingResult チェック結果が格納されます。なお、必ず@Validatedの次に 書く必要があります。