1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package net.sourceforge.mystique.application;
22
23 import net.sourceforge.mystique.domain.entity.Project;
24 import net.sourceforge.mystique.domain.repository.ProjectRepository;
25 import net.sourceforge.mystique.domain.repository.RepositoryException;
26 import net.sourceforge.mystique.infrastructure.validation.ProjectValidator;
27
28 import org.springframework.beans.factory.annotation.Autowired;
29 import org.springframework.dao.DataIntegrityViolationException;
30 import org.springframework.stereotype.Controller;
31 import org.springframework.ui.Model;
32 import org.springframework.validation.BindingResult;
33 import org.springframework.validation.ValidationUtils;
34 import org.springframework.web.bind.WebDataBinder;
35 import org.springframework.web.bind.annotation.InitBinder;
36 import org.springframework.web.bind.annotation.ModelAttribute;
37 import org.springframework.web.bind.annotation.RequestMapping;
38 import org.springframework.web.bind.annotation.RequestMethod;
39 import org.springframework.web.bind.annotation.SessionAttributes;
40 import org.springframework.web.bind.support.SessionStatus;
41
42
43
44
45 @Controller
46 @RequestMapping("/project/add.xhtml")
47 @SessionAttributes(types = Project.class)
48 public class AddProjectForm {
49
50 @Autowired
51 private ProjectRepository projectRepository;
52
53 @InitBinder
54 public void setAllowedFields(WebDataBinder binder) {
55
56 binder.setDisallowedFields(new String[] { "id" });
57
58 }
59
60 @RequestMapping(method = RequestMethod.GET)
61 public String setupForm(Model model) {
62
63 model.addAttribute(new Project());
64
65 return "project.form";
66
67 }
68
69 @RequestMapping(method = RequestMethod.POST)
70
71 public String processSubmit(@ModelAttribute Project project, BindingResult result, SessionStatus status)
72 throws RepositoryException {
73
74 ValidationUtils.invokeValidator(new ProjectValidator(), project, result);
75 if (result.hasErrors()) {
76 return "project.form";
77 }
78
79 try {
80 projectRepository.store(project);
81 } catch (DataIntegrityViolationException e) {
82 result.reject(e.getMessage(), new Object[] { project.getName() }, null);
83 return "project.form";
84 }
85
86 status.setComplete();
87
88 return "redirect:list.xhtml";
89
90 }
91
92 }