Bean property 'empname' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? - eclipse

I am trying to perform a simple submit operation from a form. I use spring boot framework with thyme leaf template for my project. Language used is java in eclipse IDE.
All I am looking to do is to take the empname and empid (refer Employee class) from the form and store it in a java object.
When I run the application, the application opens and when i navigate to edit.html, i get this error message in the browser -
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jun 18 16:14:40 EDT 2018
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/edit.html]")
I also get this error message on the console -
Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'empname' of bean class [com.cardinalcommerce.model.Employee]: Bean property 'empname' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:622) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:612) ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:104) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:228) ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:129) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:305) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:252) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:226) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174) ~[thymeleaf-spring5-3.0.9.RELEASE.jar:3.0.9.RELEASE]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
... 67 common frames omitted
This is my snippet of the html document where the error occurs.
<form class="form-horizontal" action="#" th:action="#{/employee/edit}" th:object="${employee}" method="POST">
<div class="form-group">
<label class="control-label col-sm-3">File Prefix:</label>
<div class="col-sm-7">
<input type="text" class="form-control" th:field="*{empname}" placeholder="Enter employee name" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3">File Prefix:</label>
<div class="col-sm-7">
<input type="text" class="form-control" th:field="*{empid}" placeholder="Enter the employee ID" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-7">
<button type="submit" class="btn btn-default" id="blackButton" th:value="Submit">Submit</button>
<button type="reset" class="btn btn-default" id="blackButton" th:value="Reset">Cancel</button>
</div>
</div>
This is my class where with the setters and getters -
public class Employee {
private String empid;
private String empname;
public String getEmployeeId() {
return empid;
}
public void setEmployeeId(String empid) {
this.empid = empid ;
}
public String getEmployeeName() {
return empname;
}
public void setEmployeeName(String empname) {
this.empname = empname;
}
}
This is the controller snippet -
#Controller
#RequestMapping(value="/")
public class GreetingController {
private static final Logger logger = LoggerFactory.getLogger(GreetingController.class);
#Autowired
private SomeRecord someRecord;
#GetMapping("/")
public String greeting() {
return "about";
}
#RequestMapping("/about")
public String about() {
return "about";
}
#GetMapping("/edit")
public ModelAndView edit() {
ModelAndView modelAndView = new ModelAndView("edit");
modelAndView.addObject("employee", new Employee());
return modelAndView;
}
#PostMapping("/edit")
public ModelAndView createRecord(#Valid Employee employee, BindingResult result) {
ModelAndView modelAndView = new ModelAndView();
if (result.hasErrors()) {
logger.info("Validation errors while submitting form.");
modelAndView.setViewName("CreateRecord");
modelAndView.addObject("employee", employee);
return modelAndView;
}
someRecord.addRecord(employee);
modelAndView.addObject("allRecords", someRecord.getAllRecordData());
modelAndView.setViewName("recordsInfo");
logger.info("Form submitted successfully.");
return modelAndView;
}
#GetMapping("/view")
public String view() {
return "view";
}
}
Let me know if anything else is required.
Thanks for your help.

You should use *{employeeName} and *{employeeId} rather than *{empname} and *{empid}. (Matching the getters and setters, rather than your private variables.)

Related

How can I bind form fields to a nested model on post?

I am coding a solution where the user will submit a form, posting the values back to my ASP.NET MVC controller. My model is complex and the form fields are contained in a nested object (I'm using CQRS via MediatR). When I submit the form, the values come across as null. How can I get the complex model to recognize the form fields?
Here is my code:
Controller:
[HttpPost]
[Route("edit")]
public async Task<IActionResult> Edit(UpdateApplicationCommand command)
{
await _mediator.Send(command)
.ConfigureAwait(false);
return RedirectToAction("Index");
}
Models:
public class UpdateApplicationCommand : IRequest<Unit>
{
public ApplicationEditGeneralViewModel ApplicationEditGeneralViewModel { get; set; } = null!;
}
public class ApplicationEditGeneralViewModel
{
[Required]
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}
View:
#model ApplicationEditGeneralViewModel
<form method="post" asp-action="Edit" asp-controller="Applications">
<div class="form-floating mb-3">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control", placeholder = "Application Name"})
<label for="Name">Application Name</label>
</div>
<div class="form-floating mb-3">
#Html.TextBoxFor(m => m.Description, new { #class = "form-control", placeholder = "Application Description"})
<label for="Description">Application Description</label>
</div>
<div class="d-flex flex-row-reverse bd-highlight">
<input type="submit" value="Submit" class="btn btn-primary mt-2" />
</div>
</form>
I've tried to reduce the complex model to its fields, by placing the contents of the ApplicationEditGeneralViewModel directly into the UpdateApplicationCommand class. This worked, but I'd really like to keep the nested structure so that I can reuse the ApplicationEditGeneralViewModel object.
I saw this solution here:
How to bind nested model in partial view
But I'd rather avoid adding the name as a route object (if possible) for every form field. Is there another, more simple way that I can do this?
The first way, you can custom model binding like below:
public class CustomModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
throw new ArgumentNullException(nameof(bindingContext));
var model = new UpdateApplicationCommand()
{
ApplicationEditGeneralViewModel = new ApplicationEditGeneralViewModel()
{
Description = bindingContext.ValueProvider.GetValue("Description").ToString(),
Name = bindingContext.ValueProvider.GetValue("Name").ToString()
}
};
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}
Apply the custom model binding like below:
[HttpPost]
public async Task<IActionResult> Edit([ModelBinder(typeof(CustomModelBinder))]UpdateApplicationCommand model)
{
//.....
}
The second way, just change your razor view like below:
#model UpdateApplicationCommand
<form method="post">
<div class="form-floating mb-3">
#Html.TextBoxFor(m => m.ApplicationEditGeneralViewModel.Name, new { #class = "form-control", placeholder = "Application Name"})
<label for="Name">Application Name</label>
</div>
<div class="form-floating mb-3">
#Html.TextBoxFor(m => m.ApplicationEditGeneralViewModel.Description, new { #class = "form-control", placeholder = "Application Description"})
<label for="Description">Application Description</label>
</div>
<div class="d-flex flex-row-reverse bd-highlight">
<input type="submit" value="Submit" class="btn btn-primary mt-2" />
</div>
</form>

BindingResult nor plain target object for bean name 'fileName' available as request attribute " while trying to update a raw in my db,

I'm getting this exception while trying to update a row in my database. I performed a lot of research in Google all I find is that I should add #modelAttribute which is already done.
I also found that I need to add bindind result after #ModelAttribute but this also didn't work so I removed it. I'm using JPA for persistence to manipulate my data, spring boot and thymeleaf for my views.
These are my Controllers one for updating and rendering views
#GetMapping("/edit/{id}")
public ModelAndView UpdateList(#PathVariable(name="id") String id) {
ModelAndView mav = new ModelAndView("updateList");
com.pfe.ClientRest.model.Files files = fileServ.get(id);
mav.addObject("Files", files);
return mav ;
}
#PostMapping("/Save")
public String saveRepport(#ModelAttribute("Files") com.pfe.ClientRest.model.Files dbfile) {
fileServ.save(dbfile);
return "/redirect:/ListFile";
}
this is my entity class I have getter setters and constructors
#Table( name="Files")
#Entity
public class Files {
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Id
private String id;
private String FileName;
private String Verif;
public String getId() {
return id;
}
this is my template.
<div class="container">
<h1> Modifier les informations du Rapports</h1>
<form action="#" th:action="#{/Save}" th:objects="${Files}"
method="post" >
<input type="text" th:field=*{id} readonly="readonly"/>
<input type="text" th:field="*{fileName}" placeholder="Nom du Fichier"
class="form-control mb-4
col-4">
<input type="text" th:field="*{verif}" placeholder="Accepted/Rejected"
class="form-control mb-4
col-4">
<button type="submit" class="btn btn-info col-2"> Mettre à jour</button>
</form>
</div>
The field names in the html page and entity class does not match. These are case sensitive. So the correct one should be
private String fileName;
private String verif;

Springboot Thymeleaf form validation not working

I've trying to validate the fields in Thymeleaf but the errors are not showing in the view page.
My Controller
#Controller
public class UserController {
private static final String ADD_NEW_USER="user/addUser";
#Autowired
UserService userService;
#RequestMapping(value="/user/new", method=RequestMethod.GET)
public String addUser(Registration register, Model model){
model.addAttribute("register",register);
return ADD_NEW_USER;
}
#RequestMapping(value="/user/new", method=RequestMethod.POST)
public String addUser(#Valid Registration register, BindingResult result, Model model){
model.addAttribute("register",register);
if(result.hasErrors()){
List<FieldError> err=result.getFieldErrors();
for(FieldError e:err){
System.out.println("Error on object ---> "+e.getObjectName()+" on field ---> "+e.getField()+". Message ---> "+e.getDefaultMessage());
}
return ADD_NEW_USER;
}
return INDEX_PAGE;
}
}
View template
<form th:action="#{/user/new}" th:method="post" th:object="${register}" id="addUser" role="form">
<fieldset>
<legend>
<p>Field with <span class="required">*</span> are required</p>
</legend>
<div class="form-group">
<label for="name"><span class="required">* </span>Name: </label>
<input type="text" th:field="*{name}" class="form-control" />
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="alert alert-danger">
<p>Name is invalid</p>
</div>
<p class="help-block">Please provide full name for the user</p>
</div>
<div class="form-group">
<label for="email"><span class="required">* </span> Email Address: </label>
<input class="form-control" type="email" th:field="*{email}"/>
<div th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="alert alert-danger">
<p>Email is invalid</p>
</div>
<p class="help-block">Please provide a valid email address. Activation link will be sent to this email</p>
</div>
<div class="form-group">
<label for="password"><span class="required">* </span> Password: </label>
<input type="password" th:field="*{password}" class="form-control"/>
</div>
<div class="form-group">
<input class="btn btn-success" type="submit" name="Register" value="Register"/>
</div>
</fieldset>
</form><!-- ends register form -->
Modal
#Entity
public class Registration {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#NotEmpty
#Size(min=3, max=50)
#Column(nullable=false)
private String name;
#Email
#NotEmpty
#Column(nullable=false)
private String email;
private String password;
//getters and setters
}
I can output the console error like this.
Error on object ---> registration on field ---> name. Message ---> size must be between 3 and 50
Error on object ---> registration on field ---> email. Message ---> may not be empty
Error on object ---> registration on field ---> name. Message ---> may not be empty
I might be missing something but unable to find.
the problem is that the name of the entity is Registration and that the name of the object that you use is register.
In order this to work add #ModelAttribute("register") next yo your #valid annotation
namely
#RequestMapping(value="/user/new", method=RequestMethod.POST)
public String addUser(#Valid #ModelAttribute("register") Registration register, BindingResult result, Model model){
Hope this helps
I was also facing the same issue. With may hit/trial approach I found that #Valid annotation doesn't work with spring 2.3.0.RELEASE
If you are using spring 2.3.0.RELEASE then add below dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Hope this helps.
I also faced the same issue. My bindingResult.hasErrors() was always returning true in spite of pulling no values in the form. I had to change my validation from #NotNull to #NotEmpty.
#NotNull will only validate if the object is null, #NotEmpty will check if the object has empty strings.

Bind java enum value to Spring form tag input

I want to bind my enum value to a Spring form tag input. I have the following code for the overall process:
public enum Gender {
MALE("M"),
FEMALE("F");
private String abbreviation;
Gender (String abbreviation) {
this.abbreviation = abbreviation;
}
public String getAbbreviation () {
return abbreviation;
}
public static Gender getGenderEnum (String abbreviation) {
Gender gender = null;
if (abbreviation.equals("F"))
gender = Gender.FEMALE;
else
gender = Gender.MALE;
return gender;
}
}
My Gender formatter and converter:
public class GenderEnumFormatter implements Formatter<Gender> {
#Override
public String print(Gender gender, Locale locale) {
return gender.getAbbreviation();
}
#Override
public Gender parse(String genderString, Locale locale)
throws ParseException {
return Gender.getGenderEnum(genderString);
}
}
public class GenderEnumConverter implements Converter<String, Gender> {
#Override
public Gender convert(String source) {
return Gender.getGenderEnum(source);
}
}
I am also registering both my converter and formatter in my WebMvcConfigurerAdapter class:
registry.addConverter(String.class, Gender.class,
new GenderEnumConverter());
registry.addFormatter(new DistanceEnumFormatter());
Here is the controller method that calls the edit form:
#RequestMapping(value = "/edit/{id}")
public String showEditForm(Model model, #PathVariable long id) {
model.addAttribute("race", raceRepository.findOne(id));
return "raceEditForm";
}
Here is the code for my jsp that uses the Spring form tag:
<form:form method="put" action="${edit_race_url}" commandName="race">
<legend>Add a race</legend>
<form:hidden path="id"/>
<p>
<label for="name">Race name: </label>
<form:input id="name" path="name" />
</p>
<p>
<label for="description">Race description: </label>
<form:input id="description" path="description" />
</p>
<p>
<label for="distance">Race distance: </label>
<form:select id="distance" path="distance"
items="${distances}" />
</p>
<p>
<label for="gender">Race gender: </label>
<form:select id="gender" path="gender"
items="${genders}" />
</p>
<p>
<label for="raceDate">Race date: </label>
<form:input id="raceDate" path="raceDate"/>
</p>
<p id="buttons">
<input id="reset" type="reset" tabindex="4"> <input
id="submit" type="submit" tabindex="5" value="Update race">
</p>
</form:form>
Whenever I save a new Race, the conversion from the form:input to the Gender and Distance enums is ok. But when I want to edit a race object adding the race object to the model attributes, the select element doesn't get updated with the current distance and gender values of the race object, all the other fields are getting filled with the current variable values of the race object.
Do I need to include an InitBinder method somewhere? Thanks...

[Spring MVC - Thymeleaf]- Form validation and error messages

I´m trying to create a form and validate its data via #Valid on the command object.
The validation performs well, but an error is ocurring going back to web.
This is what I have:
HTML
<div id="content" layout:fragment="contenido">
<div sec:authorize="isAnonymous()">
<form class="form-horizontal" action="#" th:action="#{register}" th:object="${userForm}" method="post">
<input type="hidden" name="_csrf" th:value="${_csrf.token}"/>
<fieldset>
<label for="alias" th:text="#{form.register.alias}">Alias</label>
<input id="alias" type="text" th:field="*{alias}" placeholder="Su alias" required="required" autofocus="autofocus"/>
<label for="pass" th:text="#{form.register.password}">Contraseña</label>
<input id="pass" type="password" th:field="*{password}" pattern="[\w\d-_]{5,15}" required="required" th:title="#{form.error.password}"/>
<p th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Error en el dato ingresado</p>
<button type="submit" name="save" class="btn btn-primary" th:text="#{control.register}">Registrarme</button>
</fieldset>
</form>
</div>
</div>
Controller
#RequestMapping(value = "/register", params = {"save"}, method = RequestMethod.POST)
public String register (final ModelMap model, #Valid final UsuarioForm userForm, final BindingResult result) {
if (result.hasErrors()) {
return "register";
} else {
return "redirect:/" + HomeController.PAGE_NAME;
}
}
When Clicking on "submit" the "register" method is called, result.hasErrors() is true so the same page should be displayed, but this error occurs.
Stack
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.thymeleaf.spring4.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:396)
org.thymeleaf.spring4.util.FieldUtils.getBindStatus(FieldUtils.java:323)
org.thymeleaf.spring4.util.FieldUtils.getBindStatus(FieldUtils.java:289)
org.thymeleaf.spring4.processor.attr.AbstractSpringFieldAttrProcessor.processAttribute(AbstractSpringFieldAttrProcessor.java:98)
org.thymeleaf.processor.attr.AbstractAttrProcessor.doProcess(AbstractAttrProcessor.java:87)
org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212)
org.thymeleaf.dom.Node.applyNextProcessor(Node.java:1017)
org.thymeleaf.dom.Node.processNode(Node.java:972)
If I add "userForm" to the model in the Controller this way:
Controller Modified
#RequestMapping(value = "/register", params = {"save"}, method = RequestMethod.POST)
public String register (final ModelMap model, #Valid final UsuarioForm userForm, final BindingResult result) {
if (result.hasErrors()) {
model.addAttribute("userForm", userForm); //THIS LINE IS ADDED
return "register";
} else {
return "redirect:/" + HomeController.PAGE_NAME;
}
}
The error disappears, BUT... the expression in the HTML ${#fields.hasErrors('password')} results false, so I cant show the error messages to the user.
Any idea of why this behaviour is happening?
Thanks in advance!
PS: I am using Spring MVC 4.1.2 with Thymeleaf 2.1.4
This
public String register(final ModelMap model,
#Valid final UsuarioForm userForm,
final BindingResult result)
should be:
public String register(final ModelMap model,
#ModelAttribute("userForm") #Valid final UsuarioForm userForm,
final BindingResult result)
Notice the #ModelAttribute annotation.