Spring MVC form error - java

I am trying to run a project in Spring MVC. Here is the code
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" 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=UTF-8">
<title>Welcome to Spring Web MVC project</title>
</head>
<body>
<h1>Spring 3 Register!</h1>
click
<form:form action="${pageContext.request.contextPath}/register" method="POST" modelAttribute="userForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Registration</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>BirthDate (mm/dd/yyyy)</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession</td>
<td><form:select path="profession" items="${professionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</body>
</html>
RegistrationController.java
/*
* 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.
*/
package RegisterInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* #author Harshit Shrivastava
*/
import RegisterInfo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
#Controller
#RequestMapping(value = "/register")
public class RegistrationController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Model model)
{
User userForm = new User();
model.addAttribute("userForm", new User());
/*List<String> professionList = new ArrayList();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.put("professionList", professionList);*/
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("userForm") User user, Map<String, Object> model)
{
System.out.println("Username : " + user.getUserName());
model.put("userForm", new User());
return "index";
}
}
User.java
/*
* 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.
*/
package RegisterInfo.model;
/**
*
* #author Harshit Shrivastava
*/
import java.util.Date;
public class User {
private String username;
private String password;
private String email;
private Date birthDate;
private String profession;
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 getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public Date getBirthDate()
{
return birthDate;
}
public void setBirthDate(Date birthDate)
{
this.birthDate = birthDate;
}
public String getProfession()
{
return profession;
}
public void setProfession(String profession)
{
this.profession = profession;
}
}
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd ">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:component-scan base-package="SpringRegister" />
<mvc:annotation-driven />
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
In the above program, Whenever I go to http://localhost:8080/SpringRegister/index.htm, I always gets this error
Error:
neither bindingresult nor plain target object for bean 'userForm' available as request attribute
What is wrong with the code?

When you hit the http://localhost:8080/SpringRegister/index.htm from browser, Your request is handled by ParameterizableViewController which does not set the model attribute (userForm) and forwards to index.jsp, the index.jsp's form tag expects the model attribute userForm <form:form action="${pageContext.request.contextPath}/register" method="POST" modelAttribute="userForm"> , which is not available. that why the error. To resolve this you can create your own conrtoller which handles your http://localhost:8080/SpringRegister/index.htm URL,
ModelAndView modelAndView = new ModelAndView("your view name");
model.addAttribute("userForm", new User());
configure that controller instead of class="org.springframework.web.servlet.mvc.ParameterizableViewController" in your servlet xml. Hope this helps.

You need to Change in Controller To bind userForm with Bean ----
Jsp Form --
<form:form action="userAction" modelAttribute="userForm " class="form-search" role="form">
Controller --
#RequestMapping (value = "/userAction")
public ModelAndView checkFeasibility(#ModelAttribute("userForm ")User userForm)
{
// Any Action
model.addObject("userForm",userForm);
return model;
}
In order to Bind userForm modelAttribute of form with User Bean.

Related

The requested resource is not available in spring mvc

After click on AddEmployee link next page is open given below
when i click on submit the then next page opening like that
addEmployee.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Spring MVC Form Handling</title>
</head>
<body>
<h2>Add Employee Data</h2>
<form:form method="POST" action="/save.html">
<table>
<tr>
<td><form:label path="id">Employee ID:</form:label></td>
<td><form:input path="id" value="${employee.id}" readonly="true"/></td>
</tr>
<tr>
<td><form:label path="name">Employee Name:</form:label></td>
<td><form:input path="name" value="${employee.name}"/></td>
</tr>
<tr>
<td><form:label path="age">Employee Age:</form:label></td>
<td><form:input path="age" value="${employee.age}"/></td>
</tr>
<tr>
<td><form:label path="salary">Employee Salary:</form:label></td>
<td><form:input path="salary" value="${employee.salary}"/></td>
</tr>
<tr>
<td><form:label path="address">Employee Address:</form:label></td>
<td><form:input path="address" value="${employee.address}"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
<c:if test="${!empty employees}">
<h2>List Employees</h2>
<table align="left" border="1">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Employee Address</th>
<th>Actions on Row</th>
</tr>
<c:forEach items="${employees}" var="employee">
<tr>
<td><c:out value="${employee.id}"/></td>
<td><c:out value="${employee.name}"/></td>
<td><c:out value="${employee.age}"/></td>
<td><c:out value="${employee.salary}"/></td>
<td><c:out value="${employee.address}"/></td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
employeeList.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>All Employees</title>
</head>
<body>
<h1>List Employees</h1>
<h3>Add More Employee</h3>
<c:if test="${!empty employees}">
<table align="left" border="1">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Employee Address</th>
</tr>
<c:forEach items="${employees}" var="employee">
<tr>
<td><c:out value="${employee.id}"/></td>
<td><c:out value="${employee.name}"/></td>
<td><c:out value="${employee.age}"/></td>
<td><c:out value="${employee.salary}"/></td>
<td><c:out value="${employee.address}"/></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
index.jsp
<%# 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>Spring3MVC with Hibernate3 CRUD Example using Annotations</title>
</head>
<body>
<h2>Spring3MVC with Hibernate3 CRUD Example using Annotations</h2>
<h2>1. List of Employees</h2>
<h2>2. Add Employee</h2>
</body>
</html>
web.xml file
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
spring-servlet.xml file
<beans xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="com"></context:component-scan>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"></tx:annotation-driven>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="jdbc:postgresql://localhost:5433/databaseDb"></property>
<property name="username" value="postgres"></property>
<property name="password" value="postgres"></property>
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.model.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="hibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
EmployeeController class
package com.controller;
import com.bean.EmployeeBean;
import com.model.Employee;
import com.service.EmployeeService;
import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.util.*;
/**
* Created by khan on 28/11/16.
*/
#Controller
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Employee employee = prepareModel(employeeBean);
employeeService.addEmployee(employee);
return new ModelAndView("redirect:/add.html");
}
#RequestMapping(value = "/employees", method = RequestMethod.GET)
public ModelAndView listEmployee() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("employeesList", map);
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("index");
}
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView editEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employee", null);
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public ModelAndView deleteEmployee(#ModelAttribute("command") EmployeeBean employeeBean, BindingResult result) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("employee", prepareEmployeebean(employeeService.getEmployee(employeeBean.getId())));
map.put("employees", prepareListofBean(employeeService.listEmployees()));
return new ModelAndView("addEmployee", map);
}
private EmployeeBean prepareEmployeebean(Employee employee) {
EmployeeBean employeeBean = new EmployeeBean();
employeeBean.setAddress(employee.getEmpAddress());
employeeBean.setAge(employee.getEmpAge());
employeeBean.setSalary(employee.getEmpSalary());
employeeBean.setName(employee.getEmpName());
employeeBean.setId(employee.getEmpId());
return employeeBean;
}
private Employee prepareModel(EmployeeBean employeeBean) {
Employee employee = new Employee();
employee.setEmpAddress(employeeBean.getAddress());
employee.setEmpAge(employeeBean.getAge());
employee.setEmpName(employeeBean.getName());
employee.setEmpSalary(employeeBean.getSalary());
employee.setEmpId(null);
return employee;
}
private List<EmployeeBean> prepareListofBean(List<Employee> employees) {
List<EmployeeBean> employeeBeen = null;
if (employees != null && !employees.isEmpty()) {
employeeBeen = new ArrayList<EmployeeBean>();
EmployeeBean bean = null;
for (Employee employee : employees) {
bean = new EmployeeBean();
bean.setName(employee.getEmpName());
bean.setAge(employee.getEmpAge());
bean.setSalary(employee.getEmpSalary());
bean.setAddress(employee.getEmpAddress());
bean.setId(employee.getEmpId());
employeeBeen.add(bean);
}
}
return employeeBeen;
}
}
EmployeeService interface
package com.service;
import com.dao.EmployeeDao;
import com.model.Employee;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
public interface EmployeeService {
public void addEmployee(Employee employee);
public List<Employee> listEmployees();
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
EmployeeServiceImpl class
package com.serviceImpl;
import com.dao.EmployeeDao;
import com.model.Employee;
import com.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
#Service("EmployeeService")
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addEmployee(Employee employee) {
employeeDao.addEmployee(employee);
}
public List<Employee> listEmployees() {
return (List<Employee>) employeeDao.listEmployees();
}
public Employee getEmployee(int empid) {
return employeeDao.getEmployee(empid);
}
public void deleteEmployee(Employee employee) {
employeeDao.deleteEmployee(employee);
}
}
EmployeeDao interface
package com.dao;
import com.model.Employee;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
public interface EmployeeDao {
public List<Employee> listEmployees();
public void addEmployee(Employee employee);
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
EmployeDaoImpl class
package com.daoImpl;
import com.bean.EmployeeBean;
import com.dao.EmployeeDao;
import com.model.Employee;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by khan on 28/11/16.
*/
#Repository
public class EmployeeDaoImpl implements EmployeeDao {
#Autowired
private SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
public List<Employee> listEmployees() {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Employee.class);
List<Employee> list = (List<Employee>) criteria.list();
transaction.commit();
return list;
}
public void addEmployee(Employee employee) {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().saveOrUpdate(employee);
transaction.commit();
}
public Employee getEmployee(int empid) {
return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);
}
public void deleteEmployee(Employee employee) {
Transaction transaction = sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession()
.createQuery("Delete from Employee where id=" + employee.getEmpId()).executeUpdate();
transaction.commit();
}
}
Employee class
package com.model;
import javax.persistence.*;
/**
* Created by khan on 28/11/16.
*/
#Entity
#Table(name = "Employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "empid")
private Integer empId;
#Column(name = "empage")
private Integer empAge;
#Column(name = "empname")
private String empName;
#Column(name = "empaddress")
private String empAddress;
#Column(name = "empsalary")
private Long empSalary;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public Integer getEmpAge() {
return empAge;
}
public void setEmpAge(Integer empAge) {
this.empAge = empAge;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpAddress() {
return empAddress;
}
public void setEmpAddress(String empAddress) {
this.empAddress = empAddress;
}
public Long getEmpSalary() {
return empSalary;
}
public void setEmpSalary(Long empSalary) {
this.empSalary = empSalary;
}
}
EmployeeBean class
package com.bean;
import org.omg.CORBA.INTERNAL;
/**
* Created by khan on 28/11/16.
*/
public class EmployeeBean {
private Integer id;
private Integer age;
private String name;
private Long salary;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getSalary() {
return salary;
}
public void setSalary(Long salary) {
this.salary = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Please Help me i try but not getting how to solve this.
Thanks every buddy in advance
change your form action to
<form:form action="${pageContext.request.contextPath}/save.html" method="POST">
..
</form:form>

Hibernate validator doesn't work

I'm using Hibernate validator with Hibernate and Spring, but it seems that validations don't work. When I don't enter a String or enter a String of 1 character (which is not between min=4 and max=20) is not showing any error and therefore saves in the table. What am I missing?
package dao;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name="etudiant")
public class Etudiant {
#Id
#Column(name="ID_ETUDIANT")
#GeneratedValue
private Long idEtudiant;
#Column(name="NOM")
#Size (min=4, max=20)
private String nom;
#Size(min=4, max=20, message="nom doit etre entre 4 et 20 svp..")
#Column(name="PRENOM")
private String prenom;
#Column(name="DATE_NAISSANCE")
#Temporal(TemporalType.DATE)
private Date dateNaissance;
#NotNull
#Column(name="EMAIL")
private String email;
public Etudiant() {
super();
}
public Long getIdEtudiant() {
return idEtudiant;
}
public void setIdEtudiant(Long idEtudiant) {
this.idEtudiant = idEtudiant;
}
public Etudiant(String nom, String prenom, Date dateNaissance, String email) {
super();
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
this.email = email;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDateNaissance() {
return dateNaissance;
}
public void setDateNaissance(Date dateNaissance) {
this.dateNaissance = dateNaissance;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Controller:
#RequestMapping(value="save",method=RequestMethod.POST)
public String saveetudient(Model md,
#Valid #ModelAttribute("etudiant") Etudiant et,
BindingResult res) {
if (res.hasErrors()) {
List <Etudiant> ets=service.listeEtudiants();
md.addAttribute("etudiants",ets);
return "etudiant1";
}
else {
service.addEtudiant(et);
List <Etudiant> ets=service.listeEtudiants();
md.addAttribute("etudiants",ets);
return "etudiant1";
}
}
In JSP I put this line to show errors:
<form action="save" method="post">
<table border="1" width="500" bgcolor="grey">
<tr>
<th>Nom </th>
<th>Prenom </th>
<th> Date de naissance</th>
<th>Email </th>
</tr>
<tr>
<td> <input type="text" name="nom" > </td>
<td> <input type="text" name="prenom" > </td>
<td> <input type="text" name="dateNaissance" > </td>
<td> <input type="text" name="email" > </td>
</tr>
</table> <br>
<input type="submit" value="ajouter">
<sform:errors path="etudiant.*"/>
<sform:errors path="prenom"/>
</form>
XML file configuration :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<context:component-scan base-package="controller"/>
<mvc:annotation-driven/>
<bean class="dao.DaoEtudiantImpl" name="daoetud"></bean>
<bean class="service.EtudiantMetierImpl" name="servetud">
<property name="dao" ref="daoetud"></property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
Finally I found the error ,
the problem was that I didin't add hibernate-validator jar I only added files in the dist/lib/required :
classmate-1.3.1
javax.el-2.2.4
-javax.el-api-2.2.2
jboss-logging-3.3.0.Final
validation-api-1.1.0
So if that happens to someone just add : hibernate-validator-5.3.2.Final.
After spent one hour to study two validation tutorials:
Hibernate Validator Annotations Example
Spring MVC Form Validation Annotation Example
I suggest you some solutions.
1) Verify hibernate validation annotation working or not
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Etudiant>> constraintViolations = validator.validate(etudiant);
2) You can create custom validator, for example EtudiantValidator, then validate manually like below:
#RequestMapping(value="save",method=RequestMethod.POST)
public String saveetudient(Model md,#ModelAttribute("etudiant") Etudiant etudiant, BindingResult res){
new EtudiantValidator().validate(etudiant, result);
...
}
However I deep into your code,I see that you have a mistake on this method:
#RequestMapping(value="save",method=RequestMethod.POST)
public String saveetudient(Model md,
#Valid #ModelAttribute("etudiant") Etudiant et,
BindingResult res)
Should change it to like below
#RequestMapping(value="save",method=RequestMethod.POST)
public String saveetudient(Model md,
#Valid #ModelAttribute("etudiant") Etudiant etudiant,
BindingResult res)
Hope this help!

javax.servlet.ServletException: Could not resolve view with name

I am following this example:
User controller:
#Controller
public class UserController {
/**
* Static list of users to simulate Database
*/
private static List<User> userList = new ArrayList<User>();
/**
* Saves the static list of users in model and renders it
* via freemarker template.
*
* #param model
* #return The index view (FTL)
*/
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(#ModelAttribute("model") ModelMap model) {
userList.add(new User("Bill", "Gates"));
userList.add(new User("Steve", "Jobs"));
userList.add(new User("Larry", "Page"));
userList.add(new User("Sergey", "Brin"));
userList.add(new User("Larry", "Ellison"));
model.addAttribute("userList", userList);
return "index";
}
/**
* Add a new user into static user lists and display the
* same into FTL via redirect
*
* #param user
* #return Redirect to /index page to display user list
*/
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(#ModelAttribute("user") User user) {
if (null != user && null != user.getFirstname()
&& null != user.getLastname() && !user.getFirstname().isEmpty()
&& !user.getLastname().isEmpty()) {
synchronized (userList) {
userList.add(user);
}
}
return "redirect:index.html";
}
class User {
private String firstname;
private String lastname;
public User() {
}
public User(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
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;
}
}
}
*-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="ua.epam.spring.hometask" />
<context:annotation-config/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value="/WEB-INF/ftl"/>
<property name="suffix" value=".ftl"/>
</bean>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl/"/>
</bean>
</beans>
WEB-INF/ftl/intex.ftl:
<html>
<head><title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
<body>
<div id="header">
<H2>
<img height="37" width="236" border="0px" src="http://viralpatel.net/blogs/wp-content/themes/vp/images/logo.png" align="left"/>
FreeMarker Spring MVC Hello World
</H2>
</div>
<div id="content">
<fieldset>
<legend>Add User</legend>
<form name="user" action="add.html" method="post">
Firstname: <input type="text" name="firstname" /> <br/>
Lastname: <input type="text" name="lastname" /> <br/>
<input type="submit" value=" Save " />
</form>
</fieldset>
<br/>
<table class="datatable">
<tr>
<th>Firstname</th> <th>Lastname</th>
</tr>
<#list model["userList"] as user>
<tr>
<td>${user.firstname}</td> <td>${user.lastname}</td>
</tr>
</#list>
</table>
</div>
</body>
</html>
and got this exception:
javax.servlet.ServletException: Could not resolve view with name 'index' in servlet with name 'index'
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1237)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:980)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Question: what can be a reson of this exception? How to fix it?
In controller redirection use only index instead of index.html. it will redirect to index method of controller.And you can view the output on index page itself after clicking on button.
As shown below:
#RequestMapping(value = "/Add", method = RequestMethod.POST)
public String add(#ModelAttribute ("usr") User user){
if (null != user && null != user.getFirstname()
&& null != user.getLastname() && !user.getFirstname().isEmpty()
&& !user.getLastname().isEmpty()) {
synchronized (userList) {
userList.add(user);
}
}
return "redirect:index";

Spring MVC Errors are not shown to user

I am trying to learn spring MVC. I have a User Registration form which has some validations to be applied. I have written a controller for it and used javax validation annotations on the model class i.e. UserBo.
I have used Spring MVC tag to show any errors found by #Valid annotation. However, the errors are not visible on screen.
Following are the files in my setup.
The Model: UserBO
package com.shailesh.beans;
import javax.validation.constraints.NotNull;
public class UserBO {
public enum MaritalStatus {
SINGLE, MARRIED
}
#Override
public String toString() {
return "UserBO [firstName=" + firstName + ", lastName=" + lastName
+ ", id=" + id + ", phone=" + phone + ", maritalStatus="
+ maritalStatus + "]";
}
#NotNull(message="First Name can not be null")
private String firstName;
#NotNull
private String lastName;
#NotNull
private Long id;
#NotNull
private String phone;
#NotNull
private MaritalStatus maritalStatus;
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 Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public MaritalStatus getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(MaritalStatus maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
The Controller : AllPathController
package com.shailesh.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.shailesh.beans.UserBO;
#Controller
public class AllPathController {
#RequestMapping(value="/register", method=RequestMethod.GET)
public String register(Model model) {
model.addAttribute("userBo", new UserBO());
return "registerform";
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public String register(#Valid #ModelAttribute("userBo") UserBO userBo, BindingResult result, Model model) {
if(result.hasErrors()) {
System.out.println("Input has some errors :"+result.toString());
//model.addAttribute("userBo", userBo);
return "registerform";
}
System.out.println("Input user details :" +userBo);
return "helloboss";
}
#RequestMapping(value="/homepage", method=RequestMethod.GET)
public String show() {
return "homepage";
}
#RequestMapping(value="/helloboss.do", method=RequestMethod.GET)
public String show2() {
System.out.println("get");
return "helloboss";
}
#RequestMapping(value="/helloboss.do", method=RequestMethod.POST)
public String show3() {
System.out.println("post");
return "hellobosspost";
}
}
The Spring context.xml file :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">
<mvc:annotation-driven />
<!-- <context:component-scan base-package="com.shailesh.controller.*" /> -->
<bean id="allPathController" class="com.shailesh.controller.AllPathController" />
<bean id="resolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
</bean>
</beans>
And the very own registerform.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.error {
color: red;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Registration Form</h2>
<sf:form method="POST" commandName="userBo">
First Name : <sf:input path="firstName" />
<br />
<sf:errors path="firstName" element="div"/>
Last Name : <sf:input path="lastName" />
<br />
<sf:errors path="lastName" />
Phone : <sf:input path="phone" />
<br />
<sf:errors path="phone" />
Marital Status :
<sf:select path="maritalStatus">
<sf:options path="maritalStatus" />
</sf:select>
<sf:errors path="maritalStatus" />
<input type="submit" value="Register" />
</sf:form>
</body>
</html>
My observation is, when i give path value for as "*", it works. However, when i use some specific value ex. firstName , it doesn't show any errors. I tried debugging in this case. I can see the errors being populated inside BindingResult but not shown on UI.
Any help is appeciated. Thanks.

Spring MVC 3 Validator not displaying Error Message

I have problem with displaying error message in spring Application.i am using Spring MVC 3 and Apache Tiles. when i am having error in form than it will not displays error message.
please help me hear is the piece of code.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/dispatcher-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-Servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.examples.spring" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
</beans>
tiles.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="create_account_success" template="/WEB-INF/jsp/account/SuccessJSP.jsp">
</definition>
<definition name="account_create" template="/WEB-INF/jsp/account/testForm.jsp">
</definition>
</tiles-definitions>
testForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="form" 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">
<title>Insert title here</title>
</head>
<body>
<form:form id="form" modelAttribute="formCreate" method="post">
<table>
<tr>
<td>Name :</td>
<td><form:input path="name"/>
<form:errors path="name"/>
</td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password"/>
<form:errors path="password"/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
AccountRegistrationController.java
package com.examples.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.examples.spring.dto.AccountDTO;
import com.examples.spring.validator.AccountValidator;
#Controller
public class AccountRegistrationController {
public static final String BASE_URL = "/account";
#RequestMapping(value = BASE_URL + "/create" ,method = RequestMethod.GET)
public ModelAndView accountCreate(){
ModelAndView view = new ModelAndView();
view.addObject("formCreate", new AccountDTO());
view.setViewName("account_create");
return view;
}
#RequestMapping(value = BASE_URL + "/create" ,method = RequestMethod.POST)
public ModelAndView accountRegistration(#ModelAttribute AccountDTO accountDTO,BindingResult result ){
ModelAndView view = new ModelAndView();
AccountValidator validator = new AccountValidator();
validator.validate(accountDTO, result);
if (result.hasErrors()) {
view.setViewName("account_create");
view.addObject("formCreate", accountDTO);
return view;
}
view.setViewName("create_account_success");
return view;
}
#RequestMapping(value = BASE_URL + "/login" ,method = RequestMethod.GET)
public ModelAndView accountLogin(){
ModelAndView view = new ModelAndView();
view.setViewName("account_login");
return view;
}
}
AccountValidator.java
package com.examples.spring.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.examples.spring.dto.AccountDTO;
public class AccountValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return AccountDTO.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object result, Errors error) {
AccountDTO accountDTO = (AccountDTO) result;
ValidationUtils.rejectIfEmpty(error, "name", "require.name", "Name Requires.");
ValidationUtils.rejectIfEmpty(error, "password", "require.password", "Password Requires.");
}
}
AccountDTO.java
package com.examples.spring.dto;
public class AccountDTO {
private String name;
private String password;
public AccountDTO() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My Code is working well but it does not displays error messages in <form:errors />.
please help me.
The third parameter to ValidationUtils.rejectIfEmpty is an error code. It should be a key to the actual message in your resource bundle. I don't know how it behaves if it can't find a value. You should change it to use a key, and optionally set a default message. See the api.
You need to register your validator with the controller in which you want to use it. See: http://static.springsource.org/spring/docs/3.0.0.RC3/reference/html/ch05s07.html#validation.mvc

Categories