Why is the controller saving the user with null property fields - java

Basically, Spring crashes with this error "value [null]; codes [NotNull.user.email,NotNull.email,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments []; default message [email]]; default message [must not be null], Field error in object 'user' on field 'firstName': rejected value [null]; codes" everytime I try to submit the completeProfile form. So, naturally, I looked at what data was saved after clicking submit on form. It turns out that the User object saved was having all the submitted property from the form as null. I checked inside the controller what was passed inside, all submitted properties from the form were null. Why does this happen?
User.java
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(min = 2, max = 80)
private String firstName;
#NotNull
#Size(min= 2, max = 80)
private String lastName;
#NotNull
#Email
private String email;
private Boolean enabled = false;
private String password = "";
private String role = "AUTHOR";
private String location = "";
private String topics = "";
private String job = "";
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTopics() {
return topics;
}
public void setTopics(String topics) {
this.topics = topics;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
completeProfile.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Complete your profile</p>
<form action="#" th:action="#{/completed-profile}" th:object="${user}" method="post">
<p>Email: <p th:text="${user.email}"></p>
<table>
<tr>
<td>Location:</td>
<td><input type="text" th:field="*{location}" /></td>
<td th:if="${#fields.hasErrors('location')}" th:errors="*{location}"></td>
</tr>
<tr>
<td>Job</td>
<td><input type="text" th:field="*{job}" /></td>
<td th:if="${#fields.hasErrors('job')}" th:errors="*{job}"></td>
</tr>
<tr>
<td>Topics of interest</td>
<td><input type="text" th:field="*{topics}" /></td>
<td th:if="${#fields.hasErrors('topics')}" th:errors="*{topics}"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" th:field="*{password}" /></td>
<td th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></td>
<td th:text="${password_error}"></td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
ProfileController.java
#Controller
public class ProfileController {
UserRepository userRepository;
public ProfileController(UserRepository userRepository) {
this.userRepository = userRepository;
}
#RequestMapping(value = {"/profile", "/profile.html"}, method = RequestMethod.GET)
public String profileForm(){
return "auth/profile";
}
#RequestMapping(value = "/complete-profile", method = RequestMethod.GET)
public String completeProfileForm(){
return "auth/completeProfile";
}
#RequestMapping(value = "/completed-profile", method = RequestMethod.POST)
public String submitProfileForm(#Valid User user, BindingResult bindingResult, Model model){
System.err.println(user.getEmail());
if (user.getPassword() == null || user.getPassword().equals("")){
// model.addAttribute("password_error", "password cannot be null");
model.addAttribute("user", user);
return "auth/completeProfile";
}
if(bindingResult.hasErrors()){
System.out.println(bindingResult.getAllErrors());
return "auth/completeProfile";
}
userRepository.save(user);
return "auth/login";
}
}

Related

Updating user through html form removes user's role in database

As the title says, I'm having difficulty in my Java + Spring/Hibernate project where when I go to update and Employee or Customers information, it removes their role from the employee_roles/customer_roles table in the database.
I had this same issue with the username being removed however, I was able to work around this by creating a hidden input form for the username in the html page.
The files for running this project can be found below, if you find that you can't get it to work properly on Mac, that may be because you will need to change the jdbc.url to just: jdbc:mysql://localhost:3306/spring_pie_deal
https://drive.google.com/file/d/1YAdaGCQXH-tjDy8EfnV0WagcV33I8ADM/view?usp=sharing
Employee:
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "username")
private String userName;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "phone_number")
private String phoneNumber;
#Column(name = "address")
private String address;
#Column(name = "zipcode")
private String zipcode;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "employee_roles",
joinColumns = #JoinColumn(name = "employee_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Collection<Role> roles;
public Employee() {
}
public Employee(String userName, String password, String firstName, String lastName, String email, String phoneNumber, String address, String zipcode) {
this.userName = userName;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
this.address = address;
this.zipcode = zipcode;
}
public Employee(String userName, String password, String firstName, String lastName, String email, String phoneNumber, String address, String zipcode, Collection<Role> roles) {
this.userName = userName;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
this.address = address;
this.zipcode = zipcode;
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
#Override
public String toString() {
return "Employee{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", address='" + address + '\'' +
", zipcode='" + zipcode + '\'' +
", roles=" + roles +
'}';
}
}
Role:
#Entity
#Table(name = "role")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
public Role() {
}
public Role(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Role{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
EmployeeDAOImpl:
#Repository
public class EmployeeDaoImpl implements EmployeeDAO{
#Autowired
private SessionFactory sessionFactory;
// define getEmployee method
#Override
public Employee getEmployee(Long theId) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// get Employee by the id
Employee theEmployee = currentSession.get(Employee.class, theId);
// return the employee
return theEmployee;
}
// define saveEmployee method
#Override
public void saveEmployee(Employee theEmployee) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// save Employee by the id
currentSession.saveOrUpdate(theEmployee);
}
// define deleteEmployee method
#Override
public void deleteEmployee(Long theId) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// delete Employee by id
currentSession.delete(theId);
}
#Override
public List<Employee> getEmployees() {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create query
Query<Employee> theQuery =
currentSession.createQuery("from Employee order by lastName", Employee.class);
// apply result list to variable list
List<Employee> theEmployees = theQuery.getResultList();
// return the result list variable
return theEmployees;
}
#Override
public Employee findByUserName(String userName) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// now create query... where username(from database) matches uName(direct relationship with userName1)
Query<Employee> theQuery = currentSession.createQuery("from Employee where username=:uName", Employee.class);
theQuery.setParameter("uName", userName);
Employee theEmployee = null;
try {
theEmployee = theQuery.getSingleResult();
}
catch (Exception e) {
theEmployee =null;
}
return theEmployee;
}
#Override
public void save(Employee employee) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create or save user
currentSession.saveOrUpdate(employee);
}
}
Employee-form.jsp:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html>
<html>
<head>
<title>Update Employee</title>
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css">
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/add-customer-style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>ERM - Employee Relationship Manager</h2>
</div>
</div>
<div id="container">
<h3>Update Employee</h3>
<form:form action="saveEmployee"
modelAttribute="employee">
<!-- need to associate this data with a employee id -->
<form:hidden path="id" />
<table>
<tbody>
<tr>
<td><form:input type="hidden" path="userName" /></td>
</tr>
<tr>
<td><form:input type="hidden" path="password" /></td>
</tr>
<tr>
<td><label>First name:</label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><label>Last name:</label></td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td><label>Email:</label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><label>Phone Number:</label></td>
<td><form:input path="phoneNumber" /></td>
</tr>
<tr>
<td><label>Address:</label></td>
<td><form:input path="address" /></td>
</tr>
<tr>
<td><label>Zip Code:</label></td>
<td><form:input path="zipcode" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear; both;"></div>
<!-- Add a logout button -->
<form:form action="${pageContext.request.contextPath}/logout"
method="POST">
<input type="submit" value="Logout" />
</form:form>
<p>
Back to List
</p>
</div>
</body>
</html>

Thymeleaf not able to post collections / lists of objects

I'm creating a web-application with spring MVC, hibernate and thymeleaf.
I have a page where I can manage users, on this page you should be able to place and remove users from groups.
I am doing this with 2 multiple select boxes.
I added a jquery script what handles the movement of users from the one select box to the other one.
But when i submit, my Group.users object list is empty and I do not get any exceptions.
Does anyone has some advice?
Thanks in advance.
Edit
I just discovered that all thymeleaf attributes inside the html tag "option", aren't compiled. Except for the th:each attr.
So it's pretty clear the problem is in my thymeleaf file.
Thymeleaf / edit.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<div th:replace="template :: css"></div>
<title>Edit group</title>
</head>
<body>
<script>
$(document).ready(function() {
$(".clickable").click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected").addClass("unselected");
$('#userGroupContainer').append(this);
$("option:selected").css("background-color", "red");
} else {
$(this).removeClass("unselected").addClass("selected");
$('#userGroupContainerSelected').append(this);
$("option:selected").css("background-color", "green");
}
});
});
</script>
<div id="bodyWrap">
<div th:replace="template :: logo">Logo</div>
<div th:replace="template :: nav">Nav</div>
<div th:replace="template :: messages">Header</div>
<div id="backGround">
<div id="contentWrap">
<form action="#{edit}"
th:action="#{${#httpServletRequest.servletPath}}"
th:object="${group}" th:method="post">
<h1 th:unless="${group.id}">Add group</h1>
<h1 th:if="${group.id}">Edit group</h1>
<hr />
<div th:replace="template :: messages">Header</div>
<div class="newFile">
<input type="hidden" th:field="*{id}" />
<table class="newFile">
<tr>
<th>Name:</th>
<td><input type="text" size="50" th:field="${group.name}" /></td>
</tr>
<tr>
<th>Description:</th>
<td><textarea th:field="${group.description}"></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
<br /> users <br />
<select multiple="multiple" id="userGroupContainer">
<option th:each="u : ${userNotInGroup}" th:text="${u.displayName}" class="clickable unselected" th:value="${u}" ></option>
</select>
<!-- It's all about the select box under this comment -->
<select multiple="multiple" id="userGroupContainerSelected" th:field="*{users}">
<option th:each="ug, rowStat : ${group.users}" th:text="${ug.displayName}" th:value="${ug}" class="clickable selected">Selected</option>
</select>
<div class="form-actions">
<button th:unless="${group.id}" type="submit">Add</button>
<button th:if="${group.id}" type="submit">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
example of the 2 multiple select boxes:
$(document).ready(function() {
$(".clickable").click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected").addClass("unselected");
$('#userGroupContainer').append(this);
$("option:selected").css("background-color", "red");
} else {
$(this).removeClass("unselected").addClass("selected");
$('#userGroupContainerSelected').append(this);
$("option:selected").css("background-color", "green");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<select multiple="multiple" id="userGroupContainer">
<option class="clickable unselected" >Example</option>
</select>
<select multiple="multiple" id="userGroupContainerSelected" th:field="*{users}">
<option class="clickable selected">Selected</option>
</select>
Controller:
#RequestMapping(value = "/management/edit/{groupId}", method = RequestMethod.GET)
public String editGroup(ModelMap model, Principal principal, #PathVariable("groupId") Long groupId) {
Group group = groupService.findGroupById(groupId);
User user = new User();
List<User> userNotInGroup = userService.findUsersNotInGroup(group);
model.addAttribute("userNotInGroup", userNotInGroup);
model.addAttribute("group", group);
return "management/groups/edit";
}
#RequestMapping(value = "/management/edit/{groupId}", method = RequestMethod.POST)
public String editGroup(#Valid Group group, BindingResult result, Model model, #PathVariable("groupId") Long groupId) {
model.addAttribute("group", group);
System.out.println("USERS: " + group.getUsers());
groupService.saveGroup(group);
return "redirect:/management/list";
}
Group Entity / object:
#Entity
#Table(name = "GROUPS")
public class Group extends DomainObject {
private static final long serialVersionUID = ;
#Id
#GeneratedValue(generator = "GROUPS_SEQ", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "GROUPS_SEQ", sequenceName = "GROUPS_SEQ")
private Long id;
#Column(name = "NAME")
private String name;
#Column(name = "DESCRIPTION")
private String description;
#JoinTable(name = "USERS_GROUPS")
#ManyToMany(fetch = FetchType.EAGER)
private Collection<User> users;
#JoinTable(name = "GROUPS_ROLES")
#ManyToMany
private Collection<Role> roles;
public Collection<User> getUsers() {
return users;
}
public void setUsers(Collection<User> users) {
this.users = users;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
}
User Entity / Object:
#Entity
#Table(name = "USERS")
public class User extends DomainObject implements UserDetails {
private static final long serialVersionUID = ;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#NotNull
private Long ID;
#Column(name = "DISPLAY_NAME")
#NotNull
private String displayName;
#Column(name = "EMAIL_ADDRESS")
#NotNull
private String emailAddress;
#Column(name = "PASSWORD")
private String password;
#Column(name = "USERNAME")
#NotNull
private String username;
#Column(name = "LAST_LOGIN")
private Date lastLogin;
#Column(name = "MODIFIED_DATE")
private Date modifiedDate;
#Column(name = "MODIFIED_BY")
private String modifiedBy;
#Transient
private Collection<? extends GrantedAuthority> authorities;
private boolean admin;
#Nullable
#JoinTable(name = "USERS_GROUPS")
#ManyToMany
private Collection<Group> groups;
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public Collection<Group> getGroups() {
return groups;
}
public void setGroups(Collection<Group> groups) {
this.groups = groups;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
#Override
public Long getId() {
return ID;
}
#Override
public void setId(Long id) {
this.ID = id;
}
}

JSP cannot detect new added element in java model class

Here is my java model class - CustomerProperty.java
package model;
import java.io.InputStream;
public class CustomerProperty {
public CustomerProperty() {
}
public int propertyid;
public String name;
public String phone;
public String occupation;
public String address1;
public String address2;
public String postcode;
public String city;
public String state;
public String payment;
public InputStream photo;
public String agent;
public String IDproject;
public String[] quickSale;
public String ICnumber;
public String bag;
public String mydate;
public int getPropertyid() {
return propertyid;
}
public void setPropertyid(int propertyid) {
this.propertyid = propertyid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getICnumber() {
return ICnumber;
}
public void setICnumber(String ICnumber) {
this.ICnumber = ICnumber;
}
public String getICNUMBER() {
return ICnumber;
}
public void setICNUMBER(String ICnumber) {
this.ICnumber = ICnumber;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String dateTime) {
this.state = dateTime;
}
public String getPayment() {
return payment;
}
public void setPayment(String payment) {
this.payment = payment;
}
public InputStream getPhoto() {
return photo;
}
public void setPhoto(InputStream photo) {
this.photo = photo;
}
public String getAgent() {
return agent;
}
public void setAgent(String agent) {
this.agent = agent;
}
public String getIDproject() {
return IDproject;
}
public void setIDproject(String IDproject) {
this.IDproject = IDproject;
}
public String[] getQuickSale() {
return quickSale;
}
public void setQuickSale(String[] quickSale) {
this.quickSale = quickSale;
}
public String getMyDate() {
return mydate;
}
public void setMyDate(String mydate) {
this.mydate = mydate;
}
Whenever my JSP calling this java class, it only can detect the original element. I have added a new element - mydate and it is like forever cannot detect it.
Below is the error code.
pe Exception report
messageInternal Server Error
descriptionThe server encountered an internal error that prevented it
from fulfilling this request.
exception
org.apache.jasper.JasperException: javax.el.PropertyNotFoundException:
The class 'model.CustomerProperty' does not have the property
'mydate'. root cause
javax.el.PropertyNotFoundException: The class 'model.CustomerProperty'
does not have the property 'mydate'. note The full stack traces of the
exception and its root causes are available in the GlassFish Server
Open Source Edition 4.0 logs.
I have try to delete the java class and recreate again but still, the JSP only can detect for my first 16 elements and not any new added element.
Any solutions? Thanks
Below is my JSP file code.
<head>
<title>Project Sales Report</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">
</head>
<body>
<p align="center" style="font-family:times;font-size:40pt"><c:out value="${project2.projectName}"/> Sales Report</p>
<table align="center" bgcolor="silver" border="1" cellspacing="0" cellpadding="20" class="customer" >
<thead>
<tr>
<th>Unit ID</th>
<th>Agent</th>
<th>Customer Name</th>
<th>IC Number</th>
<th>Phone Number</th>
<th>Occupation</th>
<th>Address 1</th>
<th>Address 2</th>
<th>Postcode</th>
<th>City</th>
<th>State</th>
<th>Payment Type</th>
<th>Receipt</th>
</tr>
</thead>
<tbody>
<c:forEach items="${customerdetail}" var="abc">
<tr>
<td><c:out value="${abc.propertyid}"/></td>
<td><c:out value="${abc.agent}" /></td>
<td><c:out value="${abc.name}" /></td>
<td><c:out value="${abc.ICnumber}" /></td>
<td><c:out value="${abc.phone}" /></td>
<td><c:out value="${abc.occupation}" /></td>
<td><c:out value="${abc.address1}" /></td>
<td><c:out value="${abc.address2}" /></td>
<td><c:out value="${abc.postcode}" /></td>
<td><c:out value="${abc.city}" /></td>
<td><c:out value="${abc.mydate}" /></td>
<td><c:out value="${abc.payment}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
<p> </p>
<div align="center">
<button type="button" style="width:70px;">Print</button>
<input type="button" value="Back" onClick="history.go(-1);
return true;" style="width:70px;"/>
</div>
</body>
Note your getter setters -
public String mybag() {
return mydate;
}
public void setmybag(String mydate) {
this.mydate = mydate;
}
It should be setMydate and getMydate. isn't it ?
Update -
It is case sensative.
public String mydate;
this should be
public String myDate;
Your JSP should be abc.myDate and not abc.mydate
<td><c:out value="${abc.mydate}" /></td>

Retrieve embedded documents from mongoDB

The below data is stored in MongoDB. I am using Spring-Data and storing the data into mongoDB.
If I want to retrieve the fields ("id" or "Name") I can able to do, but if I want to retrieve the sub fields ("firstName" or "lastName")I can't.
(eg.)If I want to retrieve sub field "lastName" from the below data I can't.Kindly help me in this regard.
Thanks in advance.
Data Stored in MongoDB:
{
"id":101,
"name": {"firstName":"Mark",
"lastName":"Antony"
}
}
The Code I am using is:
PersonService.java
public List<Audit> searchPerson(Audit audit)
{
List<NameDetails> name=audit.getName();
return mongoTemplate.find(new Query(Criteria.where("name.lastName").is(name.get(0))), Audit.class,COLLECTION_NAME);
}
PersonController.java
#RequestMapping(value = "/person/search", method = RequestMethod.GET)
public String search(#ModelAttribute Audit audit, ModelMap model) {
model.addAttribute("personList", personService.searchPerson(audit));
return "output";
}
Audit.java
#Document
public class Audit {
#Id
private String id;
private List<NameDetails> name;
public String getId() {
System.out.println("Person: getId");
return id;
}
public void setId(String id) {
System.out.println("Person: setId");
this.id = id;
}
public List<NameDetails> getName() {
System.out.println("Audit: getName");
return name;
}
public void setName(List<NameDetails> name) {
System.out.println("Audit: setName");
this.name = name;
}
}
NameDetails.java
package com.register.mongo.model;
public class NameDetails {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
System.out.println("NameDetails: setFirstName");
this.firstName = firstName;
}
public String getLastName() {
System.out.println("NameDetails: getLastName");
return lastName;
}
public void setLastName(String lastName) {
System.out.println("NameDetails: setLastName");
this.lastName = lastName;
}
}
(output.jsp)UI Page
<form action="person/search" method="get">
<table>
<tr><td>
<label>Name</label>
<input type="text" id="lastName" name="lastName"/>
</td></tr>
<tr><td>
<input type="submit" value="Search"/>
</td></tr>
</table>
</form>
<table border="2">
<c:forEach var="person" items="${personList}">
<tr>
<td>${person.id}</td>
</tr>
<tr>
<td>${person.lastName}</td>
</tr>
</c:forEach>
</table>
Change
return mongoTemplate.find(
new Query(Criteria.where("name.lastName").is(name.get(0))),
Audit.class,COLLECTION_NAME);
to
return mongoTemplate.find(
new Query(Criteria.where("name.lastName").is(name.get(0).getLastName())),
Audit.class,COLLECTION_NAME);
You are trying to use the entire NameDetails instead of just the last name.

Spring form send null model object to database

I want to send data from form to PostgreSQL. When I send data by form, hibernate save (by save() method) blank record .. I did it manually (for test) without using form and then everything is ok.
Spitter.class (entity for user)
#Entity
#Table(name="spitter")
public class Spitter implements Serializable {
private static final long serialVersionUID = 829803238866007413L;
#Id
//#SequenceGenerator(name = "hibernate_sequence")
#GeneratedValue(strategy=GenerationType.AUTO) #Column(name="spitter_id")
private Long id;
#Column(unique=true) #Size(min=3, max=20) #Pattern(regexp = "^[a-zA-Z0-9]+$", message="Nie poprawna nazwa uzytkownika.")
private String username;
#Size(min=5, max=15, message="Haslo musi miec minimum 5 znakow.")
private String password;
#Size(min=3, max=25, message="Blad w imieniu i nazwisku.")
private String fullName;
#OneToMany(mappedBy="spitter")
private List<Spittle> spittles;
#Email(message="Nie poprawny adres email.")
private String email;
private boolean updateByEmail;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public List<Spittle> getSpittles() {
return spittles;
}
public void setSpittles(List<Spittle> spittles) {
this.spittles = spittles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setUpdateByEmail(boolean updateByEmail) {
this.updateByEmail = updateByEmail;
}
public boolean isUpdateByEmail() {
return updateByEmail;
}
#Override
public boolean equals(Object obj) {
Spitter other = (Spitter) obj;
return other.fullName.equals(fullName) && other.username.equals(username) && other.password.equals(password);
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
}
SpitterController.class
createSpitterProfile - shows form (edit.jsp) and sends model object (spitter) to form
addSpitterFromForm - receives binding data from form and save it to database and redirects to simply user profile
showSpitterProfile - there is of course null model object exception
#Controller
#RequestMapping("/spitters")
public class SpitterController {
private final SpitterService spitterService;
#Inject //#Autowired
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
//...
#RequestMapping(method = RequestMethod.GET, params = "new")
public String createSpitterProfile(Model model) {
model.addAttribute("spitter", new Spitter());
return "spitters/edit";
}
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(#Valid Spitter spitter, BindingResult bindingResult) {
if(bindingResult.hasErrors())
return "spitters/edit";
spitterService.saveSpitter(spitter);
return "redirect:/spitters/" + spitter.getUsername();
}
#RequestMapping(value="/{username}", method = RequestMethod.GET)
public String showSpitterProfile(#PathVariable String username, Model model) {
model.addAttribute(spitterService.getSpitter(username));
return "spitters/view";
}
edit.jsp (registration form for new user (Spitter))
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<div>
<h2>New account test</h2>
<sf:form method="POST" modelAttribute="spitter"
enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<th><sf:label path="fullName">Full name:</sf:label></th>
<td><sf:input path="fullName" size="15" /><br/>
<sf:errors path="fullName" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="username">Username:</sf:label></th>
<td><sf:input path="username" size="15" maxlength="15" />
<small id="username_msg">No spaces, please.</small><br/>
<sf:errors path="username" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="password">Password:</sf:label></th>
<td><sf:password path="password" size="30"
showPassword="true"/>
<small>6 characters or more (be tricky!)</small><br/>
<sf:errors path="password" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="email">Email Address:</sf:label></th>
<td><sf:input path="email" size="30"/>
<small>In case you forget something</small><br/>
<sf:errors path="email" cssClass="error" />
</td>
</tr>
<tr>
<th></th>
<td>
<sf:checkbox path="updateByEmail"/>
<sf:label path="updateByEmail">Send me email updates!</sf:label>
</td>
</tr>
<tr>
<th></th>
<td>
<input name="commit" type="submit"
value="I accept. Create my account." />
</td>
</tr>
</table>
</fieldset>
</sf:form>
</div>
and blank saved record to Postgres..
Try adding #modelattribute in this method .It fill fetch the required model object.
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(**#ModelAttribute("spitter")** #Valid Spitter spitter, BindingResult bindingResult) {
if(bindingResult.hasErrors())
return "spitters/edit";
spitterService.saveSpitter(spitter);
return "redirect:/spitters/" + spitter.getUsername();
}
and just to check if it is getting the values from form,syso some values like syso(spitter.getUserName) to check if values are coming.
ALso, I believe that you are making a constructor and passing service to it ,so there is no need of #Inject
#Inject //#Autowired///Why are you injecting it if it is a constructor?
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
You have enctype="multipart/form-data in your FORM,
Check that you have something like that in your App-servlet.xml:
<bean id="multipartResolver" class=
"org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:maxUploadSize="500000" />

Categories