Value is not coming in back end in spring Hibernate - spring

Hi all i am trying to create one page which have relationship between client and Discharge. I have define one combo box which populate data of client form model and i want that client id in Discharge table but i am not getting value in back end if you inspect it in front end its look good but its null in back end so pls help me to solve this problem.
Here the code,
DischargeCard.java
#Entity
#Table(name = "Discharge_card")
public class DischargeCard {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
private int DischargeId;
#ManyToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "Client_id")
private Client Client_id;
#Column(name = "IPDNo")
private String ipdno;
#Column(name = "DOA")
private Date DOA;
#Column(name = "DOO")
private Date DOO;
#Column(name = "DOD")
private Date DOD;
#Column(name = "DOB")
private Date DOB;
#Column(name = "Age")
private int age;
#Column(name = "Sex")
private String sex;
#Column(name = "Phone")
private String phone;
#Column(name = "Address")
private String Address;
#Column(name = "Diagnosis")
private String diagnosis;
#Column(name = "Treatment")
private String treatment;
#Column(name = "Anesthesia")
private String anesthesia;
#Column(name = "Clinical_Presentation")
private String clinical_presentation;
#Column(name = "Investigation")
private String investigation;
#Column(name = "Given_Treatment")
private String given_treatment;
#Column(name = "Advice_on_Discharge")
private String advice;
< generates setter / getter >
Client.java
#Entity
#Table(name = "CLIENT")
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
int clientId;
#NotEmpty(message = "Please Enter Client Name..." )
#Column(name = "Name")
String clientName;
#Column(name = "ContactName")
String contactName;
#NotEmpty(message = " Please Enter Client Address...")
#Column(name = "Address")
String clientAddress;
#NotEmpty(message = "Please Enter Client Phone...")
#Size (min = 10)
#Pattern (regexp = "[0-9]*")
#Column(name = "Phone")
String phone;
#Email (message = "Please Enter Proper Email Address of Client...")
#Column(name = "Email")
String email;
#NotEmpty (message = "Please Enter Client City...")
#Column(name = "City")
String city;
#NotEmpty (message = "Please Enter Client Zip Code...")
#Size (min = 6)
#Pattern (regexp = "[0-9]*")
#Column(name = "Zip")
String zip;
#NotEmpty(message = "Please Enter Client State...")
#Column(name = "State")
String state;
#NotEmpty (message = "Please Enter Client Country...")
#Column(name = "Country")
String country;
#Column(name = "Private")
String privateNote;
#Column(name = "Other")
String otherNote;
#ManyToOne
#JoinColumn(name = "Company_id")
private Company company;
#OneToMany(mappedBy = "Client_id")
private Set<Invoice> invoice;
#OneToMany(mappedBy = "Client_ID")
private Set<Estimate> estimate;
#OneToMany(mappedBy = "Client_id")
private Set<DischargeCard> discharges;
< generated setter / getter >
DischargeCardController.java
#Controller
public class DischargeCardController {
#Autowired
DischargeCardService ds;
#Autowired
ClientService service;
#RequestMapping(value = "/dishcharge", method = RequestMethod.GET)
public String showClientDetailsPage(Model m, HttpServletRequest req) {
m.addAttribute("dischargecard", new DischargeCard());
m.addAttribute("actionURL", "saveCard");
List<Client> obj = service.getAll("");
m.addAttribute("clientList", obj);
List<String> clientlist = new ArrayList<>();
for(Client c : obj)
{
clientlist.add(c.getClientName().toString());
}
m.addAttribute("client_name_list",clientlist);
return "dischargeCard";
}
#RequestMapping(value = "/saveCard", method = RequestMethod.POST)
public String saveCompanyDetails(#ModelAttribute("DischargeCard")DischargeCard dc, BindingResult result,
HttpServletRequest req) {
String redirectTo = "";
/*if(result.hasErrors())
{
redirectTo = "dischargeCard";
return redirectTo;
}
else
{*/
ds.saveData(dc);
redirectTo = "redirect:dishcharge";
return redirectTo;
}
#RequestMapping(value = "/searchDischargeCard", method = RequestMethod.GET)
public ModelAndView showUsersPage() {
ModelAndView mv = new ModelAndView("searchDischargeCard");
List<Client> obj = service.getAll("");
mv.addObject("clientList", obj);
List<String> clientlist = new ArrayList<>();
for(Client c : obj)
{
clientlist.add(c.getClientName().toString());
}
mv.addObject("client_name_list",clientlist);
mv.addObject("DischargeList",ds.getAll(""));
return mv;
}
}
DischargeCard.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<jsp:include page="header.jsp"></jsp:include>
<jsp:include page="menu.jsp"></jsp:include>
<!-- BEGIN Content -->
<div id="main-content">
<!-- BEGIN Page Title -->
<div class="page-title">
<div>
<h1>
<i class="fa fa-file-o"></i> Add Dishcharge Card
</h1>
<h4>Add data of new Discharge Card</h4>
</div>
</div>
<!-- END Page Title -->
<!-- BEGIN Breadcrumb -->
<div id="breadcrumbs">
<ul class="breadcrumb">
<li><i class="fa fa-home"></i> Home <span
class="divider"><i class="fa fa-angle-right"></i></span></li>
<li class="active">Discharge</li>
</ul>
</div>
<!-- END Breadcrumb -->
<div class="row">
<div class="col-md-12">
<div class="box box-pink">
<div class="box-title">
<h3>
<i class="fa fa-bars"></i> Discharge Card
</h3>
<div class="box-tool">
<a data-action="collapse" href="#"><i class="fa fa-chevron-up"></i></a>
<a data-action="close" href="#"><i class="fa fa-times"></i></a>
</div>
</div>
<div class="box-content">
<%-- <form action="#" > --%>
<form:form action="${actionURL}" class="form-horizontal"
id="wizard-validation" method="post"
modelAttribute="dischargecard">
<form:hidden path="DischargeId" id="DischargeId" />
<div class="form-wizard" id="form-wizard-2">
<ul class="row steps steps-fill">
<li class="col-xs-12 col-sm-6 col-lg-3"><a href="#tab2-1"
data-toggle="tab" class="step active"> <span class="number">1</span>
<span class="desc"><i class="fa fa-check"></i> Client
Details</span>
</a></li>
<li class="col-xs-12 col-sm-6 col-lg-3"><a href="#tab2-2"
data-toggle="tab" class="step"> <span class="number">2</span>
<span class="desc"><i class="fa fa-check"></i>
Treatment Details</span>
</a></li>
<li class="col-xs-12 col-sm-6 col-lg-3"><a href="#tab2-3"
data-toggle="tab" class="step"> <span class="number">3</span>
<span class="desc"><i class="fa fa-check"></i> Photo's</span>
</a></li>
<li class="col-xs-12 col-sm-6 col-lg-3"><a href="#tab2-4"
data-toggle="tab" class="step"> <span class="number">4</span>
<span class="desc"><i class="fa fa-check"></i> Confirm</span>
</a></li>
</ul>
<div class="progress progress-striped">
<div class="progress-bar progress-bar-primary"></div>
</div>
<div class="tab-content">
<div class="tab-pane active" id="tab2-1">
<div class="form-group">
<label for="firstname2"
class="col-sm-3 col-lg-2 control-label">Client Name</label>
<div class="col-sm-5 col-lg-3 controls">
<!-- <input type="text" name="firstname2" id="firstname2"
class="form-control" data-rule-required="true"> -->
<%-- <form:select path="Client_id"
class="form-control chosen" data-rule-required="true"
style="border-radius: 8px;"
data-placeholder="Choose a client" tabindex="1">
<option value=""></option>
<c:forEach var="client" items="${clientList}">
<form:option value="${client.clientId}">${client.clientName}</form:option>
</c:forEach>
</form:select> --%>
<form:select path="Client_id" items="${clientList}"
itemValue="clientId" itemLabel="clientName" />
</div>
</div>
<div class="form-group">
<label for="firstname2"
class="col-sm-3 col-lg-2 control-label">IPD Number</label>
<div class="col-sm-5 col-lg-3 controls">
<form:input path="ipdno" name="ipdno" type="text"
class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Date of
Admission</label>
<div class="col-sm-5 col-lg-3 controls">
<form:input path="DOA" name="doa"
class="form-control date-picker" id="dp1" size="16"
type="text" value="" />
</div>
<div class="input-group col-sm-5 col-lg-2">
<a class="input-group-addon" href="#"><i
class="fa fa-clock-o"></i></a>
<form:input path="DOA" name="doa"
class="form-control timepicker-default" type="text" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Date of
Operation</label>
<div class="col-sm-5 col-lg-3 controls">
<form:input path="DOO" name="doo"
class="form-control date-picker" id="dp1" size="16"
type="text" value="" />
</div>
<div class="input-group col-sm-5 col-lg-2">
<a class="input-group-addon" href="#"><i
class="fa fa-clock-o"></i></a>
<form:input path="DOO" name="doo"
class="form-control timepicker-default" type="text" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Date of
Discharge</label>
<div class="col-sm-5 col-lg-3 controls">
<form:input path="DOD" name="dod"
class="form-control date-picker" id="dp1" size="16"
type="text" value="" />
</div>
<div class="input-group col-sm-5 col-lg-2">
<a class="input-group-addon" href="#"><i
class="fa fa-clock-o"></i></a>
<form:input path="DOD" name="dod"
class="form-control timepicker-default" type="text" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Date of
Birth</label>
<div class="col-sm-5 col-lg-3 controls">
<form:input path="DOB" name="dob"
class="form-control date-picker" id="dp1" size="16"
type="text" value="" />
</div>
</div>
<div class="form-group">
<label for="lastname2" class="col-sm-3 col-lg-2 control-label">Age</label>
<div class="col-sm-5 col-lg-3 controls">
<form:input path="age" name="Age" type="text" id="lastname2"
class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Radio
Buttons</label>
<div class="col-sm-9 col-lg-10 controls">
<label class="radio-inline"> <form:radiobutton
path="sex" name="optionsRadios2" value="Male" /> Male
</label> <label class="radio-inline"> <form:radiobutton
path="sex" name="optionsRadios2" value="Female" /> Female
</label>
</div>
</div>
<div class="form-group">
<label for="firstname2"
class="col-sm-3 col-lg-2 control-label">Phone</label>
<div class="col-sm-5 col-lg-3 controls">
<form:input path="phone" name="Phone" type="text"
class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Address</label>
<div class="col-sm-5 col-lg-5 controls">
<form:textarea path="Address" name="address"
class="form-control" rows="4"></form:textarea>
</div>
</div>
</div>
<div class="tab-pane" id="tab2-2">
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Diagnosis</label>
<div class="col-sm-5 col-lg-5 controls">
<form:textarea path="diagnosis" name="Diagnosis"
class="form-control" rows="4"></form:textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Treatment</label>
<div class="col-sm-5 col-lg-5 controls">
<form:textarea path="treatment" name="Treatment"
class="form-control" rows="4"></form:textarea>
</div>
</div>
<div class="form-group">
<label for="firstname2"
class="col-sm-3 col-lg-2 control-label">Anesthesia</label>
<div class="col-sm-5 col-lg-3 controls">
<form:input path="anesthesia" name="Anesthesia" type="text"
class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Clinical
Presentation</label>
<div class="col-sm-5 col-lg-5 controls">
<form:textarea path="clinical_presentation"
name="clinicalpresentation" class="form-control" rows="4"></form:textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Investigation</label>
<div class="col-sm-5 col-lg-5 controls">
<form:textarea path="investigation" name="Investigation"
class="form-control" rows="4"></form:textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Given
Treatment</label>
<div class="col-sm-5 col-lg-5 controls">
<form:textarea path="given_treatment" name="giventreatment"
class="form-control" rows="4"></form:textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Treatment
Advice on Discharge</label>
<div class="col-sm-5 col-lg-5 controls">
<form:textarea path="advice" name="Advice"
class="form-control" rows="4"></form:textarea>
</div>
</div>
</div>
<div class="tab-pane" id="tab2-3">
<div class="form-group">
<label for="country2" class="col-sm-3 col-lg-2 control-label">Country</label>
<div class="col-sm-5 col-lg-3 controls">
<input type="text" name="country2" id="country2"
class="form-control">
</div>
</div>
<div class="form-group">
<label for="city2" class="col-sm-3 col-lg-2 control-label">City</label>
<div class="col-sm-5 col-lg-3 controls">
<input type="text" name="city2" id="city2"
class="form-control">
</div>
</div>
<%-- <div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Gender</label>
<div class="col-sm-5 col-lg-3 controls">
<label class="radio-inline">
<form:radiobutton path="sex" name="gender" value="Male" /> Male
</label> <label class="radio-inline">
<form:radiobutton path="sex" name="gender" value="Female" /> Female
</label>
</div>
</div> --%>
<div class="form-group">
<label for="textarea2" class="col-sm-3 col-lg-2 control-label">More
info</label>
<div class="col-sm-5 col-lg-3 controls">
<textarea name="textarea2" id="textarea2" rows="5"
class="form-control"></textarea>
</div>
</div>
</div>
<div class="tab-pane" id="tab2-4">
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">First
Name</label>
<div class="col-sm-5 col-lg-3 controls">
<span class="text">Penny</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">last
Name</label>
<div class="col-sm-5 col-lg-3 controls">
<span class="text">Rodrigez</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Gender</label>
<div class="col-sm-5 col-lg-3 controls">
<span class="text">Female</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Username</label>
<div class="col-sm-5 col-lg-3 controls">
<span class="text">PennyRod</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 col-lg-2 control-label">Email</label>
<div class="col-sm-5 col-lg-3 controls">
<span class="text">pennyrod#domain.com</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2">
Back Continue
<button type="submit" class="btn btn-success button-submit">Submit</button>
</div>
</div>
</div>
</form:form>
</div>
</div>
</div>
</div>
</div>
<!-- END Main Content -->
<jsp:include page="footer.jsp"></jsp:include>

Related

org.springframework.beans.NotReadablePropertyException:Invalid property

Invalid property 'stCode' of bean class [java.lang.String]: Bean property 'stCode' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Regist.jsp
<div class="container">
<div class="row centered-form">
<div class="col-xs-12 col-sm-8 col-md-4 col-sm-offset-2 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
</div>
<div class="panel-body">
<f:form action="registSave" modelAttribute="r" method="post">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
State Name
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<f:input path="stCode" class="form-control input-sm"/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
District Name
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<f:input path="distCode" class="form-control input-sm"/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
Phone number
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<f:input path="phone" class="form-control input-sm"/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
Name
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<f:input path="name" class="form-control input-sm"/>
</div>
</div>
</div>
<!-- <div class="form-group">
<input type="email" name="email" id="email" class="form-control input-sm" placeholder="Email Address">
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-sm" placeholder="Password">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<input type="password" name="password_confirmation" id="password_confirmation" class="form-control input-sm" placeholder="Confirm Password">
</div>
</div>
</div> -->
<input type="submit" value="Register" class="btn btn-info btn-block">
</f:form>
</div>
</div>
</div>
</div>
</div>
RBean
package max.Bean;
public class RBean {
String stCode;
String distCode;
String phone;
String name;
public String getStCode() {
return stCode;
}
public void setStCode(String stCode) {
this.stCode = stCode;
}
public String getDistCode() {
return distCode;
}
public void setDistCode(String distCode) {
this.distCode = distCode;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Controller
package max;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import max.Bean.RBean;
#Controller
public class MainController {
#Autowired
RBean rBean;
#RequestMapping("home")
public String home()
{
return "registLayout";
}
#RequestMapping("regist")
public ModelAndView registration()
{
return new ModelAndView("reg","r","rBean");
}
#RequestMapping(value="registSave", method=RequestMethod.POST)
public ModelAndView registrationSave(#ModelAttribute("r") RBean rBean)
{
return new ModelAndView("reg","r","rBean");
}
}
if you are trying to set rBean into r variable which is available in view then you should remove the " used for rBean. Eg: return new ModelAndView("reg","r",rBean);

How to validate a form with thymeleaf and spring?

I simply want to validate a form data and display an error message. Validating email format, password size and password matching. What would be the best way to do that?
Here's what I've tried
My controller
#PostMapping("/{customerId}/createUser")
public String signIn(#PathVariable(value = "customerId", required = false) Long customerId,
#ModelAttribute(name = "user") #Valid Users user, RedirectAttributes redirectAttributes,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "customerNewUser";
}
// Encrypt password
user.setPassword(encoder.encode(user.getPassword()));
user.setCustomerId(customerId);
user.setEventDescription("User Admin creation");
try {
Users returnedUser = userService.save(user);
List<Authorities> authorities = new ArrayList<Authorities>();
Authorities auth = new Authorities(new AuthoritiesPK(returnedUser.getId(), "ROLE_CLI_ADM"), returnedUser,
"ROLE_CLI_ADM");
authorities.add(auth);
returnedUser.setAuthorities(authorities);
returnedUser.setEventDescription("Add Admin role");
for (int i = 0; i < returnedUser.getAuthorities().size(); i++) {
authorityService.save(returnedUser.getAuthorities().get(i));
}
userService.save(returnedUser);
} catch (WebExchangeBindException webe) {
StringBuilder errorBuilder = new StringBuilder();
for (ObjectError error : webe.getAllErrors()) {
errorBuilder.append(messageSource.getMessage(error.getCode(), null, Locale.getDefault())).append("\n");
}
redirectAttributes.addFlashAttribute("signInError", errorBuilder.toString());
}
return "redirect:/customers/?id=" + customerId;
}
My form in my customerNewUser html file
<form
th:action="#{${user?.id} ? '/customers/' + ${customer.id} + '/createUser/' + ${user.id} : '/customers/' + ${customer.id} + '/createUser/'}"
th:object="${user}" action="#" method="post">
<div class="alert alert-danger" th:if="${#fields.hasAnyErrors()}">
<div th:each="detailedError : ${#fields.detailedErrors()}">
<span th:text="${detailedError.message}"></span>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-5">
<label class="text-right label-control"
th:text="#{firstname} + ':'">Firstname:</label>
</div>
<div class="col-md-4">
<input type="text" id="firstname" name="firstname"
th:value="${user?.firstname} ? ${user?.firstname} : ''"
class="form-control" th:placeholder="#{firstname}"
required="required" autofocus="autofocus" th:field="*{firstname}"/>
<label th:style="'color: red;'" class="text-right label-control" th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}" th:text="#{passwordError}">Password Error</label>
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-5">
<label class="text-right label-control"
th:text="#{surname} + ':'">Surname:</label>
</div>
<div class="col-md-4">
<input type="text" id="surname" name="surname"
th:value="${user?.surname} ? ${user?.surname} : ''"
class="form-control" th:placeholder="#{surname}"
autofocus="autofocus" />
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-5">
<label class="text-right label-control"
th:text="#{email} + ':'">Email:</label>
</div>
<div class="col-md-4">
<input th:placeholder="#{email}" required="required"
autofocus="autofocus" id="email" class="form-control"
type="text" th:value="${user?.email} ? ${user?.email} : ''"
name="email" th:field="*{email}"/>
<label th:style="'color: red;'" class="text-right label-control" th:if="${#fields.hasErrors('email')}" th:errors="*{email}" th:text="#{emailError}">Email Error</label>
</div>
</div>
</div>
<div class="form-group" th:if="!${user?.id}">
<div class="form-row">
<div class="col-md-5">
<label class="text-right label-control"
th:text="#{password} + ':'">Password:</label>
</div>
<div class="col-md-4">
<input type="password" id="password" name="password"
class="form-control" th:placeholder="#{password}"
required="required" autofocus="autofocus" th:field="*{password}"/>
<label th:style="'color: red;'" class="text-right label-control" th:if="${#fields.hasErrors('password')}" th:errors="*{password}" th:text="#{passwordError}">Password Error</label>
</div>
</div>
</div>
<div class="form-group" th:if="!${user?.id}">
<div class="form-row">
<div class="col-md-5">
<label class="text-right label-control"
th:text="#{passwordConfirmation} + ':'">Password confirmation:</label>
</div>
<div class="col-md-4">
<input type="password" id="matchPassword" name="matchPassword"
class="form-control" th:placeholder="#{password}"
required="required" autofocus="autofocus" th:field="*{matchPassword}"/>
<label th:style="'color: red;'" class="text-right label-control" th:if="${#fields.hasErrors('matchPassword')}" th:errors="*{matchPassword}" th:text="#{matchPassword}">Match Password Error</label>
</div>
</div>
</div>
<div class="form-group" th:if="${user?.id}">
<div class="form-row">
<div class="col-md-5">
<label class="text-right label-control"
th:text="#{userStatus} + ':'">Status:</label>
</div>
<div class="col-md-3">
<select class="form-control form-control" id="userStatus"
name="userStatus">
<option
th:each="userStatus : ${T(br.com.macrosul.stetho.entity.UserStatus).values()}"
th:text="${userStatus}" th:value="${userStatus}"
th:selected="${user.userStatus} eq ${userStatus}"></option>
</select>
</div>
</div>
</div>
<div class="form-group">
<p class="error-control" th:text="${signInError}"></p>
</div>
<input type="submit" class="btn btn-md btn-block"
value="Sign in"
th:value="${user?.id} ? #{updateUser} : #{signIn}" />
</form>
And here is the stacktrace when I try to force a password size error ->
#Size(min=6)
#Column(nullable = false)
private String password;
Field error in object 'user' on field 'password': rejected value [12345]; codes [Size.user.password,Size.password,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.password,password]; arguments []; default message [password],2147483647,6]; default message [tamanho deve estar entre 6 e 2147483647]
I want a simple validation. If there's a simpler way to indicate the user the data are invalid I would appreciate for any help or advice!
It is a little bit late, but you need to put your BindingResult next to your #valid attribute so instead of:
#ModelAttribute(name = "user") #Valid Users user, RedirectAttributes redirectAttributes, BindingResult bindingResult
you should write:
#ModelAttribute(name = "user") #Valid Users user, BindingResult bindingResult, RedirectAttributes redirectAttributes
You need a validator like below. Its not the exact code what you need but sufficient enough and pretty close to what you need to get you going.
#Override
public void validate(Object o, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "useremail", "NotEmpty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userfirstname", "NotEmpty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userlastname", "NotEmpty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "useraddress", "NotEmpty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
if (user.getPassword().length() < 8 || user.getPassword().length() > 32) {
errors.rejectValue("password", "Size.userForm.password");
}
if (!user.getPasswordConfirm().equals(user.getPassword())) {
errors.rejectValue("passwordConfirm", "Diff.userForm.passwordConfirm");
}
}
For more details you can take a look at here, here and here.
You can put a div in the html that only exists if there are errors on the validation. Then you show each error in a loop:
<div th:if="${#fields.hasErrors('*')}">
<p th:each="err : ${#fields.errors('*')}">
<span th:text="${err}"></span>
</p>
</div>
This way, when you return to this view there will be errors on your fields so this code will be shown.

I have an issue when update a form in Spring boot

I want to update a form in spring boot - all input fields are successfully populated from the retrieved data but when I press 'submit' for update the system gives this error message.
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Nov 07 09:41:44 IST 2017
There was an unexpected error (type=Internal Server Error, status=500).
For input string: "updateApplication"
My DAO code:
public interface SLSNotificationRepository extends CrudRepository<SLSNotification, Integer> {
#Override
SLSNotification save(SLSNotification slsNotification);
#Override
SLSNotification findOne(Integer integer);
#Override
long count();
#Override
void delete(Integer integer);
#Override
void delete(SLSNotification slsNotification);
#Override
void delete(Iterable<? extends SLSNotification> iterable);
#Override
List<SLSNotification> findAll();
#Query("select a from SLSNotification a where a.slsiUnit in :unitList")
List<SLSNotification> getApplicationsByUnit(#Param("unitList")List <String> unitList);
#Query("select a from SLSNotification a where a.userId = :userId")
List<SLSNotification> getApplicationsByUserId(#Param("userId")String userId);
#Query("select a from SLSNotification a where a.slsNo = :slsNo")
SLSNotification getApplicationBySLSNumber(#Param("slsNo") String slsNo);
#Query("select a from SLSNotification a where a.importerVAT = :importerVAT group by slsNo")
List<SLSNotification> getproductByUserId(#Param("importerVAT")String importerVAT);
}
My service:
public boolean update(SLSNotification slsNotification) {
serviceLogger.info("Staring adding/updating the SLS Notification data . data : [{}]", slsNotification);
try {
serviceLogger.info("Saving data in the database. [{}]", slsNotification);
slsNotificationRepository.save(slsNotification);
return true;
} catch (Exception e) {
serviceLogger.error("Error occurred while saving SLS Common data . [{}]", e);
rollBack.rollback();
return false;
}
}
My controller is
#RequestMapping(path = "/updateApplication", method = RequestMethod.POST)
public String updateApplication(#ModelAttribute("applicationForm") #Valid SLSNotification slsNotification,
BindingResult result,
HttpSession session) {
slsiLogger.info("Request received to register new product. [{}]", slsNotification);
if (result.hasErrors()) {
slsiLogger.error("Rejecting the request due to binding errors, [{}]", result.getFieldErrors());
return "redirect:/applicationManage?";
}
if (applicationServices.update(slsNotification)) {
slsiLogger.info("Product registered successfully");
session.setAttribute(MESSAGE_KEY, "Product registered successfully");
} else {
session.setAttribute(MESSAGE_KEY, "Error occurred while registering the product");
}
return "redirect:/applicationManage?" + MESSAGE_KEY;
}
My JSP:
<form:form name="applicationForm" id="applicationForm" action="updateApplication" commandName="app" method="post">
<c:if test="${edit}">
<input type="hidden" id="snumber" name="snumber" value="${app.snumber}"/>
</c:if>
<div class="panel panel-default">
<div class="panel-body" >
<div class="row">
<label id="aaa" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name &
Address <div class="req" > *</div></label>
<label id="bbb" for="manufacturer" class="col-sm-2 col-form-label col-form-label-lg">Manufacturer Name <div class="req" > *</div></label>
<div id="">
<div class="col-sm-4">
<div class="checkbox">
<label><input type="checkbox" value="" id="registered">Registered Manufacturer in SLSI</label>
</div>
<div id="regManu">
<select id="companies">
<c:forEach items="${manu}" var="com">
<option value="${com.manufacturerName}">${com.manufacturerName}</option>
</c:forEach>
</select>
</div>
<textarea name="manufacturer" class="form-control form-control-lg"
id="manufacturer"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="4" maxlength="254"></textarea>
<input type="hidden" id="manufacture" name="manufacture" value="${app.manufacturer}"/>
<div class="help-block with-errors"></div>
</div>
<label for="exporterAddress" class="col-sm-2 col-form-label col-form-label-lg">Exporter Name &
Address <div class="req"> *</div></label>
<div class="col-sm-4">
<textarea name="exporterAddress" class="form-control form-control-lg" id="exporterAddress"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name & Address is required!"
required rows="5" maxlength="254"></textarea><br/><br/>
<input type="hidden" id="exp" name="exp" value="${app.exporterAddress}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row">
<br/> <label for="importerVAT" class="col-sm-2 col-form-label col-form-label-lg">Importer VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" type="text" name="importerVAT" id="importerVAT"
aria-describedby="importerVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.importerVAT}">
<div class="help-block with-errors"></div>
</div>
<label for="declarantVAT" class="col-sm-2 col-form-label col-form-label-lg">Declarant VAT <div class="req"> *</div></label>
<div class="col-sm-4">
<input class="form-control" name="declarantVAT" type="text" id="declarantVAT"
aria-describedby="declarantVATHelp" placeholder="Ex : 174625588-7000 (White spaces not allowed)"
data-error="VAT number is required!" onkeyup="lettersOnly(this)" required value="${app.declarantVAT}">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row" >
<label for="importerDetails" class="col-sm-2 col-form-label col-form-label-lg">Importer Name &
Address <div class="req"> *</div></label>
<div class="col-sm-4">
<textarea name="importerDetails" class="form-control form-control-lg" id="importerDetails"
placeholder="Enter the name & Address. Press Enter at the end of each line"
aria-descrribedby="exportertHelp" data-error="Name and Address is required!"
required rows="4" maxlength="254"></textarea>
<input type="hidden" id="imp" name="imp" value="${app.importerDetails}"/>
<div class="help-block with-errors"></div>
</div>
<label for="declarantDetails" class="col-sm-2 col-form-label col-form-label-lg">Declarant Name &
Address <div class="req"> *</div></label>
</div>
</div>
<div class="form-group row">
<label for="cusOffice" class="col-sm-2 col-form-label col-form-label-lg">CusDec No &
Date</label>
<div class="col-sm-2">
<input class="form-control" type="text" name="cusOffice " id="cusOffice " style="float:left;"
aria-describedby="importerVATHelp" placeholder=" Ex : KTIM1" value="${app.cusOffice}">
</div>
</div>
</div>
<div class="tabbable">
<br/>
<div class="row">
<div class="col-md-12">
<ul class="nav nav-pills">
<li class="active"><a href="#tab1" data-toggle="pill" style="text-decoration: none;">Product
Details</a></li>
<li>Consignment Details</li>
<li>Attachments</li>
</ul>
<br/>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="form-group row">
<label for="slsNo" class="col-sm-5 col-lg-2 col-xs-12 col-form-label col-form-label-lg">Relevant
SLS Standard No <div class="req"> *</div></label>
<div class="col-sm-3 col-sm-4">
<input class="form-control" type="text" id="slsNo" name="slsNo"
aria-describedby="slsNoHelp"
placeholder=" Enter SLS No here"
data-error="SLSI Standard No is required!" onkeyup="numbersOnly(this)" required value="${app.slsNo}">
<div class="help-block with-errors"></div>
</div>
<label for="slsiUnit" class="col-sm-1 col-form-label col-form-label-lg">
SLSI Unit <div class="req"> *</div></label>
<div class="col-sm-2">
<select class="form-control" id="slsiUnit" name="slsiUnit"
data-error="SLSI Unit is required!" required>
<option>UNIT1</option>
<option>UNIT2</option>
<option>UNIT3</option>
<option>UNIT4</option>
<option>UNIT5</option>
<option>UNIT6</option>
</select>
<input type="hidden" id="ut" name="ut" value="${app.slsiUnit}"/>
</div>
<label for="invoiceValue" class="col-sm-5 col-xs-6 col-md-5 col-lg-2 col-form-label col-form-label-lg">Invoice
Value (FOB) of the Product in US$ <div class="req"> *</div></label>
<div class="col-sm-6 col-md-3 col-lg-2 col-xs-6">
<div class="input-group">
<span class="input-group-addon">US$</span>
<input class="form-control" type="text" name="invoiceValue" id="invoiceValue"
aria-describedby="invoiceValueHelp"
placeholder="Value"
data-error="Invoice Value is required!" onkeyup="numbersOnly(this)" required value="${app.invoiceValue}"/>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="form-group row">
<label for="invoiceValue" class="col-sm-4 col-xs-6 col-md-2 col-lg-2 ">Total
Quantity <div class="req"> *</div></label>
<div class="col-md-3 col-lg-3 col-sm-3 col-xs-3">
<input class="form-control" type="text" name="totalQty" id="totalQty"
aria-describedby="totQtyHelp"
placeholder="Total Net Weight in Number"
data-error="Total Net Weight is required!" onkeyup="numbersOnly(this)" required value="${app.totalQty}">
</div>
<div class="col-md-3 col-lg-3 col-sm-3 col-xs-3">
<select class="form-control" id="uom" name="uom" style="float:left;">
<option>KGM</option>
<option>UNITS</option>
<option>LITERS</option>
<option>CANS</option>
</select>
<input type="hidden" id="um" name="um" value="${app.uom}"/>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label for="shippingMarks" class="col-sm-12 col-form-label col-form-label-lg">Shipping
Marks & Container No/s </label>
<textarea name="marksNumber" class="form-control form-control-lg"
id="marksNumber" placeholder="If no of containers greater than 10 please attach the container numbers as an attachment"
data-error="Shipping marks are required!" maxlength="250" rows="5" ></textarea>
<input type="hidden" id="shims" name="shims" value="${app.marksNumber}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label for="productDesc" class="col-sm-12 col-form-label col-form-label-lg">Product
Description (Max 250 charactors) <div class="req"> *</div></label>
<textarea value="${app.productDesc}" name="productDesc" class="form-control form-control-lg"
id="productDesc"
placeholder="Enter Product Description with brand,model/Type,size/s, quantity, Pkg.Type etc. here"
data-error="Product Description is required!" maxlength="250" required rows="5" ></textarea>
<input type="hidden" id="product" name="product" value="${app.productDesc}"/>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label for="purpose"
class="col-sm-12 col-form-label col-form-label-lg">Purpose <div class="req"> *</div></label>
<select class="form-control" id="purpose" name="purpose"
data-error="Purpose is required!" required>
<option>Commercial</option>
<option>Personal</option>
<option>Project</option>
<option>Charity</option>
<option>Further Processing</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="hsCode" class="col-sm-12 col-form-label col-form-label-lg">HS
Code <div class="req"> *</div></label>
<input class="form-control" type="text" id="hsCode" name="hsCode"
aria-describedby="hsCodHelp" placeholder=" Please enter HS Code here"
data-error="HS Code is required!" required value="${app.hsCode}">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<label for="issuerQltyCert" class="col-sm-12 col-form-label col-form-label-lg">Issuer
of Product/Quality Certificate <div class="req"> *</div></label>
<input class="form-control" type="text" id="issuerQltyCert" name="issuerQltyCert"
aria-describedby="issuerCertHelp"
placeholder=" Enter the Organization Issued the Certificate"
data-error="Organization is required!" required maxlength="254" value="${app.issuerQltyCert}">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label for="certRefNo" class="col-sm-12 col-form-label col-form-label-lg">Product
Certificate Ref.No <div class="req"> *</div></label>
<input class="form-control" type="text" id="certRefNo" name="certRefNo"
aria-describedby="certRefNoHelp"
placeholder=" Please enter product certificate No."
data-error="Product certificate No is required!" required value="${app.certRefNo}" >
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="tab2">
<div class="form-group row">
<label for="vessel" class="col-sm-3 col-md-2 col-xs-7 col-form-label col-form-label-lg">Vessel
Name <div class="req"> *</div></label>
<div class="col-md-2">
<input class="form-control" type="text" name="vessel" id="vessel"
aria-describedby="vesselHelp" placeholder=" Vessel Name"
data-error="Vessel Name & Date is required!" required maxlength="254" value="${app.vessel}" >
</div>
<label for="blNo" class="col-sm-5 col-md-2 col-xs-6 col-lg-2 col-form-label col-form-label-lg">Bill Of Lading
No <div class="req"> *</div></label>
<label for="blNo" class="col-sm-12 col-md-2 col-xs-12 col-form-label col-form-label-lg">Date of B/L <div class="req"> *</div></label>
<div class="col-sm-1">
<input type="text" class="datep" format="YYYY-MM-dd" style="float:left;"
readonly='true' name="blDate" id="blDate">
</div>
</div>
<input class="form-control" type="text" name="loadingPort" id="loadingPort"
aria-describedby="loadPortHelp"
placeholder=" Please enter Port of Loading here"
data-error="Port of Loading is required!" required value="${app.loadingPort}">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" id="submit" class="btn btn-success pull-right">SAVE CHANGES</button>
</div>
</div>
</form:form>
How do I get the form update to work?

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();
}

Displaying List entries as Checkboxes - Neither BindingResult nor plain available

I have the following object.
public class Anonymization {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToMany(mappedBy = "anonymization")
private List<Host> hosts;
#OneToMany(mappedBy = "anonymization")
private List<Item> items;
The objects Host and Item have several boolean Fields. I want to display a form, where all Host and Item objects are displayed as checkboxes, so that the boolean fields can be edited. I wrote a controller to display the form
#RequestMapping("monitoringsystem/{mId}/anonymization")
public String editAnonymisatzion(Model model, #PathVariable Long mId){
model.addAttribute("mId", mId);
model.addAttribute("anonymization", monitoringSystemRepository.findOne(mId).getAnonymization());
return "monitoringsystem/anonymizationForm";
}
The anonymizationForm should display the checkboxes in a for-each-loop
<!-- more code --->
<form class="form-horizontal" th:modelAttribute="anonymization" th:object="${anonymization}" th:action="#{'monitoringsystem/' + ${mId} + '/anonymisatzion/save'}" method="post">
<input type="hidden" th:field="*{id}"/>
<fieldset>
<legend>Set Anonymization</legend>
<div class="panel panel-default">
<div class="panel-heading">Anonymizie Hostnames</div>
<div class="panel-body">
<div class="form-group" th:each="host : ${anonymization.hosts}">
<label class="col-md-4 control-label" for="checkboxes" th:text="${host.name}"></label>
<div class="col-md-4">
<div class="checkbox">
<label for="checkboxes-0">
<input th:field="${host.anonymizeName}" type="checkbox" />
anonymizie
</label>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Anonymizie Items</div>
<div class="panel-body">
<div class="form-group" th:each="item : ${anonymization.items}">
<label class="col-md-4 control-label" for="checkboxes" th:text="${item.name}"></label>
<div class="col-md-4">
<div class="checkbox">
<label for="checkboxes-0">
<input th:field="${item.anonymizeName}" type="checkbox" />
anonymizie name
</label>
</div>
<div class="checkbox">
<label for="checkboxes-0">
<input th:field="${item.anonymizeData}" type="checkbox" />
anonymizie data
</label>
</div>
</div>
</div>
</div>
</div>
<!-- more code --->
Unfortunatly when i call the View I'm getting the following error
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'host' available as request attribute
I checkt my Database all Relationsships are set correctly. The List<Host> should contain 1 and the List<Item> 2 entries.
I can't find my mistake.
UPDATE 1:
I debuged the anonymization object which is passed to the form. It's is complete. Which means all listentries are present. So I guess the error has something to to do with my view - how I call the object.
I found the solution by myselfe. Fist of all i changes the way the list-objects are called in my form
<form class="form-horizontal" th:modelAttribute="anonymization" th:object="${anonymization}" th:action="#{'monitoringsystem/' + ${mId} + '/anonymisatzion/save'}" method="post">
<input type="hidden" th:field="*{id}"/>
<fieldset>
<legend>Set Anonymization</legend>
<div class="panel panel-default">
<div class="panel-heading">Anonymizie Hostnames</div>
<div class="panel-body">
<div class="form-group" th:each="host, statHost : *{hosts}">
<label class="col-md-4 control-label" for="checkboxes" th:text="*{hosts[__${statHost.index}__].name}"></label>
<div class="col-md-4">
<div class="checkbox">
<label for="checkboxes-0">
<input th:field="*{hosts[__${statHost.index}__].anonymizeName}" type="checkbox" />
anonymizie
</label>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">Anonymizie Items</div>
<div class="panel-body">
<div class="form-group" th:each="item, statItem : *{items}">
<label class="col-md-4 control-label" for="checkboxes" th:text="*{items[__${statItem.index}__].name}"></label>
<div class="col-md-4">
<div class="checkbox">
<label for="checkboxes-0">
<input th:field="*{items[__${statItem.index}__].anonymizeName}" type="checkbox" />
anonymizie name
</label>
</div>
<div class="checkbox">
<label for="checkboxes-0">
<input th:field="*{items[__${statItem.index}__].anonymizeData}" type="checkbox" />
anonymizie data
</label>
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<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>
</div>
</div>
</fieldset>
</form>
Futhermore there seems to be a problem with the naming of the getter and setter. Mine were like:
setBoolean(boolean b){
this.b = b;
}
isBoolean(){
return b;
}
Spring or thymeleaf (i don't know which component is responsible) seems to need the getter starting with get. After changing this it's working now.
setBoolean(boolean b){
this.b = b;
}
getBoolean(){
return b;
}

Resources