How to show field error in a Spring Roo custom controller' form - spring

I am stuck with the following problem: error messages are not shown in the user form, but exist in the BindingResult. Need your assistance.
I am using the Spring Roo generated controller SignUpController
#RequestMapping("/signup/**")
#Controller
public class SignUpController {
List<ObjectError> signUpErrors;
#Autowired
private SignUpValidator validator;
#ModelAttribute("UserRegistrationForm")
public UserRegistrationForm formBackingObject() {
return new UserRegistrationForm();
}
#RequestMapping(params = "form", produces = "text/html")//, method = RequestMethod.GET)
public String createForm(Model uiModel) {
populateSignUpForm(uiModel, new UserRegistrationForm());
//uiModel.addAttribute("signUpErrors", signUpErrors);
return "signup/index";
}
#RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String create(#Valid UserRegistrationForm userRegistration,
BindingResult bindingResult, Model uiModel, HttpServletRequest request) {
validator.validate(userRegistration, bindingResult);
if (bindingResult.hasErrors()) {
populateSignUpForm(uiModel, userRegistration);
//uiModel.addAttribute("signUpErrors", bindingResult.getAllErrors());
return "signup/index";
}
...
for a custom form-backing object UserRegistrationForm
public class UserRegistrationForm {
#NotNull(message="Must be filled.")
#Size(min=6, max = 45)
private String login;
#Email
private String email;
#NotNull
#Size(min=6, max = 45)
, try to validate it using custom validator. I can show error messages to users, directly passing BindingResults into the jspx, and using the code as follows:
<c:if test="${signUpErrors.size()>0}">
<util:panel id="title" title="${title}">
<h2>
<spring:message code="signup_index_error" />
</h2>
<p></p>
<c:forEach var="err" items="${signUpErrors}">
<br />
<tr>
<td>${err.objectName} </td>
<td>${err.codes} </td>
<td>${err.arguments} </td>
<td>${err.defaultMessage} </td>
</tr>
</c:forEach>
</util:panel>
<p></p>
</c:if
But the standart Roo and Spring tags doesn't work:
<field:input field="login"
id="fc_.._UserRegistrationForm_login" required="true"
z="" />
<sf:errors path="login" cssStyle="error"></sf:errors>
<field:input field="email"
id="fc_.._UserRegistrationForm_email" required="true"
z="" />
<sf:errors path="*" cssStyle="error"></sf:errors>

Related

check if Team exists in the database or the input field is empty

It is necessary to check if the input fields for Team are empty, and whether there is such a Team in the repository.
If the field is not empty and there is no such Team, then you can create a new Team. If the field is empty or Team already exists, then give an error
AdminController
#Controller
public class AdminController {
#RequestMapping(value = "/admin/team", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public String addTeam(Model model, #ModelAttribute("teamForm") #Validated TeamForm teamForm,
BindingResult result, final RedirectAttributes redirectAttributes) {
System.out.println("addTeam invoked");
if (result.hasErrors()) {
return "/admin";
}
Team newTeam = new Team();
newTeam.setName(teamForm.getName());
newTeam.setUrl(teamForm.getUrl());
teamRepository.save(newTeam);
return "teamList";
}
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
model.addAttribute("teamForm",new TeamForm());
model.addAttribute("eventForm",new EventForm());
model.addAttribute("usersForm",new UsersForm());
return "admin";
}
admin.html
<form th:action="#{/admin/team}"
th:object="${teamForm}" method="POST">
Team name:
<input type="text" th:field="*{name}" />
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Incorrect Name</p>
<br/>
Url :
<input type="text" th:field="*{url}" />
<br/>
<input type="submit" value="Create Team" />
</form>

Field is always null in Spring Boot Postmapping method

I want to bind my HTML table with all fields to Java code in Spring Boot.
Therefore, I have annotated my method with Postmapping, too.
I was already able to show all the fields in Thymeleaf and I was also able to set the checkBox value ( true / false ) accordingly.
This is my Thymeleaf HTML code:
<form action="#" th:action="#{/mitarbeiterverwaltung}" th:object="${users}" method="post">
<fieldset>
<table border="1" align="center">
<thead>
<tr>
<!-- <th:text = "#{mitarbeiterverwaltung.active}>Active ( Tick ) / Passive</th>-->
<th>Active ( Tick ) / Passive</th>
<th>ID</th>
<th>Username</th>
<th>Anzeigename</th>
<th>Dienstnummer</th>
</tr>
</thead>
<tbody>
<tr th:each="user, itemStat : *{users}">
<td><input th:field="*{users[__${itemStat.index}__].isActive}"
th:checked="${user.isActive}"
class="checkBox"
type="checkBox"
name="checkBox"
/></td>
<td><input th:field="*{users[__${itemStat.index}__].id}"
readonly/></td>
<td><input th:field="*{users[__${itemStat.index}__].username}"
readonly/></td>
<td><input class="anzeigename"
type="text"
name="anzeigename"
th:field="*{users[__${itemStat.index}__].anzeigename}"
th:id="${itemStat.index}"
readonly/></td>
<td><input class="dienstnummer"
type="text"
name="dienstnummer"
th:field="*{users[__${itemStat.index}__].dienstnummer}"
th:id="${itemStat.index}"
readonly/></td>
</tr>
</tbody>
</table>
<br />
<div style="text-align:center;">
<input type="submit" id="submitButton" th:value="Speichern"/>
</div>
</fieldset>
And this is my Java code, where the field isActive of UserCreationDto is always null.
#PostMapping
public String updateActivePassiveUser(#ModelAttribute UserCreationDto userTableSettings,
#RequestParam("checkBox") String checkBoxName, BindingResult result, Model model, Errors errors) {
logger.info("Method {} called in {}", new Object() {}.getClass().getEnclosingMethod().getName(), this.getClass().getName());
if (errors.hasErrors()) {
logger.error("Error in {}", new Object() {}.getClass().getEnclosingMethod().getName());
return "error";
}
List<Benutzer> users = userManagementServiceImpl.getAllUsers();
userManagementServiceImpl.updateActivePassiveUser(1, 0);
return "redirect:/mitarbeiterverwaltung?success";
}
Here is a picture of the field in Java code where the method is annotated with #PostMapping
And so does my #RequestMapping look like:
This is my #RequestMapping method:
#RequestMapping
public String showUserManagement(Model model) {
logger.info("Method {} called in {}", new Object() {}.getClass().getEnclosingMethod().getName(), this.getClass().getName());
List<Benutzer> users = userManagementServiceImpl.getAllUsers();
userForm = userManagementServiceImpl.saveUserForm(users);
model.addAttribute("users", userForm);
return "mitarbeiterverwaltung";
}
My UserCreationDto where all the fields get added to a list:
public class UserCreationDto {
private List<User> users = new ArrayList<>();
public void addUser(User user) {
this.users.add(user);
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
And my simple POJO class with all the fields
#Data
public class User {
//#SafeHtml prevents XSS ( Cross-Site Scripting )
#SafeHtml
private String username;
private String password;
private String anzeigename;
private String dienstnummer;
private long id;
private Boolean isActive;
}
The other fields like anzeigename, dienstnummer, id, and username are filled within my Java code, however, isactive is always null.
Maybe, someone can tell me what I am doing wrong here.
Thank you very much in advance.
I think you have to many options set. You don't need th:checked:
<input th:field="*{users[__${itemStat.index}__].isActive}"
class="checkBox"
type="checkBox"
name="checkBox" />
I found another way now, but it is not really nice.
#PostMapping
public String updateActivePassiveUser(#Valid #ModelAttribute("userForm") UserCreationDto userTableSettings,
#RequestParam List<String> searchValues, BindingResult result, Model model, Errors errors) {
The field searchValues contains all the checkBoxes that are ticked.
This is my view:
<td><input type="checkbox"
name="searchValues"
th:value="${user.id}"
th:checked="${user.isActive}"
/>
Now, the only problem that I am having is how to update my column that is of type Boolean in Postgresql?
For accomplishing this task I call this:
userRepo.updateActivePassiveUser(new Boolean("False"), id);
#Modifying
#Query(value = "UPDATE benutzer SET active = :active WHERE id = :id", nativeQuery = true)
#Transactional
void updateActivePassiveUser(#Param("active") Boolean active, #Param("id") long id);
However, the value in my database never changes.
Maybe, someone could give me a last hint, please!

Spring form binding return null with many-2-one relationship

Here is the problem, when I try to submit form, user entity returns null.
Form is
<form:form class="g-form" modelAttribute="objView" id="userAssignmentForm">
<form:hidden path="id" value="${objView.id}"/>
${objView.user.id}
<div class="g-form-group required">
<label for="user">User</label>
<form:hidden id="user" path="user" value="${objView.user}"/>
<input type="text" value="${objView.user.userName}" readonly="true"/>
<input type="button" class="import-input" onclick="gImport.showImportUserForm()"/>
</div>
Controller is
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #ResponseBody
String create(
#ModelAttribute("objView") UserAssignmentView objView, BindingResult result,
SessionStatus status,
HttpServletRequest request) throws UnsupportedEncodingException {
UserAssignment obj = new UserAssignment();
obj.setUser(objView.getUser());
userAssignmentService.create(obj);
return "ok";
}
Model is below contains a view entity. What am I missing?
public class UserAssignmentView extends UserAssignment {
public UserAssignmentView() {
}
public UserAssignmentView(UserAssignment obj) {
setId(obj.getId());
setStatus(obj.getStatus());
setUser(obj.getUser());
}
}
And this is form view part of controller
#RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView form(HttpServletRequest request) {
UserAssignment obj = new UserAssignment();
Account account = AccountRegistry.getByHttpSession(request.getSession());
ModelAndView modelAndView = new ModelAndView("forms/userAssignmentForm");
modelAndView.addObject("objView", UserAssignmentWrapper.wrap(obj));
return modelAndView;
}
I could not solve since 3 days, how can I set user to userassignment?

Spring MVC #Valid not working when form is binded to a list

I am trying to do form validations on a Spring MVC form binded to a list of objects. The validations are not working. Please let me know if I am missing something
#Component
public class Customer{
#NotEmpty private int custId;
#NotEmpty private List<Order> orders;
//Getters & Setters...
}
#Component
public class Order{
#NotEmpty private String id;
#NotEmpty private String orderName;
//Getters & Setters...
}
//JSP - custFormBean is set as a model attribute
<form:form method="post" action="/submitOrder.htm" modelAttribute="custFormBean">
<table class="activity" width="600px" bgcolor="#FCF4DE">
<c:forEach items="${custForm.orders}" var="order" varStatus="status">
<tr>
<td>
<c:out value="${order.id}" />
</td>
</tr>
<tr>
<td>
<form:password path="orders[${status.index}].orderName" name="name" />
</td>
<td><form:errors path="orders[${status.index}].orderName" cssClass="errorMessage" /></td>
</tr>
</c:forEach>
<tr></tr>
<tr>
<td align="center" colspan="2">
<input type="submit" id="orderSubmit" class="formButton" value="OK" />
</td>
</tr>
</table>
</form:form>
//Controller
#Controller
#SessionAttributes("custFormBean")
public class CustomerController {
#RequestMapping(value = "/order.htm", method=RequestMethod.GET)
public String getOrder(ModelMap model, HttpServletRequest request) {
nextPage = "order"
try {
Customer custBean = custService.getCustOrders(...);
model.addAttribute("custFormBean", custBean);
} catch (ServiceException e) {
log.error("ServiceException when calling getChallengeQuestionLists", e);
}
return nextPage;
}
#RequestMapping(value = "/submitOrder.htm", method=RequestMethod.POST)
public String submitOrder(#Valid #ModelAttribute("custFormBean") Customer custBean, BindingResult result, Model model, HttpServletRequest request){
String nextPage = "success";
if(result.hasErrors()) {
//This is not working - The custBean is populated with the values entered in the form but if I leave the fields empty the validation is not kicking in.
log.debug("Validation errors...");
nextPage = "error";
}
return nextPage;
}
}
Please let me know if I am missing something
From Hibernate Validator javadoc of #NotEmpty:
Check that a String is not empty (not null and length > 0) or that a
Collection (or array) is not empty (not null and length > 0)
I think your list is not null and has length > 0 although all of them are blanks. So according to this the validator probably kicked it and yielded correct result.
You may need to write custom validator that checks there's at least a non-blank element in the list?

Spring MVC Form Validation - The request sent by the client was syntactically incorrect

I am trying to add form validations to a working application. I started by adding a NotNull check to Login Form. I am using Hibernate impl of Bean Validation api.
Here's the code I have written
#Controller
#RequestMapping(value="/login")
#Scope("request")
public class LoginController {
#Autowired
private CommonService commonService;
#Autowired
private SiteUser siteUser;
#InitBinder
private void dateBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(Date.class, editor);
}
#ModelAttribute
protected ModelMap setupForm(ModelMap modelMap) {
modelMap.addAttribute("siteUser", siteUser);
return modelMap;
}
#RequestMapping(value="/form", method = RequestMethod.GET)
public ModelAndView form(ModelMap map){
if (siteUser.getId() == null){
map.addAttribute("command",new SiteUser());
return new ModelAndView("login-form",map);
}else {
return new ModelAndView("redirect:/my-dashboard/"+siteUser.getId());
}
}
#RequestMapping(value="/submit", method=RequestMethod.POST)
public ModelAndView submit(#Valid SiteUser user, ModelMap map, BindingResult result){
if (result.hasErrors()) {
map.addAttribute("command", user);
System.out.println("Login Error block");
return new ModelAndView("login/form",map);
}
else {
User loggedInUser = commonService.login(user.getEmail(), user.getPassword());
if (loggedInUser != null) {
siteUser.setId(loggedInUser.getId());
siteUser.setName(loggedInUser.getName());
System.out.println("site user attr set");
}
return new ModelAndView("redirect:/my-dashboard/"+loggedInUser.getId());
}
}
}
The Model is
#Component
#Scope("session")
public class SiteUser {
private Integer id = null;
#NotNull
private String name = null;
private String email = null;
private String password = null;
private List<String> displayPrivList = null;
private List<String> functionPrivList = null;
// And the getters and setters
}
The JSP is
<c:url var="loginSubmitUrl" value="/login/submit"/>
<form:form method="POST" action="${loginSubmitUrl}">
<form:errors path="*" />
<div class="row">
<div class="span4">
</div>
<div class="span4">
<h3>Please Login</h3>
<label><span style="color:red">*</span>Email</Label><form:input path="email" type="text" class="input-medium" />
<label><span style="color:red">*</span>Password</Label><form:input path="password" type="password" class="input-medium" />
<br/>
<button type="submit" class="btn btn-primary">Login</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form:form>
I have added messages.properties and the annotation driven bean def in the context xml.
Other answers on the subject talk about form fields not getting posted. In my case, that's the expected behavior - that if I submit a blank form, I should get an error.
Please advise what am I missing?
I think this question had the same issue as yours
Syntactically incorrect request sent upon submitting form with invalid data in Spring MVC (which uses hibernate Validator)
which just points out
You have to modify the order of your arguments. Put the BindingResult result parameter always directly after the parameter with the #Value annotation
You need this: <form:errors path="email" cssClass="errors" />
Use the tag form:errors for each input with the same "path" name.
It is also possible to list all the error at the same time if you don't put a path.
Here, check an full example with sample code that you can download to learn how to do:
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/
Can you try changing the <form:form> by including the commandName to it like this
<form:form method="POST" action="${loginSubmitUrl}" commandName="user">

Resources