validate input in Thymeleaf - java

I have this input:
Masa: <input type="number" class="form-control form-text" name="masa"/>
<div class="text col-sm-12 error" th:if="${wzrost}" >
<p class="text text-center">
To pole jest wymagane
</p>
</div>
Wzrost: <input type="number" class="form-control form-text " name="wzrost"/>
<div class="text col-sm-12 error" th:if="${wzrost}" >
<p class="text text-center">
To pole jest wymagane
</p>
</div>
And this controller;
String x = String.valueOf(masa);
String y = String.valueOf(wzrost);
if(x==null ){
model.addAttribute("wzrost",true);
return"views/success";
}
if(y==null ){
model.addAttribute("wzrost",true);
return"views/success";
}
When I click form submit button I always get error nullpointerexception.
How do I validate input, so that when it is empty the message pops up

#PostMapping("/cal-bmi")
public String calculateBmiForm(Model model, Integer masa, Integer wzrost) {
String x = String.valueOf(masa);
String y = String.valueOf(wzrost);
if(x==null ){
model.addAttribute("wzrost",true);
return"views/success";
}
if(y==null ){
model.addAttribute("wzrost",true);
return"views/success";
}
}
ANd when i get a valu form masa and wzrost i check from null, i click submit alwas nullpointerexception
<form th:action="#{/cal-bmi}" method="post">
<ul class="gender-options">
<input id="man" type="radio" name="gender" value="male" required />
<label for="man">mężczyzna</label> ⁄
<input id="woman" type="radio" name="gender" value="female"/>
<label for="woman">kobieta</label>
</ul>
Masa: <input type="number" class="form-control form-text" required placeholder="(kg)" name="masa"/>
<!--<div class="text col-sm-12 error" th:if="${wzrost}">-->
<!--<p class="text text-center">-->
<!--To pole jest wymagane-->
<!--</p>-->
<!--</div>-->
Wzrost: <input type="number" class="form-control form-text " required placeholder="(cm)" name="wzrost"/>
<!--<div class="text col-sm-12 error" th:if="${wzrost}">-->
<!--<p class="text text-center">-->
<!--To pole jest wymagane-->
<!--</p>-->
<!--</div>-->
<input type="submit" class="col-lg-10 btn btn-primary" value="Oblicz"/>
</form>
Now i used required but is not good solution

It seems like you want to implement server side validation. For this the best approach is to use validators and its bindingResult. Steps to implement server side validation is
Have for model
public class PersonForm {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Use form model in html
<form action="#" th:action="#{/personForm}" th:object="${personForm}" method="post">
<table>
<tr>
<td><label th:text="#{label.name}+' :'"></label></td>
<td><input type="text" th:field="*{name}" /></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Generic Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
Have validator class
#Component
public class PersonFormValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return PersonForm.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "name", "field.name.empty");
PersonForm p = (PersonForm) target;
if (p.getName().equalsIgnoreCase("XXX")) {
errors.rejectValue("name", "Name cannot be XXX");
}
}}
Bind validator to controller and let spring do the magic.
#Controller
public class WebController {
#Autowired
PersonFormValidator personFormValidator;
#InitBinder("personForm")
protected void initPersonFormBinder(WebDataBinder binder) {
binder.addValidators(personFormValidator);
}
#PostMapping("/personForm")
public String checkPersonInfo(#Validated PersonForm personForm, BindingResult bindingResult, final RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
return "personForm";
}
redirectAttributes.addFlashAttribute("personResult", apiClientService.getPersonResult(personForm));
return "redirect:/spouseForm";
}
}

Related

How to re-render previous page when validating form

I have a controller that renders a chores.html page with various sorts of chores.
#GetMapping("/chores")
public String getDueChores(Model model)
{
var tomorrow = LocalDate.now().plusDays(1);
var chores = choreRepository.findByDueBefore(tomorrow);
model.addAttribute("choresDue", chores);
model.addAttribute("allChores", choreRepository.findAll());
model.addAttribute("chore", new Chore());
model.addAttribute("chores", new ArrayList<Chore>());
return "chores";
}
The same page also has a form for adding a new chore. Here's the controller method:
#PostMapping("/chores")
public String addNewChore(#ModelAttribute #Valid Chore chore)
{
chore.setDue(LocalDate.now().plusDays(chore.getDaysBetween()));
choreRepository.save(chore);
return "redirect:/chores";
}
Now I want to display the errors if the new chore is invalid.
Attempt 1:
#PostMapping("/chores")
public String addNewChore(#ModelAttribute #Valid Chore chore,
Errors errors)
{
if (errors.hasErrors())
{
return "chores";
}
chore.setDue(LocalDate.now().plusDays(chore.getDaysBetween()));
choreRepository.save(chore);
return "redirect:/chores";
}
This shows the error message, but sense it's not going through the logic in the GET controller method, all the other chores on the page don't get populated.
Attempt 2:
#PostMapping("/chores")
public String addNewChore(#ModelAttribute #Valid Chore chore,
Errors errors)
{
if (errors.hasErrors())
{
return "redirect:/chores";
}
chore.setDue(LocalDate.now().plusDays(chore.getDaysBetween()));
choreRepository.save(chore);
return "redirect:/chores";
}
This doesn't work because the error information is lost on the redirect, and the errors aren't displayed.
Could anyone point me in the right direction, please?
Here's chores.html, if it's relevant:
<body>
<h1>Due today...</h1>
<form method="post" th:action="#{/chore}" th:object="${chore}">
<ul>
<li th:each="chore: ${choresDue}">
<input type="checkbox" name="choreIds" th:value="${chore.id}"/>
<label th:text="${chore.name}"></label>
</li>
</ul>
<input type="submit" value="Mark Chores Complete">
</form>
<form method="post" action="#" th:action="#{/chores}" th:object="${chore}">
<input type="text" th:field="*{name}" placeholder="Chore name">
<span class="validationError"
th:if="${#fields.hasErrors('name')}"
th:errors="*{name}">Chore name is invalid</span>
<br>
<input type="text" th:field="*{daysBetween}" placeholder="Do chore every # days">
<span class="validationError"
th:if="${#fields.hasErrors('daysBetween')}"
th:errors="*{daysBetween}">Chore name is invalid</span>
<br>
<input type="submit" value="Add chore">
</form>
<hr>
<h1>All Chores</h1>
<form th:method="delete" th:action="#{/deleteChore}" th:object="${chore}">
<ul>
<li th:each="chore: ${allChores}">
<input type="checkbox" name="choreIds" th:value="${chore.id}"/>
<label th:text="${chore.name} + ' every ' + ${chore.daysBetween} + ' days'"></label>
</li>
</ul>
<input type="submit" value="Delete selected chores">
</form>
</body>
Solution is to add Errors to the Model.
#PostMapping("/chores")
public String addNewChore(#ModelAttribute #Valid Chore chore,
Errors errors,
Model model)
{
if (errors.hasErrors())
{
model.addAttribute("error", errors);
var tomorrow = LocalDate.now().plusDays(1);
var chores = choreRepository.findByDueBefore(tomorrow);
model.addAttribute("choresDue", chores);
model.addAttribute("allChores", choreRepository.findAll());
return "chores";
}
chore.setDue(LocalDate.now().plusDays(chore.getDaysBetween()));
choreRepository.save(chore);
return "redirect:/chores";
}

Spring MVC: Unable to bind data to my modelAttribute when trying to edit the form

I am trying to edit a submitted form but I am facing difficulties in doing so the problem is when I am submitting the form after editing null is being sent.I have been trying to get rid of this by myself but alas I have not been able to so.Please help me out.
My controller(only significant part)
#RequestMapping(value = "/registerstudentProcess", method = RequestMethod.POST)
public ModelAndView addStudent(HttpServletRequest request, #ModelAttribute("add_student") Student user) {
userService.registerStudent(user, request.getParameter("password"));
ModelAndView mav = new ModelAndView("addedstudent");
mav.addObject("adminsession");
mav.addObject("user", user);
mav.addObject("success_msg", user.getId() + " has been successfully added as an Student");
return mav;
}
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
public ModelAndView editstud(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("editstudent");
// mav.addObject("upd", new Student());
mav.addObject("adminsession");
mav.addObject("olduser", userService.editStudent(Integer.parseInt(request.getParameter("nayastud"))));
mav.addObject("batches", userService.getAllBatches());
return mav;
}
#RequestMapping(value = "/updatestud", method = RequestMethod.POST)
public ModelAndView updatestud(HttpServletRequest request, #ModelAttribute("olduser") Student stup) {
ModelAndView mav = new ModelAndView("addedstudent");
mav.addObject("adminsession");
mav.addObject("user", userService.updateStudent(stup));
mav.addObject("success_msg", stup.getId() + " has been successfully added as an Student");
return mav;
}
Model:Student.java
package project.ams.model;
public class Student {
private Integer id;
private String email;
private String name;
private String batch;
private String session;
private String address;
private String contact;
private String status;
//with proper getters and setters
}
addedstudent.jsp
<table class="table table-bordered table-condensed" align="center">
<tr>
<th colspan="2" style="text-align: center;">DETAILS</th>
<tr>
<tr>
<td><label>Id</label></td>
<td>${user.id}</td>
</tr>
<tr>
<td><label>Name</label></td>
<td>${user.name}</td>
</tr>
<tr>
<td><label>Email</label></td>
<td>${user.email}</td>
</tr>
<tr>
<td><label>Batch</label></td>
<td>${user.batch}</td>
</tr>
<tr>
<td><label>Session</label></td>
<td>${user.session}</td>
</tr>
<tr>
<td><label>Address</label></td>
<td>${user.address}</td>
</tr>
<tr>
<td><label>Phone Number:</label></td>
<td>${user.contact}</td>
</tr>
</table>
<table class="table table-condensed" align="center">
<tr>
<td>
<form:form id="editForm" action="editstud" method="post">
<input type="hidden" name="nayastud" value="${user.id}"/>
<button name="register"
class="btn btn-default">Edit Details</button>
</form:form>
</td>
<td>
<button onclick="location.href='admhome'"
class="btn btn-default">Back To Home</button></td>
</tr>
</table>
editstudent.jsp
<form:form id="regForm" modelAttribute="olduser" action="updatestud"
method="post">
<div class="form-group">
<form:label path="id">Enrollment Number</form:label>
<form:input path="id" name="id" id="id" class="form-control"
value="${olduser.id}" disabled="true" />
</div>
<div class="form-group">
<form:label path="name">Name</form:label>
<form:input path="name" name="name" id="name" class="form-control"
value="${olduser.name}" />
</div>
<div class="form-group">
<form:label path="email">Email</form:label>
<form:input path="email" name="email" id="email"
class="form-control" value="${olduser.email}" />
</div>
<div class="form-group">
<form:label path="batch">Batch</form:label>
<form:select path="batch" name="batch" id="batch"
class="form-control">
<option value="${olduser.batch}" selected></option>
<c:forEach var="bat" items="${batches}">
<form:option path="batch" value="${bat}">${bat}</form:option>
</c:forEach>
</form:select>
</div>
<div class="form-group">
<form:label path="session">Session</form:label>
<form:input path="session" name="session" id="session"
class="form-control" value="${olduser.session}" />
</div>
<div class="form-group">
<form:label path="address">Address</form:label>
<form:input path="address" name="address" id="address"
class="form-control" value="${olduser.address}" />
</div>
<div class="form-group">
<form:label path="contact">Phone</form:label>
<form:input path="contact" name="contact" id="contact"
class="form-control" value="${olduser.contact}" />
</div>
<div class="form-group">
<input type="hidden" name="password" value="Hello#123" />
<form:input type="hidden" path="status" name="status" value="a" />
</div>
<button id="register" name="register" class="btn btn-default">Update</button>
</form:form>
Edit 1
Added Screenshots(Sorry not able to post more screenshots due to reputation issues.)
Here I am changing the address and trying to update its value in the db.
Editing Student Info
Error here.Getting null object back from the edit page
when you are sending get request to fetch edit_student then you are passing value through request param and you should access this value using #PathVariable
or #RequestParam ..
<form:form id="editForm" action="editstud" method="post">
Expects a post handler
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
is defined to accept only GET requests.
Try changing edit student method to
#RequestMapping(value = "/editstud",method=RequestMethod.GET)
public ModelAndView editstud(#RequestParam String nayastud) {
ModelAndView mav = new ModelAndView("editstudent");
mav.addObject("adminsession");
mav.addObject("olduser", userService.editStudent(Integer.parseInt(request.getParameter("nayastud"))));
mav.addObject("batches", userService.getAllBatches());
return mav;
}

Why I am not able to insert and update?

<%#include file="../header.jsp" %>
<h1>Add Room</h1>
<form action="save" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Room Type</label>
<input type="text" name="roomType" placeholder="Enter Room Type" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Description</label>
<input type="text" name="roomDescription" placeholder="Enter Room Description" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Number</label>
<input type="number" name="roomNumber" placeholder="Enter Room Number" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="file" name="file" placeholder="Select Room Image" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="hidden" name="ro_id" value="${Room.ro_id}" placeholder="Select Room Image" required="required" class="form-control"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" value="submit">Save</button>
</div>
</form>
<%#include file="../footer.jsp" %>
Here is my edit jsp from where I update my database
Edit Room Jsp for updating for database using Room controller and I get
"Column Image"cannot be null
<%#include file="../header.jsp" %>
<h1>Edit Room</h1>
<form action="${SITE_URL}/admin/room/save" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Room Type</label>
<input type="text" name="roomType" value="${Room.room_type}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Description</label>
<input type="text" name="roomDescription" value="${Room.room_description}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Number</label>
<input type="number" name="roomNumber" value="${Room.room_number}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="file" name="file" link src="D:/Hotels/uploadedImage/${Room.image}" required="required" class="form-control" />
</div>
<form:hidden path="${Room.ro_id}" />
<input type="text" value="${Room.ro_id}" name="id"/>
<div class="form-group">
<button type="submit" class="btn btn-success" value="editroom/ro_id" >Save</button>
</div>
</form>
<%#include file="../footer.jsp" %>
When I try to update the page i get Column"image" cannot be null
and when I try to add it "Required int parameter #id is not present
/**
*
* #author
*/
#Controller
#RequestMapping(value = "/admin/room")
public class Roomcontroller {
#Autowired
private RoomService roomService;
#RequestMapping(method = RequestMethod.GET)
public String index(ModelMap map) throws SQLException {
map.addAttribute("Room", roomService.getAll());
return "admin/room/index";
}
#RequestMapping(value = "/addroom", method = RequestMethod.GET)
public String addRoom() throws SQLException {
return "admin/room/addroom";
}
#RequestMapping( value = "/editroom/{ro_id}", method = RequestMethod.GET )
public #ResponseBody ModelAndView edit(#PathVariable("ro_id") int ro_id) throws SQLException {
ModelAndView mv = new ModelAndView("admin/room/editroom");
mv.addObject("Room", roomService.getById(ro_id));
return mv;
}
#RequestMapping(value = "/deleteroom/{ro_id}", method = RequestMethod.GET)
public String delete(#PathVariable("ro_id") int ro_id) throws SQLException {
roomService.delete(ro_id);
return "redirect:/admin/room";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#RequestParam("roomType") String roomType,#RequestParam("id") int id,
#RequestParam("roomDescription") String roomDescription, #RequestParam("roomNumber") int roomNumber
,#RequestParam("file") MultipartFile multipartFile,HttpServletRequest req) throws SQLException, IOException {
Room attributes
Room room = new Room();
room.setRo_id(id);`
room.setRoom_type(roomType);
room.setRoom_description(roomDescription);
room.setRoom_number(roomNumber);
// TO DO : Save room, fetch the id of saved room and set it through
// setter in above object.
System.out.println(room.getRo_id());
if(room.getRo_id()==0){
System.out.println(room.getRo_id());
String serverRootPath = req.getServletContext().getRealPath("");
System.out.println(serverRootPath);
// You can change the directory.
File roomImageDirectory = new File("D:\\Hotels\\uploadedImages");
if (!roomImageDirectory.exists()) {
roomImageDirectory.mkdirs();
}
String[] fileNameToken = multipartFile.getOriginalFilename().split("\\.");
// You can change file name to be saved.
String newFileName = "room-" + room.getRoom_number() + "." + fileNameToken[fileNameToken.length - 1];
File roomImage = new File(roomImageDirectory, "/" + newFileName);
roomImage.createNewFile();
multipartFile.transferTo(roomImage);
room.setImage(newFileName);
roomService.insert(room);
}
else
{
roomService.update(room);
}
return "redirect:/admin/room";
}
}

Ajax call error in Spring MVC

I have a form where I add the customer's informations. This informations are passed to #Controller by an Ajax call.
Customer.java
public class Customer {
private String name;
private String fiscalCode;
private String vat;
private String telephone;
private String webSite;
private String sector;
private String address;
//Below there are constructor and getter/setter methods
Above the form there is:
<c:set var="serverUrl" value="${pageContext.servletContext.contextPath}"/>
<script>
var serverUrl = '${serverUrl}';
</script>
Form in the jsp
<form>
<div class="form-group">
<input id="nameCustomer" class="form-control" type="text" placeholder="Name customer">
</div>
<div class="form-group">
<input id="fiscalCode" class="form-control" type="text" placeholder="Fiscal code">
</div>
<div class="form-group">
<input id="vat" class="form-control" type="number" placeholder="VAT number (if available)">
</div>
<div class="form-group">
<input id="telephone" class="form-control" type="tel" placeholder="Phone number">
</div>
<div class="form-group">
<input id="website" class="form-control" type="email" placeholder="Customer's Website (if available)">
</div>
<div class="form-group">
<input id="address" class="form-control" type="text" placeholder="Customer's Address">
</div>
<div class="form-group">
<input id="sector" class="form-control" type="text" placeholder="Sector">
</div>
<button id="createCustomer" type="button" class="btn btn-success" style="text-align: center">Save</button>
</form>
Ajax call (the link to this ajax call code is below the form)
$("#createCustomer").click(function () {
alert("createCustomer");
alert(serverUrl);
var nameCustomer = $("#nameCustomer").val();
var fiscalCode = $("#fiscalCode").val();
var vat = $("#vat").val();
var telephone = $("#telephone").val();
var website = $("#website").val();
var address = $("#address").val();
var sector = $("#sector").val();
alert(address);
$.ajax({
url: serverUrl + "/addCustomer",
dataType: 'text',
data: {name: nameCustomer,
fiscalCode: fiscalCode,
vat: vat,
telephone: telephone,
webSite: website,
address: address,
sector: sector},
success: function (data) {
$("#customerAdded").modal('show');
},
error: function (xhr, error, exception) {
$("#errorCustomer").modal('show');
}
});
});
Controller
#Controller
public class CustomerController {
#RequestMapping("addCustomer")
public void addCustomer(#ModelAttribute Customer customer){
JOptionPane.showMessageDialog(null, customer.toString());
}
Chrome gives me this error:
http://localhost:8080/ReportVisitaWeb/addCustomer?name=gdg&fiscalCode=dfgdfg&vat=&telephone=dfgg&webSite=dfggf&address=dfgddf&sector=gdg Failed to load resource: the server responded with a status of 404 (Not Found)
Why?
You are not mapping the request "addCustomer" correctly. Edit your CustomerController as below:
#Controller
public class CustomerController {
#RequestMapping("/addCustomer")
public void addCustomer(#ModelAttribute Customer customer){
JOptionPane.showMessageDialog(null, customer.toString());
}
}

Spring MVC Not Displaying Form Errors

Here's my controller
#RequestMapping(value = "/save",method = RequestMethod.POST)
public ModelAndView saveUserAccount(#ModelAttribute("account") UserAccountForm userAccount, BindingResult result){
AddUserValidator userValidator = new AddUserValidator();
userValidator.validate(userAccount,result);
boolean hasErrors = result.hasErrors();
if(hasErrors){
return render(ADD_USER_VIEW)
.addAttr("ACCOUNT_ROLES", Arrays.asList(AccountRole.values()))
.addAttr("TENANTS",tenantInfoService.getAll())
.addAttr("errors",result)
.addAttr("account",userAccount).toMav();
}
return render(ADD_USER_VIEW)
.addAttr("ACCOUNT_ROLES", Arrays.asList(AccountRole.values()))
.addAttr("TENANTS",tenantInfoService.getAll())
.addAttr("account",new UserAccountForm())
.toMav();
}
Here's the render library That I have created.
public class RenderMavBuilder {
private final ModelAndView mav;
public static RenderMavBuilder render(String viewname){
RenderMavBuilder target = new RenderMavBuilder(viewname);
return target;
}
public RenderMavBuilder addAttr(String attrName, Object value){
mav.addObject(attrName, value);
return this;
}
public RenderMavBuilder addAttr(Object value){
mav.addObject(value);
return this;
}
public RenderMavBuilder addAttrs(Map<String , ?> attrs){
mav.addAllObjects(attrs);
return this;
}
private RenderMavBuilder(String viewName){
this.mav = new ModelAndView(viewName);
}
public ModelAndView toMav(){
return mav;
}
}
Here's my validator
Here's my form.
<div class="col-md-6 centered">
<form:errors path="*" />
<form:form commandName="account" method="post" action="${pageContext.request.contextPath}/user/save">
<!-- Username -->
<div class="col-xs-12 form-group">
<label class="control-label">Username</label>
<form:input path="username" type="text" class="form-control" />
</div>
<!-- Password -->
<div class="col-xs-12 form-group">
<label class="control-label">Password</label>
<form:password path="password" class="form-control"/>
</div>
<!-- Password -->
<div class="col-xs-12 form-group">
<label class="control-label">Password</label>
<form:password path="retypedPassword" class="form-control"/>
</div>
<!-- First Name -->
<div class="col-xs-12 form-group">
<label class="control-label">First Name</label>
<form:input path="firstName" type="text" class="form-control"/>
</div>
<!-- First Name -->
<div class="col-xs-12 form-group">
<label class="control-label">Last Name</label>
<form:input path="lastName" type="text" class="form-control"/>
</div>
<!-- User Role -->
<div class="col-xs-12 form-group">
<label class="control-label">User Role</label>
<form:select path="accountRole" class="form-control">
<form:options items="${ACCOUNT_ROLES}"/>
</form:select>
</div>
<!-- Branch Designation -->
<div class="col-xs-12 form-group">
<label class="control-label">Designated Branch</label>
<select path="tenantId" items="${TENANTS}" class="form-control">
<c:forEach var="branch" items="${TENANTS}">
<option value="${branch.id}">${branch.tenantDescription}</option>
</c:forEach>
</select>
</div>
<!-- Button -->
<div class="col-md-12 form-group">
<button class="form-control btn btn-primary submit-button" type="submit">Save New User <i class="fa fa-check-square-o"></i></button>
</div>
</form:form>
On my controler the binding result has errors. however, the error is not being displayed on the view, what am I missing?
The problem is the way you are constructing your ModelAndView, you should use the Errors object to construct it. Use Errors.getModel() to obtain the underlying Map that represents the model and use that, next to the view name, to construct the ModelAndView.
Next to that for your other model attributes you should simply add #ModelAttribute annotated methods to retrieve those. I would also suggest adding a GET based method which you redirect to after successful submit.
Your helper class seems also rather pointless as doing it simply inside your controller would simplify your code (imho).
Your controller could look something along these lines.
#RequestMapping(value = "/save",method = RequestMethod.POST)
public ModelAndView saveUserAccount(#ModelAttribute("account") UserAccountForm userAccount, BindingResult result){
AddUserValidator userValidator = new AddUserValidator();
userValidator.validate(userAccount,result);
boolean hasErrors = result.hasErrors();
return new ModelAndView(hasErrors ? ADD_USER_VIEW, "redirect:/add", errors.getModel());
}
#RequestMapping(value="/add")
public String addUserAccount(Model model) {
model.addObject("account", new UserAccountForm());
return ADD_USER_VIEW;
}
#ModelAttribute
public void referenceData(Model model) {
model.addObject("ACCOUNT_ROLES", Arrays.asList(AccountRole.values()));
model.addObject("TENANTS",tenantInfoService.getAll());
}

Categories