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?
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";
}
}
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>
I'm not sure what's going wrong here. I've written similar projects that worked just fine but for whatever reason, the data is not being written to the database.
The functionality I'm trying to achieve at the moment is to grab the information from the sign up form and store it in my phpmyadmin db.
This code is identical (word for word) to another person doing this project and theirs is working fine. Leads me to believe the issue is with the JDBC driver or the the database in some way.
Here is the form page code
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Phone Auction Site</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Login</h1>
<form action="login.jsp">
Username:<br>
<input type="text" name="username"><br>
Password:<br>
<input type="password" name="password"><br>
<input type="submit" value="Log In">
</form>
<h1>Sign Up</h1>
<form action="signup.jsp">
Username:<br>
<input type="text" name="username"><br>
Password:<br>
<input type="password" name="password"><br>
First Name:<br>
<input type="text" name="firstName"><br>
Last Name:<br>
<input type="text" name="lastName"><br>
Address:<br>
<input type="text" name="address"><br>
Phone Number:<br>
<input type="text" name="phoneNum"><br>
Email:<br>
<input type="text" name="email"><br>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
Here is the signup.jsp page that gets the attributes, creates the instance and calls the saveToDatabase method
<%#page import="phoneauctionronan.Customer"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sign Up</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String address = request.getParameter("address");
String phoneNum = request.getParameter("phoneNum");
String email = request.getParameter("email");
Customer c = new Customer(username, password, firstName, lastName, address, phoneNum, email);
c.saveToDatabase();
%>
</body>
</html>
Here is the Customer class
package phoneauctionronan;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Customer
{
private int id;
private String username;
private String password;
private String firstName;
private String lastName;
private String address;
private String phoneNum;
private String email;
public Customer()
{
}
public Customer(String username, String password, String firstName, String lastName, String address, String phoneNum, String email)
{
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNum = phoneNum;
this.email = email;
}
public boolean saveToDatabase()
{
boolean saved = false;
Connection c = DBHelperClass.getConnection();
if (c != null)
{
try
{
Statement s = c.createStatement();
String template = "INSERT INTO customer (username, password, firstName, lastName, address, phoneNumber, emailAddress) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement inserter = c.prepareStatement(template);
inserter.setString(1, this.username);
inserter.setString(2, this.password);
inserter.setString(3, this.firstName);
inserter.setString(4, this.lastName);
inserter.setString(5, this.address);
inserter.setString(6, this.phoneNum);
inserter.setString(7, this.email);
inserter.executeUpdate();
saved = true;
}
catch (SQLException ex)
{
Logger.getLogger(Customer.class.getName()).log(Level.SEVERE, null, ex);
}
}
return saved;
}
public Customer validateCustomer(String username, String password)
{
boolean found = false;
Connection c = DBHelperClass.getConnection();
if(c!=null)
{
try
{
Statement s = c.createStatement();
String template = "SELECT * from customers where username = ? and password = ?";
PreparedStatement inserter = c.prepareStatement(template);
inserter.setString(1, username);
inserter.setString(2, password);
ResultSet resultSet = inserter.executeQuery();
while(resultSet.next())
{
this.id = resultSet.getInt("userID");
this.username = resultSet.getString("userName");
this.password = resultSet.getString("password");
this.firstName = resultSet.getString("firstName");
this.lastName = resultSet.getString("lastName");
this.address = resultSet.getString("address");
this.phoneNum = resultSet.getString("phoneNum");
this.email = resultSet.getString("email");
found = true;
}
}
catch (SQLException ex)
{
Logger.getLogger(Customer.class.getName()).log(Level.SEVERE, null, ex);
}
}
return this;
}
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 getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getPhoneNum()
{
return phoneNum;
}
public void setPhoneNum(String phoneNum)
{
this.phoneNum = phoneNum;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
}
Finally here is the DBConnection class
package phoneauctionronan;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DBHelperClass
{
public static Connection getConnection()
{
String host = "localhost";
String dbName = "phones";
int port = 3306;
String mySqlUrl = "jdbc:mysql://" + host + ":" + port
+ "/" + dbName;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println("ClassNotFound !!!!" + e);
}
Properties userInfo = new Properties();
userInfo.put("user", "root");
userInfo.put("password", "password");
try
{
Connection connection = DriverManager.getConnection(mySqlUrl, userInfo);
return connection;
}
catch (SQLException ex)
{
Logger.getLogger(DBHelperClass.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
Here is a pic of my customer table structure
Here a pic of the name of the db and table just in case
Completely lost as to what might be causing this!
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
In my application I am trying to register a user by adding his details to the database and after success fully insert these values. I need to display form input page but on result page I am not getting any output.
My ACTION CLASS IS
package action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import dao.Empdao;
import model.Empmodel;
public class Empaction extends ActionSupport implements ModelDriven<Object>{
private static final long serialVersionUID = 1L;
Empmodel modelobj;
public Empmodel getModelobj() {
return modelobj;
}
public void setModelobj(Empmodel modelobj) {
this.modelobj = modelobj;
}
public String execute() throws Exception{
Empdao empdao = new Empdao();
int queryResult = empdao.registration(modelobj);
if (queryResult==0)
{
addActionError("it is a dublicate entry please enter anothe id");
return ERROR;
}
else{
return SUCCESS;
}
}
#Override
public Object getModel() {
modelobj = new Empmodel();
return null;
}
}
Success.jsp is
<body>
first name : <s:property value="modelobj.firstname"/> <br>
last name :<s:property value="modelobj.lastname" />
<s:property value="modelobj.id" />
<s:property value="modelobj.gender" />
<s:property value="modelobj.dob" />
<s:property value="modelobj.maritalstatus" />
<s:property value="modelobj.email" />
<s:property value="modelobj.joiningdate" />
<s:property value="modelobj.designation" />
<s:property value="modelobj.country" />
<s:property value="modelobj.state" />
<s:property value="modelobj.city" />
<s:property value="modelobj.pincode" />
<s:property value="modelobj.mobileno" />
<s:property value="modelobj.groups" />
</body>
</html>
Empmodel CLASS IS
package model;
public class Empmodel {
private String firstname;
private String lastname;
private String id;
private String gender;
private String dob;
private String maritalstatus;
private String email;
private String joiningdate;
private String designation;
private String address;
private String country;
private String state;
private String city;
private int pincode;
private long mobileno;
private String groups;
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 getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getMaritalstatus() {
return maritalstatus;
}
public void setMaritalstatus(String maritalstatus) {
this.maritalstatus = maritalstatus;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getJoiningdate() {
return joiningdate;
}
public void setJoiningdate(String joiningdate) {
this.joiningdate = joiningdate;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getMobileno() {
return mobileno;
}
public void setMobileno(long mobileno) {
this.mobileno = mobileno;
}
public String getGroups() {
return groups;
}
public void setGroups(String groups) {
this.groups = groups;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
<constant name="struts.devmode" value="true"/>
<package name="loginmodel" extends ="struts-default">
<action name ="emplogin" class ="action.Empaction">
<result name= "wait">/Registration/wait.jsp</result>
<result name = "input">/Registration/empregistration.jsp</result>
<result name ="success" type="redirect" >/Registration/success.jsp</result>
<result name="error">/Registration/empregistration.jsp</result>
</action>
</package>
empregistration.jsp
<%# page language ="java" contentType ="text/html; charset=ISO-8859-1" pageEncoding ="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<%# taglib uri="/struts-dojo-tags" prefix="sx" %>
<html>
<head>
<sx:head/>
<script type="text/javascript" src ="script.js"></script>
</head>
<body>
<div align="center"> <h1 style="color: red"> ENPLOYEE REGISTRATION FORM</h1>
<s:form action="emplogin" method="post">
<s:textfield name="modelobj.firstname" label="Employee Firstname"/>
<s:textfield name ="modelobj.lastname" label ="Last name"/>
<s:textfield name ="modelobj.id" label="Id"/>
<s:radio name ="modelobj.gender" list="{'male', 'female'}" label = "Gender"/>
<sx:datetimepicker name="dob" displayFormat="dd-MMM-yyyy" label="DOB"></sx:datetimepicker>
<s:radio name ="modelobj.maritalstatus" list="{'singale','married'}" label="Marital Status" />
<s:textfield name ="modelobj.email" label ="Email"/>
<sx:datetimepicker name ="modelobj.joiningdate" displayFormat="dd-MMM-yyyy" label="Joining Date"></sx:datetimepicker>
<s:textfield name= "modelobj.designation" label = "Designation"/>
<s:textarea name ="modelobj.address" label ="Address" />
<s:textfield name = "modelobj.country" label ="Country" />
<s:textfield name ="modelobj.state" label = "State" />
<s:textfield name ="modelobj.city" label ="City"/>
<s:textfield name ="modelobj.pincode" label ="Pincode"/>
<s:textfield name ="modelobj.mobileno" label="Mobile No"/>
<s:select name ="modelobj.groups" list="{'group 1', 'group 2', 'group 3'}" label ="Group" cssStyle="{width:184px"/>
<tr><td> </td></tr>
<tr>
<td> </td>
<s:submit align="center"></s:submit>
</s:form>
</div>
</body>
</html>
You are redirecting the page on success that is wrong because you loose values needed to display results. Use
<result name ="success">/Registration/success.jsp</result>
or simply
<result>/Registration/success.jsp</result>
BTW, you only have getters & setters for firstname and lastname, so the only these properties will display. If you want to display other properties then you should add correcponding methods to fields.
You may read the servlet API javadoc to make clue what may cause result type="redirect".
For further compare the difference between forward and redirect results consider this thread.
If type=redirectAction then you have to mention the Action name without any extensions
if its only redirect then you have to mention including the action name and extension, For your Question it was because of redirect the problem happened.
Even after redirecting to some page and when you come back to the result page , and if you want to retain data then its better you better put in session .
Do not redirect you page remove it and use
<result name ="success">/Registration/success.jsp</result> in you struts.xml file