Spring + Hibernate Validation error - java

I am trying to implement Hibernate+Spring Validation to my application,but there is one issue, it won't display error message on page after I submit faulty data. Here is code:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class StudentVO {
private int studentID;
private String userName;
#NotNull
#Size(min=2, max=45, message="Your Name should be between 2 - 45 characters.")
private String firstName;
private String middleName;
#NotNull
#Size(min=2, max=45, message="Your Surname should be between 2 - 45 characters.")
private String lastName;
JSP
<form:form id="myform" modelAttribute="student" method="post" class="form-horizontal" action="/register/registerStudent">
<div class="form-group">
<label for="firstname" class="col-sm-3 control-label">First Name</label>
<div class="col-sm-6">
<form:input type="text" class="form-control float_left" id="firstname" path="firstName" placeholder="First Name" />
<form:errors path="firstName"></form:errors>
</div>
</div>
<div class="form-group">
<label for="middlename" class="col-sm-3 control-label" id="md">Middle Name</label>
<div class="col-sm-6">
<form:input type="text" class="form-control" id="middlename" path="middleName" placeholder="Middle Name" />
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-3 control-label">Last Name</label>
<div class=" col-sm-6">
<form:input type="text" class="form-control float_left" id="lastname" path="lastName" placeholder="Last Name" required="true" />
<form:errors path="lastName"></form:errors>
</div>
Controller
#RequestMapping(value = { "/register/registerStudent" }, method = { RequestMethod.GET, RequestMethod.POST })
public String registerSubmit(#Valid StudentVO student, BindingResult result, Model model, HttpServletRequest request,
#RequestParam String action, #RequestParam(value = "parentID", required = false) String parentID,
#RequestParam(value = "studentID", required = false) String studentID,
RedirectAttributes redirectAttributes) {
if(result.hasErrors()){
model.addAttribute("student", student);
List<Map<String, String>> age = lookupService.getFields("age");
model.addAttribute("age", age);
return "studentSignup";
}
Thanks for help!

I found problem in my registerSubmit method I didn't mention #ModelAttribute, so code for method should look like:
#RequestMapping(value = { "/register/registerStudent" }, method = { RequestMethod.GET, RequestMethod.POST })
public String registerSubmit(#Valid #ModelAttribute StudentVO student, BindingResult result, Model model, HttpServletRequest request,
#RequestParam String action, #RequestParam(value = "parentID", required = false) String parentID,
#RequestParam(value = "studentID", required = false) String studentID,
RedirectAttributes redirectAttributes) {
if(result.hasErrors()){
model.addAttribute("student", student);
List<Map<String, String>> age = lookupService.getFields("age");
model.addAttribute("age", age);
return "studentSignup";
}

Related

Failed to convert value of type 'java.lang.String' to required type 'example.entity.Address'

#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="addresses")
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long add_id;
#Column
private String address;
#Column
private String postalcode;
#Column
private String city;
#Column
private String state;
#Column
private String country;
public Long getAdd_id() {
return add_id;
}
public void setAdd_id(Long add_id) {
this.add_id = add_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPostalcode() {
return postalcode;
}
public void setPostalcode(String postalcode) {
this.postalcode = postalcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
HTML Page :
<form
method="post"
role="form"
th:action="#{/address/save}"
th:object="${address}"
>
<input type="hidden" th:field="*{add_id}" />
<div class="form-group mb-3">
<label class="form-label">Address</label>
<input
class="form-control"
id="address"
name="address"
placeholder="Enter Address"
th:field="*{address}"
type="text"
/>
<p th:errors = "*{address}" class="text-danger"
th:if="${#fields.hasErrors('address')}"></p>
</div>
<div class="form-group mb-3">
<label class="form-label">Postal Code</label>
<input
class="form-control"
id="postalcode"
name="postalcode"
placeholder="Enter Postal Code"
th:field="*{postalcode}"
type="text"
/>
<p th:errors = "*{postalcode}" class="text-danger"
th:if="${#fields.hasErrors('postalcode')}"></p>
</div>
<div class="form-group mb-3">
<label class="form-label">City</label>
<input
class="form-control"
id="city"
name="city"
placeholder="Enter City"
th:field="*{city}"
type="text"
/>
<p th:errors = "*{city}" class="text-danger"
th:if="${#fields.hasErrors('city')}"></p>
</div>
<div class="form-group mb-3">
<label class="form-label">State</label>
<input
class="form-control"
id="state"
name="state"
placeholder="Enter State"
th:field="*{state}"
type="text"
/>
<p th:errors = "*{state}" class="text-danger"
th:if="${#fields.hasErrors('state')}"></p>
</div>
<div class="form-group mb-3">
<label class="form-label">Country</label>
<input
class="form-control"
id="country"
name="country"
placeholder="Enter Country"
th:field="*{country}"
type="text"
/>
<p th:errors = "*{country}" class="text-danger"
th:if="${#fields.hasErrors('country')}"></p>
</div>
<div class="form-group" style="text-align:center">
<button class="btn btn-success" type="submit">Save</button>
</div>
</form>
Controller:
#Autowired
private AddressRepository addressRepository;
#GetMapping("/address/{id}")
public String addAddress(#PathVariable("id") Long add_id, Model model){
System.out.println("\nInside addressform :\n");
#SuppressWarnings("deprecation")
Address address = addressRepository.getById(add_id);
System.out.println(address.getAdd_id());
System.out.println("add_id : "+add_id);
model.addAttribute("address", address);
return "addressform";
}
// handler method to handle post request to save address
#PostMapping("/address/save")
public String saveAddress(#Valid #ModelAttribute("address") Address address) {
System.out.println("\nInside address save method.");
System.out.println(address.getAdd_id());
System.out.println(address.getAddress());
System.out.println(address.getPostalcode());
System.out.println(address.toString());
addressRepository.save(address);
return "redirect:/users";
}
ERROR :
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'example.entity.Address'; Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'madhapur'
org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'example.entity.Address'; Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'madhapur'
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:79)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:53)
at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:729)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttributeFromRequestValue(ServletModelAttributeMethodProcessor.java:142)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:78)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:147)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:181)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:148)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
Firstly I figured out couple of codes that can cause serious performance issues and is not advised.
Here's a few:
Take off your Generated Getters and Setters and Leave the annotation #Getter and #Setter to do the work.
Take off <input type="hidden" th:field="*{add_id}" /> as it will be auto-generated from your entity Address private Long add_id
Take off address.toString() from your saveAddress controller as this is not needed to parse data to your Entity, your entity receives String already which will be parsed from your form, there is no need to convert with toString again.
One of your error states Failed to convert from type [java.lang.String] to type [java.lang.Long] which simply means you're trying to convert Long to String which should be auto generated by your Entity
I hope this helps!!!

Spring one-to-many Object in Thymeleaf Tab

I am using Spring and Thymeleaf templates. What I am trying is, to show a customer's addresses within a Thymeleaf template (using Bootstrap tabs) in a many-to-one relation.
I can't get the addresses to show up or add new ones. Any help is appreciated!
customerAddressform.html (Thymeleaf)
<html>
<head lang="en">
<!--/*/ <th:block th:include="fragments/headerinc :: head"></th:block> /*/-->
</head>
<body>
<div th:if="${not #lists.isEmpty(address)}">
<table class="table table-striped table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>Id</th>
<th>Address Id</th>
<th>Description</th>
<th>Price</th>
<th>Delete</th>
</tr>
</thead>
<tr th:each="address : ${address}">
<td th:text="${address.id}" href="/customer/${customer.id}/address/${address.id}">Id</td>
<td><a th:text="${address.addressId}" th:href="${ '/customer/' + customer.id + '/address/' + address.id}">Address
Id</a></td>
<td>description</td>
<td>price</td>
<td><a>Delete</a></td>
</tr>
</table>
</div>
<div>
<!-- Button trigger modal -->
<button type="button" href="#" class="btn-primary btn-sm btn-block btn-addrow" data-toggle="modal"
data-target="#modalNewCustomerAddress">+</button>
<!-- Modal -->
<div class="modal fade" id="modalNewCustomerAddress" tabindex="-1" role="dialog" aria-labelledby="New Address"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalScrollableTitle">New Address</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body margin-15">
<form id="customerAddressForm" th:object="${address}" th:action="#{/customer/{customer.id}/address/new}" method="post">
<div class="row">
<input type="hidden" />
<input type="hidden" />
<label for="streetName">Street:</label>
<input type="text" class="form-control form-control-lg" th:field="*{streetName}" id="streetName" />
<label for="houseNumber">House Number:</label>
<input type="text" class="form-control form-control-lg" id="houseNumber"/>
<label for="postalCode">Postal Code:</label>
<input type="text" class="form-control form-control-lg" id="postalCode"/>
<label for="city">City:</label>
<input type="text" class="form-control form-control-lg" id="city"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" form="customerAddressForm" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
AddressController.java
#Controller
public class AddressController {
private AddressService addressService;
#Autowired
public void setAddressService(AddressService addressService) {
this.addressService = addressService;
}
#RequestMapping(value = "/address", method = RequestMethod.GET)
public String list(Model model){
model.addAttribute("address", addressService.listAllAddress());
System.out.println("Returning address:");
return "customerAddress";
}
// #RequestMapping("address/{id}")
// public String showAddress(#PathVariable Integer id, Model model){
// model.addAttribute("address", addressService.getAddressById(id));
// return "addressshow";
// }
#RequestMapping("customer/{customer.id}/address")
public String edit(#PathVariable Integer id, Model model){
model.addAttribute("address", addressService.getAddressById(id));
return "customerAddressform";
}
#RequestMapping("customer/{customer.id}/address/new")
public String newAddress(Model model){
model.addAttribute("address", new Address());
return "customerAddressform";
}
// #RequestMapping(value = "address", method = RequestMethod.POST)
// public String saveAddress(Address address){
// addressService.saveAddress(address);
// //return "redirect:/addresss";
// return "redirect:/address/" + address.getId();
// }
#RequestMapping("customer/{customer.id}/deleteAddress")
public String deleteAddress(#RequestParam Integer id) {
addressService.deleteAddressById(id);
return "redirect:/customer/{customer.id}/address";
}
}
Address.java
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
private String addressId;
private String addressType;
private String streetName;
private String houseNumber;
private String postalCode;
private String cityName;
private String country;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "customer_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Customer customer;
public Address(){
}
public Address(String addressId, String addressType, String streetName, String houseNumber, String postalCode, String cityName, String country, Customer customer){
this.addressId = addressId;
this.addressType = addressType;
this.streetName = streetName;
this.houseNumber = houseNumber;
this.postalCode = postalCode;
this.cityName = cityName;
this.country = country;
this.customer = customer;
}
Customer.java
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
private String customerId;
private String name;
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer")
private Set<Address> address;

Null fields in Thymeleaf form using Spring Boot, other fields fine

I'm relatively new to Spring Boot. Currently, I'm making a Spring Boot application with user registration system but I've run into an issue. Some of the fields in a form are registering as ‘null’ on the back end, despite the request being posted correctly.
I have a HTML/ Thymeleaf form which submits 8 fields to create a 'User' object. This is the form:
<form th:action="#{/users/register_attempt}" th:object="${user}"
method="post" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">DOB: </label>
<div class="col-8">
<input type="text" th:field="*{dob}" class="form-control" th:required="required" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">First Name: </label>
<div class="col-8">
<input type="text" th:field="*{name}" class="form-control" th:required="required" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Surname: </label>
<div class="col-8">
<input type="text" th:field="*{surname}" class="form-control" th:required="required" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">PPSN: </label>
<div class="col-8">
<input type="text" th:field="*{ppsn}" class="form-control" th:required="required" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Address: </label>
<div class="col-8">
<input type="text" th:field="*{address}" class="form-control" th:required="required" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Phone Number: </label>
<div class="col-8">
<input type="number" th:field="*{phone}" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="email" th:field="*{email}" class="form-control" th:required="required" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" class="form-control"
required minlength="6" maxlength="10" th:required="required"/>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Sign Up</button>
</div>
</div>
</form>
And here is the model that the form code is meant to mimic:
public class User {
#Id
#GeneratedValue
private Long id;
#NotBlank
private String dob;
#NotBlank
private String name;
#NotBlank
private String surname;
#NotBlank
private String ppsn;
#NotBlank
private String address;
#NotBlank
private String phone;
#NotBlank
#Column(unique = true)
private String email;
private String nextApptId;
private String dose1Date;
private String dose2Date;
private String lastLogin;
#NotBlank
private String password;
public User() {
super();
}
public User(String dob, String name, String surname, String ppsn, String address, String phone, String email, String password) {
super();
this.dob = dob;
this.name = name;
this.surname = surname;
this.ppsn = ppsn;
this.address = address;
this.phone = phone;
this.email = email;
this.password = password;
}
public Long getId() {
return id;
}
public String getDob() {
return dob;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getPpsn() {
return ppsn;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNextApptId() {
return nextApptId;
}
public void setNextApptId(String apptId) {
this.nextApptId = apptId;
}
public String getDose1Date() {
return dose1Date;
}
public void setDose1Date(String dose1Date) {
this.dose1Date = dose1Date;
}
public String getDose2Date() {
return dose2Date;
}
public void setDose2Date(String dose2Date) {
this.dose2Date = dose2Date;
}
public String getLastLogin() {
return lastLogin;
}
public void setLastLogin(String lastLogin) {
this.lastLogin = lastLogin;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
But for some reason I can't figure out, the first four fields - i.e. Dob (date of birth), Name, Surname, and PPSN, are producing a null error when instantiating the user object on the server side, e.g.:
`Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 4 errors<EOL>
Field error in object 'user' on field 'dob': rejected value [null]; codes [NotBlank.user.dob,NotBlank.dob,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.dob,dob]; arguments []; default message [dob]]; default message [must not be blank] `.
The other four fields, Address, Phone, Email, and Password appear to be working just fine.
As far as I can make out, there it isn't a typo issue (forgive me if that ends up being the case). I have intercepted the Post request using Burp to check that the contents of the fields were making it out of the form and into the request, with the right names for the fields in my User class, and indeed they are all there as intended.
I imagine this means that the issue is coming from how the back end controller code is interpreting this post request based on the model, but I have no real idea of how or where to start. Here is the current controller:
#GetMapping("/register")
public String startRegistration(Model model) {
model.addAttribute("user", new User());
return "register";
}
#PostMapping("/register_attempt")
public String registerAttempt(#Valid User newUser) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encodedPassword = passwordEncoder.encode(newUser.getPassword());
newUser.setPassword(encodedPassword);
userRepository.save(newUser);
return "registered_successfully";
}
EDIT: Further debugging & clarification with issue persisting
Removing the #Valid annotation from the Post Mapping and using old fashioned print statements shows the same results - that the first four fields are null, for no obvious reason.
#PostMapping("/register_attempt")
public String registerAttempt(#ModelAttribute("user") User newUser) {
System.out.println("Saving user ");
System.out.println("Name " + newUser.getName());
System.out.println("Last Name " + newUser.getSurname());
System.out.println("PPSN " +newUser.getPpsn());
System.out.println("DOB " +newUser.getDob());
System.out.println("email " +newUser.getEmail());
System.out.println("address " +newUser.getAddress());
System.out.println("encrypted password " +newUser.getPassword());
System.out.println("Phone num " +newUser.getPhone());
userRepository.save(newUser);
System.out.println("User saved");
return "registered_successfully";
}
Using the following dummy data:
Which sends this Post Request to the back end:
Results in these print statements:
Saving user
name null
last Name null
ppsn null
dob null
email foo#bar.com
address Here and there
password password
Phone num 987654321
And these error messages:
javax.validation.ConstraintViolationException: Validation failed for classes [app.model.User] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=surname, rootBeanClass=class app.model.User, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=dob, rootBeanClass=class app.model.User, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=name, rootBeanClass=class app.model.User, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=ppsn, rootBeanClass=class app.model.User, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
]
If you have any insight into why this might be happening, I would very much appreciate it.
You have th:object="${user}" in your Thymeleaf template, so I have to assume that you #GetMapping method in your controller has added an instance of User to the Model using addAttribute.
In your #PostMapping, you should also use #ModelAttribute:
#PostMapping("/register_attempt")
public String registerAttempt(#Valid #ModelAttribute("user") User newUser) {
...
You also need to have setters for each field. I see that User has no setName(String name), no setDob(String dob), ...
Some other tips:
Do not create BCryptPasswordEncoder instances in your controller method itself. When you use Spring Boot, this should be an application wide singleton (Called a bean in Spring lingo). Add a class to your application e.g. ReservationSystemApplicationConfiguration which declares this:
#Configuration
public class ReservationSystemApplicationConfiguration {
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Then in your controller, inject the password encoder:
#Controller
#RequestMapping("...")
public class MyController {
private final PasswordEncoder passwordEncoder;
public MyController(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
#PostMapping("/register_attempt")
public String registerAttempt(#Valid #ModelAttribute("user") User newUser) {
String encodedPassword = passwordEncoder.encode(newUser.getPassword());
newUser.setPassword(encodedPassword);
userRepository.save(newUser);
return "registered_successfully";
}
}
A Controller should not directly call the Repository, but use a Service in between.
It is better to use different objects for mapping the form data and for storing the data into the database. See Form Handling with Thymeleaf for more information on how to do that.

Failed to convert property value of type [java.lang.String]

My spring application have problem with save 'date" to "database". where is mistake?
error
Failed to convert property value of type [java.lang.String] to
required type [java.sql.Date] for property bornDate; nested exception
is java.lang.IllegalArgumentException: Could not parse date:
Unparseable date: "2016-11-02"
mysql
use lifecalc;
create table Man (
manId int not null auto_increment primary key,
name varchar(30) not null,
bornDate date,
lastDate date
);
insert into man value
(null, "Pawel Cichon", "1920-11-30", "2000-02-20");
entity
#Entity
#Table(name="Man")
public class Man {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="manId")
private int manId;
#Column
private String name;
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Column
private java.sql.Date bornDate;
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Column
private java.sql.Date lastDate;
//getter end setter
controller
#Controller
#RequestMapping("/")
public class AppController {
#Autowired
private ManService manService;
#ModelAttribute("man")
public Man modelToAddMan(){
return new Man();
}
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, true));
}
#RequestMapping(value="/addMan.html", method = RequestMethod.POST)
public String addManFinish(#Valid #ModelAttribute("man") Man man, BindingResult result) {
if(result.hasErrors()){
return "addMan";
} else{
manService.addMan(man);
return "redirect:/index.html";
}
}
addMan.html
<form:form method="POST" modelAttribute="man">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">name</label>
<form:input path="name" />
<form:errors path="name" cssClass="error"/>
</div>
<div class="form-group">
<label for="bornDate" class="col-sm-2 control-label">bornDate</label>
<form:input path="bornDate" />
<form:errors path="bornDate" cssClass="error"/>
</div>
<div class="form-group">
<label for="lastDate" class="col-sm-2 control-label">lastDate</label>
<form:input path="lastDate" />
<form:errors path="lastDate" cssClass="error"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="save" /> <a
class="btn btn-danger" role="button"
href="<spring:url value="/index.html" />">cancel </a>
</div>
</form:form>
Instead of:
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Column
private java.sql.Date bornDate;
Use java.util.date:
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Column
private java.util.date bornDate;

Spring mvc #RequestBody String format

I have one Controller : personController.java
#Controller
public class personController {
private static final Logger LOG = LoggerFactory.getLogger(OcaController.class);
#RequestMapping(value = "/person", method = {RequestMethod.POST, RequestMethod.GET})
public String ocaContract(#RequestBody String requestPerson) {
return requestPerson;
}
1 JSP : person.jsp
<html>
<head>
</head>
<body>
<form class="form-horizontal" METHOD="POST" ACTION="webmvc/person" ENCTYPE="x-www-form-urlencoded">
<div class="controls">
<input type="text" name="name" id="name" value="" placeholder="">
</div>
<div class="controls">
<input type="text" name="surname" id="surname" value="" placeholder="">
</div>
<input type="submit" value="ok"/>
</form>
</body>
</html>
and one Object Class : Person.java
#XmlRootElement(name="Person")
public class Person {
#XmlElement(required = true)
protected String name;
#XmlElement(required = true, nillable = true)
protected String surname;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
} ...
When I populate the JSP and click on the input button, my controller return this "requestPerson" string :
name=&surname=
Is it a way to have this string as a POJO ? My final result must be at the XML format :
<person>
<name>Lisala</name>
<surname>Lili</surname></person>
I hope you ll can help me because i'm on it since 1 day now and i didn't find an easy way to accomplish this.
You can replace #RequestBody with #ModelAttribute and String to Person
public String ocaContract(#ModelAttribute Person requestPerson) {

Categories

Resources