Spring Nested object is getting null while submitting form - spring

I am trying to post data with thymeleaf, command model has two nested objects, one is fetching data, while another is fetching null. I am confused, what is going on behind the scene, though using the same concept and code.
Please notice, I am getting data for People Object in logs, but not for Project Object, though using the same code. Please help.
Form Snippet.
<form th:fragment="form" method="post" th:object="${expense}" th:action="#{/createexpense}">
<input type="hidden" th:field="*{expenseId}" />
<div class="form-group">
<label class="col-md-4 control-label" for="textarea">Expense Description</label>
<div class="col-md-4">
<textarea class="form-control" id="textarea" th:field="*{description}" name="textarea">Expense Description</textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Amount</label>
<div class="col-md-4">
<input id="textinput" name="textinput" type="text" placeholder="Enter Amount" th:field="*{amount}" class="form-control input-md">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Project</label>
<div class="col-md-4">
<select class="form-control" id="sel1" th:field="*{project}">
<option th:each="project: ${projects}" th:value="${{project.projectId}}" th:text="${project.name}">1</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">People</label>
<div class="col-md-4">
<select class="form-control" id="sel1" th:field="*{people}" >
<option th:each="people: ${peoples}" th:value="${people.id}" th:text="${people.name}">1</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Expense Type</label>
<div class="col-md-4">
<select class="form-control" id="sel1" th:field="*{expenseType}">
<option th:each="exp: ${expenseTypes}" th:value="${exp}" th:text="${exp}">1</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Create
Expense</label>
<div class="col-md-4">
<input type="submit" class="btn btn- danger" value="Submit"/
</div>
</div>
Model Bean Class
#Data
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
#Entity
public class Expense {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long expenseId;
#Lob
private String description;
#OneToOne
#Cascade(CascadeType.ALL)
private People people;
private Double amount;
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdAt;
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updatedAt;
#ManyToOne
#Cascade(CascadeType.ALL)
private Project project;
#Enumerated(EnumType.STRING)
private ExpenseType expenseType;
public Expense(String description, Double expense) {
this.description = description;
this.amount = expense;
}
public Expense() {
}
public void setCreatedAt(Date createdAt) {
this.createdAt = new Date();
}
public Date getUpdatedAt() {
return updatedAt;
}
#PreUpdate
public void setUpdatedAt() {
this.updatedAt = new Date();
}
}
Controller Snippet
#PostMapping(path="/createexpense")
public Expense addExpense(#ModelAttribute("expense") Expense expense ,BindingResult result){
log.debug(expense.toString());
expense.setPeople(peopleService.getPeople(expense.getPeople().getId()));
expense.setProject(flatProjectService.getFlatProjectById(expense.getProject().getProjectId()));
return expenseService.createExpense(expense);
}
#GetMapping(path="/createexpense")
public ModelAndView addExpense(ModelAndView modal){
//adding projects list and people list in expense view
modal.addObject("projects", flatProjectService.getAllProjects());
modal.addObject("peoples", peopleService.getAllPeoples());
modal.setViewName("createexpense");
modal.addObject("expense", new Expense());
modal.addObject("expenseTypes", ExpenseType.values());
return modal;
}
Error Logs
2018-07-22 18:22:44.010 DEBUG 25500 --- [nio-8080-exec-5] c.d.b.controller.HomeController : Expense(expenseId=null, description=hello, people=People(id=2, name=Avinash, peopleType=null, phoneNo=9504974665, address=Beside Maa Clinic, expense=[], createdDate=2009-06-01 13:45:30.0, updatedDate=2009-06-01 13:45:30.0), amount=5000.0, createdAt=null, updatedAt=null, project=null, expenseType=PAID)
2018-07-22 18:22:44.090 ERROR 25500 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null

Looking at your HTML logic. I suspect issue is in Project Loop
You are defining th:field="*{project}"
but using as pro in option
Ideally it should be like this
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Project</label>
<div class="col-md-4">
<select class="form-control" id="sel1" th:field="*{project}">
<option th:each="project: ${projects}" th:value="${project.projectId}"
th:text="${pro.name}">1</option>
</select>
</div>
</div>

Related

Spring How to update database entites from dropdown lists thymeleaf

So I need to update the entities in my table with the selected values from dropdown lists from thymeleaf.
What I want to do is update the movie column based on the selections from dropdown list. But I have more than one dropdown list for each WeekMovie entity.
I cant figure out how to update them all.
My WeekMovies Class
#Entity
public class WeekMovies {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#ManyToOne
#JoinColumn(name="movie_id")
private Movie movie;
#ManyToOne
#JoinColumn(name="saloon_id")
private Saloon saloon;
//getter setters.
My Controller
#RequestMapping(value = "/update",method= RequestMethod.GET)
public String updateweekmovies(Model model){
List<WeekMovies> weekMoviesList = weekMovieService.findAll();
List<Movie> movieList= movieService.findAll();
model.addAttribute("weekMovieList",weekMoviesList);
model.addAttribute("movieList",movieList);
return "updateweekmovies";
}
#RequestMapping(value = "/update",method= RequestMethod.POST)
public String updateweekPost(Model model){
return "updateweekmovies";
}
My Thymeleaf
div class="container">
<div class="row">
<form class="form-horizontal" th:action="#{/week/update}" method="post"
enctype="multipart/form-data">
<fieldset>
<legend class="center-block">
Update Book Information<span style="font-size: small"> * is a
required field</span>
</legend>
<!-- category -->
<div class="form-group">
<label class="col-md-2 control-label" for="weekmovie">*
Category</label>
<div class="col-md-8">
<li th:each="weekmovie:${weekMovieList}">
<select th:value="${weekmovie.movie}" id="weekmovie" name="weekmovie" class="form-control">
<option value="" selected="selected" disabled="disabled">Please
select an option...</option>
<option th:each="movie:${movieList}" th:value="${movie.id}" th:text="${movie.title}"> </option>
</select>
</li>
</div>
</div>
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-8">
<button type="submit" class="btn btn-success">Update Movie</button>
</div>
</div>
</fieldset>
</form>
</div>

How to assign entity to another entity in a form using ThymeLeaf?

I am working on MVC Java project and am using Spring Boot with ThymeLeaf. The issue I have is, that when creating a Task, I want to select and save a User, that will be assign to the task. I managed to do the selection correctly, but am unable to save the selected user. It always saves without the User assigned.
Here is my Task entity class:
#Entity
public class Task extends BaseEntity {
private String name;
private String description;
private Date dateOfCreation;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dueDate;
#ManyToOne
private User assignee;
public Task() {
this.dateOfCreation = new Date(System.currentTimeMillis());
}
}
My User entity is as follows:
#Entity
public class User extends BaseEntity {
private String username;
private String password;
#OneToMany(mappedBy = "assignee")
private List<Task> assignedTasks;
}
Where BaseEntity contains
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
My controller function, that is responsible for my taskform.html is:
#RequestMapping("/new")
public String newTask(Model model){
model.addAttribute("task", new Task());
model.addAttribute("users", userService.getAllUsers());
return "task/taskform";
}
And my taskform.html looks like this:
<form class="form-horizontal" th:object="${task}" th:action="#{/task}" method="post">
<input type="hidden" th:field="*{id}"/>
<input type="hidden" th:field="*{version}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{name}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Description:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{description}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Description:</label>
<div class="col-sm-10">
<input type="date" th:value="*{dueDate}" th:field="*{dueDate}" id="dueDate" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Select user:</label>
<div class="col-sm-10">
<select class="form-control">
<option th:field="*{assignee}" th:each="assignee : ${users}" th:value="${assignee}" th:text="${assignee.username}">
</option>
</select>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
I am trying to pass the object from users list as the value, but it does not work Any idea, how to do it?
Showing the users works as expected:
Working frontend
Null is being assigned to assignee column, where the user should be assigned.
Null in H2 Database
EDIT
Here is my POST method from Task Controller:
#RequestMapping(method = RequestMethod.POST)
public String saveOrUpdate(Task task){
taskService.persistTask(task);
return "redirect:/task/list";
}

Unable to bind thymeleaf template and spring boot correctly

I am working on registration in spring boot with spring security and thymeleaf but for some reason the userForm.getUsername() gives null value during POST (see code below)
Person.java
#Entity#Table(name = "person")
public class Person {
#Id#Column(name = "username")
private String username;
#Column(name = "mobile")
private String mobile;
#JsonIgnore#Column(name = "password")
private String password;
#Transient#JsonIgnore
private String passwordConfirm;
#ManyToMany(cascade = CascadeType.ALL)#JoinTable(name = "bookandperson", joinColumns = #JoinColumn(name = "username"), inverseJoinColumns = #JoinColumn(name = "bookName"))
private List < Book > listOfBooks = new ArrayList < Book > ();
}
PersonController.java
#Controller
public class PersonController {
#Autowired
private UserService userService;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator userValidator;
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model, Principal user) {
if (user != null) {
return "redirect:/";
}
model.addAttribute("userForm", new Person());
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute Person userForm, BindingResult bindingResult, Model model) {
System.out.println(userForm.getUsername()); //This is giving null value
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
System.out.println("binding result has errors");
return "registration";
}
userService.save(userForm);
securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm());
return "redirect:/";
}
registration.html
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
<nav th:replace="common/navbar :: common-navbar"/>
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-6">
<form th:action="#{/registration}" method="post">
<div class="form-group row">
<label for="inputUsername" class="col-sm-2 col-form-label">Username</label>
<div class="col-md-6">
<input type="text" class="form-control" th:field="${userForm.username}" id="inputUsername" value="" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="mobile" class="col-sm-2 col-form-label">Mobile</label>
<div class="col-md-6">
<input type="text" class="form-control" th:field="${userForm.mobile}" id="inputMobile" placeholder="Mobile">
</div>
</div>
<div class="form-group row">
<label for="inputPassword" class="col-sm-2 col-form-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" th:field="${userForm.password}" id="inputPassword" placeholder="Password">
</div>
</div>
<div class="form-group row">
<label for="inputPasswordConfirm" class="col-sm-2 col-form-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" th:field="${userForm.passwordConfirm}" id="inputPasswordConfirm" placeholder="Password">
</div>
</div>
<div class="form-group row">
<div class="offset-2 col-sm-10">
<button type="submit" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" class="btn btn-primary">Submit</button>
</div>
</div>
<small th:text="${error}"></small>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</body>
I binded correctly using th:field="${userForm.username}" but unable to find what is the problem here.
you have to take the model object into the form as follows
<form action="#" th:action="#{/registration}" th:object="${userForm}" method="post">
and add the getters and setters to the Person class

Cannot process submitted foreign keys

There are 3 one-to-many relationships into an entity Pta :
#Entity
#Table(name = "pta")
public class Pta {
#Id()
#SequenceGenerator(name="s_pta", sequenceName="pta.s_pta", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_pta")
#Column(name="pta_code")
private Integer code;
#Column(name="pta_intitule")
private String lib;
#ManyToOne
#JoinColumn(name = "obj_code")
private Objectif objectif;
#ManyToOne
#JoinColumn(name = "struct_code")
private Structure structure;
#ManyToOne
#JoinColumn(name = "exer_code")
private Exer exercice;
public Pta() {
super();
}
public Pta(Integer code) {
super();
this.code = code;
}
// getters and setters
}
#Entity
#Table(name = "objectif")
public class Objectif {
#Id
#SequenceGenerator(name="s_objectif", sequenceName="pta.s_objectif", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_objectif")
#Column(name = "obj_code")
private int code;
#Column(name="obj_intitule")
private String lib;
#ManyToOne
#JoinColumn(name = "prog_code")
private Programme programme;
#ManyToOne
#JoinColumn(name = "nat_obj_code")
private NatureObjectif nature_objectif;
public Objectif() {
super();
}
public Objectif(int code) {
super();
this.code = code;
}
public Objectif(int code, String lib) {
super();
this.code = code;
this.lib = lib;
}
// getters and setters
}
#Entity
#Table(name = "structure")
public class Structure {
#Id()
#Column(name="struct_code")
private String code;
#Column(name="struct_sigle")
private String sigle;
#Column(name="struct_lib")
private String lib;
public Structure() {
super();
}
public Structure(String code) {
super();
this.code = code;
}
// getters and setters
}
#Entity
#Table(name = "exercice")
public class Exer {
#Id()
#Column(name="exer_code")
private String exerCode;
#Column(name="exer_lib")
private String exerLibelle;
public Exer(){
super();
}
public Exer(String exer_code) {
super();
this.exerCode = exer_code;
}
// getters and setters
}
I want to insert a record into the Pta.
controller for page jsp :
modelView.addObject("exercices",exerDao.list());
modelView.addObject("structures",structureDao.list());
HashMap<String, String> criteres = new HashMap<String, String>();
criteres.put("nat_obj_code", "DdP");
modelView.addObject("docs_perf", objectifDao.lireParCritere(criteres));
criteres.clear();
criteres.put("nat_obj_code", "ODD");
modelView.addObject("odds", objectifDao.lireParCritere(criteres));
criteres.clear();
criteres.put("nat_obj_code", "PRO");
modelView.addObject("produits", objectifDao.lireParCritere(criteres));
modelView.addObject("action", request.getContextPath().concat("/elaboration/savePtaEtDetails"));
modelView.addObject("pta_formulaire", new Pta());
return modelView;
jsp :
<form:form cssClass="form-horizontal" servletRelativeAction="${action}" method="post" commandName="pta_formulaire">
<form:hidden path="code"/>
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<label class="col-sm-4 control-label">Exercice</label>
<div class="col-sm-4">
<form:select path="exercice" cssClass="validate[required]">
<form:option value="" label=" -- Sélectionner -- "/>
<form:options items="${exercices}" itemValue="exerCode" itemLabel="exerLibelle" />
</form:select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Document de performance</label>
<div class="col-sm-4">
<form:select path="objectif" style="width:500px;" cssClass="validate[required]">
<form:option value="" label=" -- Sélectionner -- "/>
<form:options items="${docs_perf}" itemValue="code" itemLabel="lib" />
</form:select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">ODD</label>
<div class="col-sm-4">
<select id="odd" name="odd" style="width:500px;">
<option value=""> -- Sélectionner -- </option>
<c:forEach items="${odds}" var="odd">
<option value="${odd.code}">${odd.lib}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Axes du PND</label>
<div class="col-sm-4">
<select id="pnd" name="pnd" style="width:500px;" multiple></select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Programmes</label>
<div class="col-sm-4">
<select id="programme" name="programme" style="width:500px;" multiple></select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Effets</label>
<div class="col-sm-4">
<select id="effet" name="effet" style="width:500px;" multiple></select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Produits PMO</label>
<div class="col-sm-4">
<select id="produit" name="produit" style="width:500px;" multiple>
<option value=""> -- Sélectionner -- </option>
<c:forEach items="${produits}" var="produit">
<option value="${produit.code}">${produit.lib}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Actions PMO</label>
<div class="col-sm-4">
<select id="action" name="action" style="width:500px;" multiple></select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Activité</label>
<div class="col-sm-4">
<select id="activite" name="activite" style="width:500px;">
<option value=""> -- Sélectionner -- </option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Résultat attendu</label>
<div class="col-sm-4">
<select id="resultat" name="resultat" style="width:500px;">
<option value=""> -- Sélectionner -- </option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Indicateur</label>
<div class="col-sm-8">
<select id="indicateur" name="indicateur" style="width:500px;">
<option value=""> -- Sélectionner -- </option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<fieldset>
<legend><label class="control-label">Programmation physique</label></legend>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<label class="col-sm-1 control-label">T1</label>
<div class="col-xs-10">
<input class="form-control" type="text" name="t1">
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label class="col-sm-1 control-label">T2</label>
<div class="col-xs-10">
<input class="form-control" type="text" name="t2">
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label class="col-sm-1 control-label">T3</label>
<div class="col-xs-10">
<input class="form-control" type="text" name="t3">
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label class="col-sm-1 control-label">T4</label>
<div class="col-xs-10">
<input class="form-control" type="text" name="t4">
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<fieldset>
<legend><label class="control-label">Programmation financière</label></legend>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="col-sm-1 control-label">Montant</label>
<div class="col-xs-3">
<input class="form-control" type="text" name="progr_financiere">
</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label class="col-sm-4 control-label">Structure</label>
<div class="col-sm-4">
<form:select path="structure" style="width:230px;" cssClass="validate[required]">
<form:option value="" label=" -- Sélectionner -- "/>
<form:options items="${structures}" itemValue="code" itemLabel="lib" />
</form:select>
</div>
</div>
</div>
<input class="btn btn-primary btn-sm" type="submit"/>
</form:form>
In the controller target :
#RequestMapping(value = "/savePtaEtDetails", method = RequestMethod.POST)
public ModelAndView savePtaEtDetails(#ModelAttribute("pta_formulaire") Pta pta, #RequestParam String exercice, #RequestParam int objectif,
#RequestParam String structure) {
System.out.println("eeeeeeeeeeeeeeee");
return new ModelAndView("redirect:/accueil");
}
At runtime when submitting the form then I got the error The request sent by the client was syntactically incorrect. So what is wrong ?
I found it :) The solution was to not set the attribute in the constructor of the "master" entities :
public Exer(String exer_code) {
super();
}
public Structure(String code) {
super();
}
public Objectif(String code) {
super();
}

Spring Validation - Errors not displayed

I'm using a combination of Annotation validation and a Custom Validator
Object:
#Entity
#Table(name = "monitoringsystems")
public class MonitoringSystem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotNull(message = "Name must not be empty.")#Size(min=1, message="Name must not be empty.")
private String name;
#NotNull(message = "URL must not be empty.")#Size(min=1, message="Name must not be empty.")
private String url;
#NotNull(message = "Username must not be empty.")#Size(min=1, message="Name must not be empty.")
private String username;
#NotNull(message = "Password must not be empty.")#Size(min=1, message="Name must not be empty.")
private String password;
#NotNull(message = "Confirm Password must not be empty.")#Size(min=1, message="Name must not be empty.")
#Transient
private String passwordConfirm;
CustomValidator:
#Component
public class MonitoringSystemValidator implements Validator {
#Override
public boolean supports(Class<?> type) {
return MonitoringSystem.class.isAssignableFrom(type);
}
#Override
public void validate(Object o, Errors errors) {
MonitoringSystem monitoringSystem = (MonitoringSystem) o;
if(!monitoringSystem.getPassword().equals(monitoringSystem.getPasswordConfirm())){
errors.rejectValue("passwordConfirm", "Passwords are not equal.");
}
}
}
I initialize the custom validator in my controller and set the mapping for the form and the saving method.
Controller:
#Controller
public class MonitoringSystemController {
#Autowired
private MonitoringSystemValidator monitoringSystemValidator;
#InitBinder
public void dataBinding(WebDataBinder binder) {
binder.addValidators(monitoringSystemValidator);
}
#RequestMapping("/monitoringsystem/new")
public String newMonitoringSystem(Model model, HttpServletRequest request) {
MonitoringSystem monitoringSystem = new MonitoringSystem();
model.addAttribute("monitoringSystem", monitoringSystem);
request.getSession().setAttribute("anonymization", monitoringSystem.getAnonymization());
request.getSession().setAttribute("hosts", monitoringSystem.getHosts());
return "monitoringsystem/form";
}
#RequestMapping(value = "/monitoringsystem/save", method = RequestMethod.POST)
public String save(#Valid MonitoringSystem monitoringSystem, BindingResult result, HttpServletRequest request, Model model) {
if(result.hasErrors()){
model.addAttribute("monitoringSystem", monitoringSystem);
request.getSession().setAttribute("anonymization", request.getSession().getAttribute("anonymization"));
request.getSession().setAttribute("hosts", request.getSession().getAttribute("hosts"));
return "monitoringsystem/form";
}
//more code
In a first step I only want to change the CSS of my fields (I use bootstrap) so display the errors.
Form:
<form class="form-horizontal" th:modelAttribute="monitoringSystem" th:object="${monitoringSystem}" th:action="#{/monitoringsystem/save}" method="post">
<input type="hidden" th:field="*{id}"/>
<fieldset>
<legend>New Monitoring-System</legend>
<div class="form-group" th:classappend="${#fields.hasErrors('name')} ?: 'has-error has-danger'">
<label class="col-md-4 control-label" for="textinput">Systemname</label>
<div class="col-md-5">
<input th:field="*{name}" class="form-control input-md" type="text" />
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('url')} ?: 'has-error has-danger'">
<label class="col-md-4 control-label" for="textinput">URL</label>
<div class="col-md-5">
<input th:field="*{url}" class="form-control input-md" type="text" />
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('username')} ?: 'has-error has-danger'">
<label class="col-md-4 control-label" for="textinput">Username</label>
<div class="col-md-5">
<input th:field="*{username}" class="form-control input-md" type="text" />
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('password')} ?: 'has-error has-danger'">
<label class="col-md-4 control-label" for="textinput">Password</label>
<div class="col-md-5">
<input th:field="*{password}" class="form-control input-md" type="password" />
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('passwordConfirm')} ?: 'has-error has-danger'">
<label class="col-md-4 control-label" for="textinput">Confirm Password</label>
<div class="col-md-5">
<input th:field="*{passwordConfirm}" class="form-control input-md" type="password" />
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4">
<a th:href="#{/monitoringsystem}" class="btn btn-default btn-small">Cancel</a> <button id="singlebutton" name="singlebutton" class="btn btn-primary btn-small">Submit</button>
</div>
</div>
</fieldset>
</form>
My validation is working correctly. The form is only saved if my fields are not null, the size is greater 1 and the password match. If not, my controller redirects me to the form.
The problem is, that my css don't change. So there must be a problem with my view-code or the errorBinding is not passed correctly to the view. But I can't find my mistake.
There was an error in my if condition which add the errorclasses. I had to change ${#fields.hasErrors('url')} ?: 'has-error has-danger' to ${#fields.hasErrors('*{name}')} ? 'has-error has-danger'

Resources