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>
Related
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";
}
}
Hello I'm new with Spring and cannot find the mistake =( I'm using Spring MVC and want to select User bean for Client with one to many mapping. When I trying to save new Client I get a mistake.
HTTP Status 400 – Bad Request
Type Status Report
Description The server cannot or will not process the request due to
something that is perceived to be a client error (e.g., malformed
request syntax, invalid request message framing, or deceptive request
routing).
User Bean
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="surname")
private String surname;
#Column(name="name")
private String name;
#Column(name="second_name")
private String secondName;
#Column(name="phone_number")
private String phoneNumber;
#Column(name="type")
#Enumerated(EnumType.STRING)
private UserType type;
#OneToMany(mappedBy="user",
fetch = FetchType.LAZY
// , cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}
)
private List<Client> clients;
public User() {
}
public User(String surname, String name, String secondName, String phoneNumber, UserType type) {
this.surname = surname;
this.name = name;
this.secondName = secondName;
this.phoneNumber = phoneNumber;
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public UserType getType() {
return type;
}
public void setType(UserType type) {
this.type = type;
}
public List<Client> getClients() {
return clients;
}
public void setClients(List<Client> clients) {
this.clients = clients;
}
public void add(Client tempClient) {
if(clients == null) {
clients = new ArrayList<>();
}
clients.add(tempClient);
tempClient.setUser(this);
}
#Override
public String toString() {
return "User [id=" + id + ", surname=" + surname + ", name=" + name + ", secondName=" + secondName
+ ", phoneNumber=" + phoneNumber + ", type=" + type + "]";
}
Client Bean
#Entity
#Table(name="client")
public class Client {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="turnover")
private long turnover;
#ManyToMany(
//fetch = FetchType.LAZY,
//cascade= {CascadeType.PERSIST, CascadeType.MERGE,
// CascadeType.DETACH, CascadeType.REFRESH}
)
#JoinTable(
name="activity_client",
joinColumns = #JoinColumn(name="client_id"),
inverseJoinColumns=#JoinColumn(name="activity_id"))
private List<Activity> activities;
#ManyToOne(
//cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}
)
#JoinColumn(name="user_id")
private User user;
#Column(name="status")
#Enumerated(EnumType.STRING)
private ClientStatus status;
#OneToMany(mappedBy="client"
// , cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}
)
private List<ContactPerson> contactPersons;
#OneToMany(mappedBy="client"
// , cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH}
)
private List<Action> actions;
public Client() {
}
public Client(String name, long turnover, ClientStatus status) {
this.name = name;
this.turnover = turnover;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTurnover() {
return turnover;
}
public void setTurnover(long turnover) {
this.turnover = turnover;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public ClientStatus getStatus() {
return status;
}
public void setStatus(ClientStatus status) {
this.status = status;
}
public List<ContactPerson> getContactPersons() {
return contactPersons;
}
public void setContactPersons(List<ContactPerson> contactPersons) {
this.contactPersons = contactPersons;
}
public List<Action> getActions() {
return actions;
}
public void setActions(List<Action> actions) {
this.actions = actions;
}
public void add(ContactPerson tempContactPerson) {
if(contactPersons == null) {
contactPersons = new ArrayList<>();
}
contactPersons.add(tempContactPerson);
tempContactPerson.setClient(this);
}
public void add(Action tempAction) {
if(actions == null) {
actions = new ArrayList<>();
}
actions.add(tempAction);
tempAction.setClient(this);
}
public void add(Activity tempActivity) {
if(activities==null) {
activities = new ArrayList<>();
}
activities.add(tempActivity);
}
public List<Activity> getActivities() {
return activities;
}
public void setActivities(List<Activity> activities) {
this.activities = activities;
}
#Override
public String toString() {
return "Client [id=" + id + ", name=" + name + ", turnover=" + turnover + ", status=" + status + "]";
}
}
Controller for Client
#Controller
#RequestMapping("/client")
public class ClientController {
#Autowired
private ClientService clientService;
#Autowired
private UserService userService;
#GetMapping("/list")
public String listClients(Model theModel) {
List<Client> theClients = clientService.getClients();
theModel.addAttribute("clients", theClients);
return "client/list-clients";
}
#GetMapping("/showFormForAdd")
public String showFormForAdd(Model theModel) {
Client theClient = new Client();
theModel.addAttribute("client", theClient);
theModel.addAttribute("clientStatus", ClientStatus.values());
List<User> users = userService.getUsers();
theModel.addAttribute("clientUser", users);
return "client/client-form";
}
#PostMapping("/saveClient")
public String saveClient(#ModelAttribute("client") Client theClient) {
clientService.saveClient(theClient);
return "redirect:/client/list";
}
#GetMapping("/showFormForUpdate")
public String showFormForUpdate(#RequestParam("clientId") int theId, Model theModel) {
Client theClient = clientService.getClient(theId);
theModel.addAttribute("client", theClient);
theModel.addAttribute("clientType", ClientStatus.values());
return "client/client-form";
}
#GetMapping("/delete")
public String deleteClient(#RequestParam("ClientId") int theId) {
clientService.deleteClient(theId);
return "redirect:/client/list";
}
}
JSP for Client
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title> Save Client</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-target-style.css"/>
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>CRM - Customer Relationship Manager</h2>
</div>
</div>
<div id="container">
<h3>Save User</h3>
<form:form action="saveClient" modelAttribute="client" method="POST">
<form:hidden path="id"/>
<table>
<tbody>
<tr>
<td><label> Name:</label></td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td><label> Turnover:</label></td>
<td><form:input path="turnover"/></td>
</tr>
<tr>
<td><label> Manager:</label></td>
<td>
<form:select path="user">
<form:options items="${clientUser}" itemValue="id" itemLabel="surname" />
</form:select>
</td> </tr>
<tr>
<td><label> Status:</label></td>
<td>
<form:select path="status">
<form:options items="${clientStatus}" itemLabel="status" />
</form:select>
</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>
<p>
Back to List
</p>
</div>
</body>
</html>
If I comment next peace of code its work OK
<tr>
<td><label> Manager:</label></td>
<td>
<form:select path="user">
<form:options items="${clientUser}" itemValue="id"
itemLabel="surname" />
</form:select>
/td>
I try to search this question in internet but example of code looks like the same as my. Please help me to find the mistake ;)
This I have in Tomcat logs
127.0.0.1 - - [20/Nov/2017:12:24:56 +0200] "GET / HTTP/1.1" 404 1073 0:0:0:0:0:0:0:1 - - [20/Nov/2017:12:25:05 +0200] "GET /crmdemo/
HTTP/1.1" 302 - 0:0:0:0:0:0:0:1 - - [20/Nov/2017:12:25:12 +0200] "GET
/crmdemo/target/list HTTP/1.1" 200 944 0:0:0:0:0:0:0:1 - -
[20/Nov/2017:12:25:28 +0200] "GET /crmdemo/client/list HTTP/1.1" 200
652 0:0:0:0:0:0:0:1 - - [20/Nov/2017:12:25:30 +0200] "GET
/crmdemo/client/showFormForAdd HTTP/1.1" 200 1726 0:0:0:0:0:0:0:1 - -
[20/Nov/2017:12:25:30 +0200] "GET
/crmdemo/resources/css/add-target-style.css HTTP/1.1" 304 -
0:0:0:0:0:0:0:1 - - [20/Nov/2017:12:25:38 +0200] "POST
/crmdemo/client/saveClient HTTP/1.1" 400 1130
I find an answer. I need to put .id in path
<td>
<form:select path="user.id">
<form:options items="${clientUser}" itemValue="id"
itemLabel="surname" />
</form:select>
</td>
I have searched around but can't find any help.
I'm trying to create a user but 2 fields keeps being null (firstname and department).
The Gui (html):
<div style="width: 900px; margin-left: auto; margin-right: auto">
<form action="EmployeesAddManager.jsp" method="post">
Firstname:<br>
<input type="text" name="firstname" style="width: 200px"><br>
Lastname:<br>
<input type="text" name="lastname" style="width: 200px"><br>
Gender:
<select name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
Email:<br>
<input type="text" name="email" style="width: 200px"><br>
Role:
<select name="role">
<option value="Department Leader">Department Leader</option>
<option value="Assistant">Assistant</option>
</select><br>
Department:
<select name="department">
<option value="Tetriz">Tetriz</option>
<option value="Cube">Cube</option>
</select><br>
Image:<br>
<input type="text" name="image" style="width: 200px"><br>
Username:<br>
<input type="text" name="username" style="width: 200px"><br>
Password:<br>
<input type="text" name="password" style="width: 200px"><br>
<input type="submit" value="Create Employee">
</form>
</div>
Already in the 'EmployeesAddManager.jsp' I try to print out the inputs, but firstname and department will be null (all the others works):
<%#page import="model.EmployeeModel"%>
<%#page import="model.Employees"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
//We get the fulfilled parameters
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String gender = request.getParameter("gender");
String email = request.getParameter("email");
String role = request.getParameter("role");
String department = request.getParameter("department");
String image = request.getParameter("image");
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("Firstname from EmployeesAddManager.jsp: "+firstname);
System.out.println("Lastname from EmployeesAddManager.jsp: "+lastname);
System.out.println("Department from EmployeesAddManager.jsp: "+department);
//We instantiate an employee and set the parameters
Employees emp = new Employees(0, firstname, lastname, gender, email, role, department, image, username, password);
//We call for the method for creating a new employee, and send the new instantiated employee
EmployeeModel empModel = new EmployeeModel();
empModel.newEmployee(emp);
/*This method is used to redirect client request to some other location
for further processing ,the new location is available on different server
or different context.our web container handle this and transfer the request
using browser ,and this request is visible in browser as a new request.
Some time this is also called as client side redirect.
*/
response.sendRedirect("/Employees_servlet");
%>
</body>
</html>
And here the Model thats connect to the database:
public void newEmployee(Employees emp) throws SQLException{
try {
PreparedStatement ps = DbModel2.getPreparedStatement("INSERT INTO employee_table (Id_employee, Firstname, Lastname, Gender, Email, RoleId_Fk, DepartmentId_Fk, Image) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1, emp.getId());
ps.setString(2, emp.getFirstname());
ps.setString(3, emp.getLastname());
ps.setString(4, emp.getGender());
ps.setString(5, emp.getEmail());
ps.setString(6, emp.getRole());
ps.setString(7, emp.getDepartment());
ps.setString(8, emp.getImage());
System.out.println("Id: "+emp.getId());
System.out.println("Firstname: "+emp.getFirstname());
System.out.println("Lastname: "+ emp.getLastname());
System.out.println("Gender: "+emp.getGender());
System.out.println("Email: "+emp.getEmail());
System.out.println("Role: "+emp.getRole());
System.out.println("Department: "+emp.getDepartment());
System.out.println("Image: "+emp.getImage());
ps.executeUpdate();
System.out.println("EXECUTED");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The Employees.java:
public class Employees {
private int id;
private String firstname;
private String lastname;
private String gender;
private String email;
private String role;
private String department;
private String image;
private String username;
private String password;
public Employees(int id, String firstname, String lastname, String gender, String email, String role, String department, String image, String username, String password) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.gender = gender;
this.email = email;
this.role = role;
this.department = department;
this.image = image;
this.username = username;
this.password = password;
System.out.println("this.firstname: "+firstname);
System.out.println("this.department: "+department);
System.out.println("getFirstname: "+getFirstname());
System.out.println("getDepartment: "+getDepartment());
}
public int getId() {
return id;
}
public void setId(int 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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
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;
}
}
Because in getters you have done it like
return department change that to this.department and same goes for firstname
Edit:
It worked in your case, as I just wanted to enforce the values using this but I need to understand why it didn't work before.
I did not try this code and this may sound bit childish but did you try changing the name? Have you checked for white spaces?
I would like to build a form to save an User. I have 2 tables, User and UserRole as described in Spring Security. To save an user I need to create a User Object that contains a field Set. I want to create a list of checkboxes and map them into an Set of UserRoles, but I don't know how to map them with checkboxes. I have the following classes:
#Controller
public class UserController {
#Autowired
IUserService userService;
/** Default GET form handler for users, in submission will call saveRegistration */
#RequestMapping(value="/createuser", method=RequestMethod.GET)
public String createUser(Model model) {
// User form will be bind to this User object
model.addAttribute("user", new User());
// Code about adding the user roles to JSP?
// Maybe something like this?:
// User u = new User ("useruser","123456",false);
// Set<UserRole> roles = new HashSet<UserRole>();
// roles.add(new UserRole(u,"ROLE_ADMIN"));
// roles.add(new UserRole(u,"ROLE_USER"));
// model.addAttribute("roles", roles);
return "createuser";
}
/** This method will be called on form submission, handling POST request,
* It also validates the user input */
#RequestMapping(value="/createuser", method=RequestMethod.POST)
public String doCreateUser(Model model, #Valid User user, BindingResult result) {
if(result.hasErrors()) {
return "createuser";
}
userService.createUser(user,user.getUserRole()) //createUser(User user, Set<UserRole> role)
return "success";
}
}
My JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="resources/css/createuser.css" />
</head>
<body onload='document.createUserForm.username.focus();'>
<sf:form name="createUserForm" method="post"
action="${pageContext.request.contextPath}/createuser"
commandName="user">
<table class="formtable">
<tr>
<td class="label">Username:</td>
<td><sf:input class="control" path="username" name="username"
type="text" /><br />
<div class="error">
<sf:errors path="username"></sf:errors>
</div></td>
</tr>
<tr>
<td class="label">Role:</td>
<td>
<ul>
<sf:checkboxes element="li" path="userRole" items="${roles}"></sf:checkboxes>
</ul></td>
</tr>
<tr>
<td class="label">Password:</td>
<td><sf:input class="control" path="password" name="password"
type="password" />
<div class="error">
<sf:errors path="password"></sf:errors>
</div></td>
</tr>
<tr>
<td class="label">Confirm Password:</td>
<td><input class="control" name="confirmpass" type="password" />
<div class="error">
<sf:errors path="password"></sf:errors>
</div></td>
</tr>
<tr>
<td class="label"></td>
<td><input class="control" value="Create account" type="submit" /></td>
</tr>
</table>
</sf:form>
User Role:
public class UserRole {
private Integer userRoleId;
private User user;
private String role;
public UserRole () {
}
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "user_role_id",
unique = true, nullable = false)
public Integer getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "username", nullable = false)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Column(name = "role", nullable = false, length = 45)
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String toString () {
return role;
}
}
And User:
public class User {
#NotNull
#NotBlank(message="Username cannot be blank.")
#Size(min=4, max=15, message="Username must be between 4 and 15 characters long.")
#Pattern(regexp="^\\w{6,}$", message="Username can only consist of numbers, letters and the underscore character.")
private String username;
#NotBlank(message="Password cannot be blank.")
#Pattern(regexp="^\\S+$", message="Password cannot contain spaces.")
#Size(min=6, message="Username must be longer than 6 characters.")
private String password;
//private String confirmPassword;
private boolean enabled;
private Set<UserRole> userRole = new HashSet<UserRole>(0);
public User() {
}
public User(String username, String password, boolean enabled) {
this.username = username;
this.password = password;
this.enabled = enabled;
}
public User(String username, String password,
boolean enabled, Set<UserRole> userRole) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.userRole = userRole;
}
#Id
#Column(name = "username", unique = true, nullable = false, length = 45)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password", nullable = false, length = 60)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "enabled", nullable = false)
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
public Set<UserRole> getUserRole() {
return userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
/*public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}*/
}
Thanks in advance.
Refert this post, and i dont see the itemlabel and itemid attribute, which maps to userrole object.
also refer post
Found solution using Properties Editor. Here and here
I tried to implement the annotated form input validation in Spring 4.
The following tutorials just don't work.
http://www.javacodegeeks.com/2013/04/spring-mvc-form-validation-with-annotations-2.html
http://codetutr.com/2013/05/28/spring-mvc-form-validation/
The symptoms are the same: the errors.hasErrors() always return false.
And some reader of the above tutorial 2 reported the identical issue, too.
This is the model object Spitter :
public class Spitter {
private Long id;
#NotNull
#Size(min = 5, max = 16)
private String username="default name";
#NotNull
#Size(min = 5, max = 25)
private String password;
#NotNull
#Size(min = 2, max = 30)
private String firstName;
#NotNull
#Size(min = 2, max = 30)
private String lastName;
#NotNull
#Email
private String email;
public Spitter() {
}
public Spitter(String username, String password, String firstName,
String lastName, String email) {
this(null, username, password, firstName, lastName, email);
}
public Spitter(Long id, String username, String password, String firstName,
String lastName, String email) {
this.id = id;
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(#Size(min = 5, max = 16) String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
}
#Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that, "firstName",
"lastName", "username", "password", "email");
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, "firstName",
"lastName", "username", "password", "email");
}
}
This the form JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="f" %>
<%# page session="false" %>
<html>
<head>
<title>Spitter</title>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>Register</h1>
<f:form method="POST" commandName="spitter" modelattribute="spitter">
f-First Name: <f:input path="firstName" /><br/>
f-Last Name: <f:input path="lastName" /><br/>
f-Email: <f:input path="email" /><br/>
f-User Name: <f:input path="username" /><br/>
f-Password: <f:input path="password" /><br/>
<input type="submit" value="Register" />
</f:form>
</body>
</html>
I am using:
validation-api-1.1.0.Final.jar
hibernate-validator-5.0.1.Final.jar
This question is solved at here!
How to turn on annotation driven validation in Spring 4?
You also need to tell Spring to enable JSR-303 validation. If you are using an xml way, try registering
<mvc:annotation-driven/> in your context xml
or if you are using java style:
#EnableWebMvc atop your context loading class
Hope this solves