[Spring MVC]ControllerクラスでFormを受け取るサンプル

2021年6月24日

サンプルコード

@Controller
@RequestMapping("users")
public class UserController {

    @Autowired
    UserService userService;

    @ModelAttribute
    UserForm setUpForm() {
        return new UserForm();
    }


    @RequestMapping(value = "create", method = RequestMethod.POST)
    String create(@Validated UserForm form, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return list(model);
        }
        User user = new User();
        BeanUtils.copyProperties(form, user);
        userService.create(user);
        return "redirect:/users";
    }
}

 

SpringMVC

Posted by arkgame