「Spring MVC」@ModelAttribute、@ControllerAdvice、@Controllerアノテーションを利用する

1.コントローラ

@Controller
@ControllerAdvice
public class UserController {

    private Map<Long, User> userMap = new HashMap<>();

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public String addUser(
      @ModelAttribute("user") User user,
      BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "error";
        }
        model.addAttribute("userName", user.getuserName());
        model.addAttribute("userId", user.getuserId());

        userMap.put(user.getuserId(), user);

        return "userView";
    }

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("msg", "this is test data");
    }
}

2.Modelクラス

@XmlRootElement
public class User {

    private long userId;
    private String userName;

    public User(long userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }

   //some code
}

3.JSP画面

<form:form method="POST" action="/addUser"
  modelAttribute="user">
    <form:label path="userName">ユーザ名:</form:label>
    <form:input path="userName"/>

    <form:label path="userId">ユーザ番号:</form:label>
    <form:input path="userId"/>

    <input type="submit" value="Submit"/>
</form:form>

 

Software

Posted by arkgame