package com.example.sample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; 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; import org.springframework.web.servlet.ModelAndView; @Controller public class UserController { private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @RequestMapping("/signUp") public ModelAndView formUser(@ModelAttribute("formModel")User user, ModelAndView mav) { mav.setViewName("signUp"); mav.addObject("user", user); return mav; } @RequestMapping(value = "/signUp", method = RequestMethod.POST) public ModelAndView createUser(@ModelAttribute("formModel") @Validated User user, BindingResult result ,ModelAndView mav) { mav.setViewName("signUp"); if(!result.hasErrors()) { userService.saveUser(user); // ユーザー情報をデータベースに保存 mav.addObject("user", user); System.out.println("登録成功"); } else { System.out.println("登録失敗"); } return mav; } } | |< >|Java| package com.example.sample; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import lombok.Getter; import lombok.Setter; @Entity @Table(name="users") public class User { @Id @Column @GeneratedValue(strategy = GenerationType.IDENTITY) @NotNull private int id; @Getter @Setter @Column(name= "user_name", length = 255, nullable = false) @NotNull @NotBlank private String userName; @Getter @Setter @Column(length = 255, nullable = false) @NotNull @NotBlank private String password; } | |< >|Java| package com.example.sample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { private final UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public User saveUser(User user) { return userRepository.save(user); // ユーザー情報をデータベースに保存 } public Iterable<User> getAllEntities() { return userRepository.findAll(); } }