「Spring MVC」Controllerを作成するサンプル
書式
@Controller
public classクラス名
@ModelAttribute
public Form名 setupフォーム名
使用例
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller //アノテーションの付与 public class UserController { @ModelAttribute // Modelの属性名を指定 public UserForm setupUserForm() { UserForm form = new UserForm(); return form; } //@RequestMappingアノテーション @RequestMapping public String index(Model model) { return "user/top"; } @RequestMapping(value = "user/create", method = RequestMethod.POST) public String create(@Validated UserForm form, BindingResult result, Model model) { // 入力エラー確認 if (result.hasErrors()) { return "user/top"; } model.addAttribute("name", form.getName()); //Viewを渡す return "user/create"; } }