Thymeleaf Could not bind form errors using expression "*" - spring

I use Spring-boot and Thymeleaf template engine and I try use th:classappend attribute for adding optional "has-error" class for < div > html tag using #fields.hasErrors('*') expression
<form method="POST" action="/registration" class="form-signin">
<h2 class="form-signin-heading">Create your account</h2>
<div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''">
<input name="username" type="text" class="form-control" placeholder="Username" autofocus="true"/>
<p class="alert alert-danger" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></p>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''">
<input name="password" type="text" class="form-control" placeholder="Password" autofocus="true"/>
<p class="alert alert-danger" th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></p>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''">
<input name="passwordConfirm" type="text" class="form-control" placeholder="Confirm your password" autofocus="true"/>
<p class="alert alert-danger" th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}"></p>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</form>
but I have this error
Could not bind form errors using expression "*". Please check this
expression is being executed inside the adequate context (e.g. a
with a th:object attribute)
my controller methods
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.save(userForm);
securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
what am I doing wrong?

I just add th:object="${userForm} attribute to my form element. And now it work fine!

Related

Model attribute inconsistent after form submission

I'm still trying to figure out what's happening on the backend here. Working with Spring Boot/Thymeleaf. I have a form template that updates a model attribute object on save. I'm trying to use the updated values on the backend, however it's inconsistent among my functions and I'm not sure why.
Thymeleaf template
<div layout:fragment="content" class="container">
<form action="#" th:action="#{/utility/exportbadges}" th:object="${badgeExport}" method="post">
<div class="form-group col-md-6">
<label class="col-form-label-sm">Badge type</label>
<select th:field="*{type}" class="form-control">
<option th:each="badgeType : ${T(org.myorg.myproject.model.badge.BadgeType).values()}"
th:value="${badgeType}"
th:text="${badgeType}">
</option>
</select>
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Use background?</label>
<input type="checkbox" th:field="*{background}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Mark preprinted?</label>
<input type="checkbox" th:field="*{preprinted}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Save to path (/tmp default):</label>
<input type="text" th:field="*{saveDir}" class="form-control" placeholder="/tmp">
</div>
<div class="form-group col-md-12 mt-2">
<div class="col-sm-10">
<input class="btn btn-primary" id="save" type="submit" value="Export" />
<input class="btn btn-secondary" type="reset" value="Reset" />
</div>
</div>
</form>
</div>
#RequestMapping(value = "/utility/exportbadges")
public String exportBadges(Model model) {
final BadgeExport badgeExport = new BadgeExport();
model.addAttribute("badgeExport", badgeExport);
return "utility/exportbadges";
}
POST method. The object is correct in this function. Any field that's edited in the form above reflects in this function. However, on redirect, the object is as if it only has default instantiation/has been unedited.
#RequestMapping(value = "/utility/exportbadges", method = RequestMethod.POST)
public String exportBadgeFlow(Model model,
#ModelAttribute("badgeExport") final BadgeExport badgeExport) {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir pre export: {}", badgeExport.getSaveDir());
switch(badgeExport.getType()) {
case "Attendee":
log.error("Attendee export not yet implemented");
break;
case "Vip":
return "redirect:exportbadges/vip-badges.pdf";
case "Specialty":
return "redirect:exportbadges/specialty-badges.pdf";
case "Staff":
return "redirect:exportbadges/staff-badges.pdf";
case "Guest":
return "redirect:exportbadges/guest-badges.pdf";
}
return "redirect:exportbadges";
}
Redirect function. Badge type will be null and saveDir will be /tmp as default instead of updated value in form.
#RequestMapping(value = "/utility/exportbadges/vip-badges.pdf")
public ResponseEntity<String> getAllVipBadgePdf(#ModelAttribute("badgeExport") final BadgeExport badgeExport) throws IOException {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir during export: {}", badgeExport.getSaveDir());
}

How tell the view an error has occured from controller? (Spring MVC)

How can I say trigger error/validation messages in the view from the controller in a better way? Currently, I do this by sending boolean attributes. For example, in creating a product, I have two possible errors. Invalid format of UPC of a product, or duplicate upc. I also have a validati
#RequestMapping("/createProduct")
public String createProduct(Model model, #RequestParam(value = "name") String name,
#RequestParam(value = "upc") String upc, #RequestParam(value = "category") String categoryName,
#RequestParam(value = "description") String description, #RequestParam(value = "price") BigDecimal price,
#RequestParam(value = "stock") int stock){
model.addAttribute("activeTab", 3);
if(Validator.invalidUpcFormat(upc)){
model.addAttribute("invalidFormat", true); //trigger for invalid format
return "management";
}
Category category = productService.getCategory(categoryName);
Product product = new Product(upc, category, name, description, price);
InventoryProduct inventoryProduct = new InventoryProduct(product, stock);
try {
managerService.add(inventoryProduct);
model.addAttribute("productCreated", true);
} catch (DuplicateProductException e) {
model.addAttribute("upc", upc);
model.addAttribute("duplicateProduct", true); // trigger for duplicate product
}
return "management";
}
And here is my view:
<div id="menu3"
class="tab-pane fade <c:if test="${activeTab == 3}">in active</c:if>">
<div class="container-fluid" style="padding: 2%;">
<div class="row">
<div class="col-md-12"
style="padding-left: 15%; padding-right: 15%;">
<c:if test="${productCreated}">
<div class="alert alert-success fade in">
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a> <strong>Success!</strong>
Product has been created!
</div>
</c:if>
<c:if test="${duplicateProduct}">
<div class="alert alert-warning fade in">
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a> <strong>Oh no!</strong>
Product with the UPC ${upc} already exists!
</div>
</c:if>
<c:if test="${invalidFormat}">
<div class="alert alert-warning fade in">
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a> <strong>Oops!</strong>
Invalid UPC format!
</div>
</c:if>
<form
action="${pageContext.request.contextPath}/manager/createProduct"
method="post">
<div class="form-group">
<label for="Name">Name </label> <input type="text" name="name"
class="form-control" required />
</div>
<div class="form-group">
<label for="UPC">UPC </label> <input type="number" name="upc"
class="form-control" required />
</div>
<div class="form-group">
<div class="form-group">
<label for="category">Category</label> <select
class="form-control" name="category" required>
<option selected disabled value="">SELECT CATEGORY</option>
<c:forEach items="${categories}" var="item">
<option>${item.getName()}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="5" name="description"></textarea>
</div>
<div class="form-group">
<label for="price">Price </label> <input type="number"
name="price" class="form-control" required />
</div>
<div class="form-group">
<label for="stock">Stock </label> <input type="number"
name="stock" class="form-control" required />
</div>
<button type="submit" class="btn btn-primary">Add
product</button>
</form>
</div>
</div>
</div>
</div>
Is there a better of doing this other than sending boolean triggers?
You could use Spring BindingResult. This is typical filled with the result of Binding and Validation results. But you can also add errors by hand.
But first you need to refactor your code, so that you use an single command/form-backing object instead of all the #Param values
public class CreateProductCommand {
private String name;
private String upc;
private String categoryName;
.... //other fields
public CreateProductCommand (){} //parameter less conturctor
Getter+Setter
}
Controller
#RequestMapping("/createProduct")
public ModelAndView createProduct(CreateProductCommand createProductCommand, BindingResult bindingResult) //Binding result must be the parameter direct next to the object that should been validated!!!
{
if (someustomValidationForUcpFail()) {
bindingResult.rejectValue("upc", //the field name of the invalid field
"error.Message.Key",
"Default Error Message");
}
if (bindingResult.hasErrors()) {
ModelMap model = new ModelMap();
model.add("createProductCommand", createProductCommand);
return new ModelAndView("createForm", model)
} else {
Product product = ...
return new ModelAndView("showProduct", "product", product)
}
}
jsp:
You need to use springs form and input tag:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:springForm="http://www.springframework.org/tags/form"
version="2.0">
....
<springForm:form action="<c:url value="/manager/createProduct">" method="POST" modelAttribute="createProductCommand">
<springForm:input path="name"/> <form:errors path="name" />
<springForm:input path="ucp"/> <form:errors path="ucp" />
....
</springForm:form>
....

Validation of wrapper in spring form

I've wrapped two objects I wanted to use in one form. Here is the wrapper class:
public class UserCustomer {
User user;
Customer customer;
//Getters and setters
//Constructors
Controller:
#Controller
public class RegisterController {
#RequestMapping("/register")
public String showRegister(Model model){
model.addAttribute("userCustomer", new UserCustomer(new User(), new Customer()));
return "register";
}
#RequestMapping(value="/doRegister", method = RequestMethod.POST)
public String doRegister(Model model, #Valid UserCustomer userCustomer, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "register";
}
System.out.println(userCustomer.getUser());
return "registered";
}
}
And the form:
<h3 class="new-models">For New Customers</h3>
<div class="register">
<sf:form method="post" action="${pageContext.request.contextPath}/doRegister" commandName="userCustomer">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<sf:errors path="customer.name" cssClass="alert-danger"/>
<sf:input name="name" type="text" path="customer.name"/>
</div>
<div>
<span>Last Name<label>*</label></span>
<sf:errors path="customer.surname" cssClass="alert-danger"/>
<sf:input name="surname" type="text" path="customer.surname"/>
</div>
<div>
<span>Email Address<label>*</label></span>
<sf:errors path="user.email" cssClass="alert-danger"/>
<sf:input name="email" type="text" path="user.email"/>
</div>
<div>
<span>Username<label>*</label></span>
<sf:errors path="user.username" cssClass="alert-danger"/>
<sf:input name="username" type="text" path="user.username"/>
</div>
<div class="clearfix"> </div>
<!--a class="news-letter" href="#">
<label class="sf:checkbox">
<!--sf:input type="checkbox" name="newsletter" path="customer.newsletter" checked=""/><i> </i>Sign Up for Newsletter</label>
</a-->
<a class="news-letter" href="#"></a>
</div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<sf:errors path="user.password" cssClass="alert-danger"/>
<sf:input name="password" type="password" path="user.password"/>
</div>
<div>
<span>Confirm Password<label>*</label></span>
<sf:input type="password" path=""/>
</div>
</div>
<div class="clearfix"> </div>
<div class="register-but">
<input type="submit" value="register">
<div class="clearfix"> </div>
</div>
</sf:form>
</div>
Everything seems to be working fine, except for validation. I don't really know how to make validation in this wrapper.
Example validation for email in User class:
#Pattern(regexp = ".*\\#.*\\..*")
I have solved myself this problem, it's way more simple than I have expected it would be.
Validation works simply by adding #Valid annotation above user and customer fields in this wrapper, so that spring knows to actually validate them "deeper".

Thymeleaf Binding list of objects

Here's my Object that I've retrieved from the DB:
#RequestMapping("/category/edit/{id}")
#org.springframework.transaction.annotation.Transactional
public ModelAndView displayCategoryList(#PathVariable("id")Integer id){
ModelAndView mav = new ModelAndView("category-form");
List<CatFeatGroup> catFeatGroupList = catFeatGroupService.findGroupsForCategory(id);
mav.addObject("catFeatGroupList",catFeatGroupList);
return mav;
}
Here's my form.
<form class="form-horizontal">
<div th:each="catFeatGroup,status : ${catFeatGroupList}" class="form-group">
<label>Position</label><input th:field="catFeatGroupList[${status.index}].position" th:value="${catFeatGroup.position}" />
<label>Name</label> <input name="catGroupList[${status.index}].name" th:value="${catFeatGroup.name}" />
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I need to use th:field to bind that object however this error shows up:
Could not parse as expression: "catFeatGroupList[${status.index}].position"
Add the "__" notation like this
<form class="form-horizontal">
<div th:each="catFeatGroup,status : ${catFeatGroupList}" class="form-group">
<label>Position</label><input th:field="*{catFeatGroupList[__${status.index}__].position}" th:value="${catFeatGroup.position}" />
<label>Name</label> <input data-th-name="*{catFeatGroupList[__${status.index}__].name}" th:value="${catFeatGroup.name}" />
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

While form submitting using ajax..getting Post not supported error ...don't know what is the error?

I am using form submission using AJAX in Spring MVC and Thymeleaf. When I try to submit it it shows
Post method is not supported
I can't figure out the mistake in my code:
<form class="form-horizontal" action="#" th:action="#{/teacher/teacherProfileUpdation}" th:object="${teacherProfileDetailsList}"
id="saveTeacherForm" method="POST" >
<br />
<div class="row">
<div class="col-lg-14 col-md-12">
<br />
<h5 style="margin-left: 15%;">Personal Details</h5>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher first name" id="txtTeacherFname" th:field="*{firstName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher middle name" id="txtTeacherMname" th:field="*{middleName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher last name" id="txtTeacherLname" th:field="*{lastName}" type="text" class="form-control" />
</div>
</div>
</div>
<div class="col-lg-14 col-md-12">
<div class="form-actions">
<input type="hidden" id="hdnStudentByIdInSchoolAdmin" value="0" />
<input type="button" class="btn btn-info pull-right" id="btnUpdateTeacherProfile" value="Save" />
</div>
</div>
</div>
JS:
saveTeacherProfile :function(){
$("#saveTeacherForm").ajaxForm({
success : function(status) {
alert("success");
},
}).submit();
}
Controller:
#RequestMapping(value = "/updateTeacherProfile", method = RequestMethod.POST)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
System.out.println("-----------"+teacherProfileDetails.getFirstName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getLastName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getMiddleName()+"-------------");
return "success";
}
You are posting the form, but most likely your Spring controller is not configured to accept POST requests. Try this in your server-side Controller class for this page:
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public void myControllerMethod()
{
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
//ur Logic
}

Resources