I am here again with a new concern. I'm getting the Etat HTTP 400 error page when I am trying to create a new Utilisateur in mysql database. But no error is displayed in the console.
My code:
Utilisateur.java
package com.model;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="utilisateur")
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="idutilisateur")
private int idUtilisateur;
#Column(name="emailutilisateur")
private String emailUtilisateur;
#Column(name="motpasseutilisateur")
private String motPasseUtilisateur;
#Column(name="nomutilisateur")private String nomUtilisateur;
#Column(name="dateinscriptionutilisateur")
private Timestamp dateInscriptionUtilisateur;
public int getIdUtilisateur() {
return idUtilisateur;
}
public void setIdUtilisateur(int idUtilisateur) {
this.idUtilisateur = idUtilisateur;
}
public String getEmailUtilisateur() {
return emailUtilisateur;
}
public void setEmailUtilisateur(String emailUtilisateur) {
this.emailUtilisateur = emailUtilisateur;
}
public String getMotPasseUtilisateur() {
return motPasseUtilisateur;
}
public void setMotPasseUtilisateur(String motPasseUtilisateur) {
this.motPasseUtilisateur = motPasseUtilisateur;
}
public String getNomUtilisateur() {
return nomUtilisateur;
}
public void setNomUtilisateur(String nomUtilisateur) {
this.nomUtilisateur = nomUtilisateur;
}
public Timestamp getDateInscriptionUtilisateur() {
return dateInscriptionUtilisateur;
}
public void setDateInscriptionUtilisateur(Timestamp dateInscriptionUtilisateur) {
this.dateInscriptionUtilisateur = dateInscriptionUtilisateur;
}
#Override
public String toString() {
return "Utilisateur [idUtilisateur=" + idUtilisateur + ", emailUtilisateur=" + emailUtilisateur
+ ", motPasseUtilisateur=" + motPasseUtilisateur + ", nomUtilisateur=" + nomUtilisateur
+ ", dateInscriptionUtilisateur=" + dateInscriptionUtilisateur + "]";
}
}
UtilisateurDaoImpl.java
package com.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.model.Utilisateur;
#Repository
public class UtilisateurDaoImpl implements UtilisateurDao {
#Autowired
private SessionFactory sessionFactory;
public void addUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().saveOrUpdate(utilisateur);
}
#SuppressWarnings("unchecked")
public List<Utilisateur> getAllUtilisateur() {
List<Utilisateur> listeUtilisateur = sessionFactory.getCurrentSession().createQuery("from Utilisateur").list();
return listeUtilisateur;
}
public Utilisateur getUtilisateurById(int idUtilisateur) {
return (Utilisateur)sessionFactory.getCurrentSession().get(Utilisateur.class, idUtilisateur);
}
public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
sessionFactory.getCurrentSession().update(utilisateur);
return utilisateur;
}
public void deleteUtilisateur(int idUtilisateur) {
Utilisateur utilisateur = (Utilisateur)sessionFactory.getCurrentSession().load(Utilisateur.class, idUtilisateur);
if(utilisateur != null){
this.sessionFactory.getCurrentSession().delete(utilisateur);
}
}
}
UtilisateurServiceImpl.java
package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.UtilisateurDao;
import com.model.Utilisateur;
#Service
#Transactional
public class UtilisateurServiceImpl implements UtilisateurService {
#Autowired
private UtilisateurDao utilisateurDao;
public void setUtilisateurDao(UtilisateurDao utilisateurDao) {
this.utilisateurDao = utilisateurDao;
}
#Transactional
public void addUtilisateur(Utilisateur utilisateur) {
utilisateurDao.addUtilisateur(utilisateur);
}
#Transactional
public List<Utilisateur> getAllUtilisateur() {
return utilisateurDao.getAllUtilisateur();
}
#Transactional
public Utilisateur getUtilisateurById(int idUtilisateur) {
return utilisateurDao.getUtilisateurById(idUtilisateur);
}
#Transactional
public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
return utilisateurDao.updateUtilisateur(utilisateur);
}
#Transactional
public void deleteUtilisateur(int idUtilisateur) {
utilisateurDao.deleteUtilisateur(idUtilisateur);
}
}
UtilisateurController.java
package com.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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.web.servlet.ModelAndView;
import com.model.Utilisateur;
import com.service.UtilisateurService;
#Controller
public class UtilisateurController {
#SuppressWarnings("unused")
private final static Logger logger = Logger.getLogger("UtilisateurController");
public UtilisateurController(){
System.out.println("UtilisateurController()");
}
#Autowired
private UtilisateurService service;
#RequestMapping(value="/newUtilisateur", method=RequestMethod.GET)
public ModelAndView newUtilisateur(ModelAndView model){
Utilisateur utilisateur = new Utilisateur();
model.addObject("utilisateur", utilisateur);
model.setViewName("utilisateurForm");
return model;
}
#RequestMapping(value="/saveUtilisateur", method = RequestMethod.POST)
public ModelAndView saveUtilisateur(#ModelAttribute Utilisateur utilisateur) {
System.out.println(utilisateur.getIdUtilisateur());
if (utilisateur.getIdUtilisateur() == 0) {
service.addUtilisateur(utilisateur);
} else {
service.updateUtilisateur(utilisateur);
}
return new ModelAndView("redirect:/");
}
#RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView listeUtilisateur(ModelAndView model) throws IOException{
List<Utilisateur> listeUtilisateur = service.getAllUtilisateur();
model.addObject("listeUtilisateur", listeUtilisateur);
model.setViewName("listeutilisateur");
return model;
}
#RequestMapping(value = "/editUtilisateur", method = RequestMethod.GET)
public ModelAndView editUtilisateur(HttpServletRequest request) {
int idUtilisateur = Integer.parseInt(request.getParameter("idUtilisateur"));
System.out.println(idUtilisateur);
Utilisateur utilisateur = service.getUtilisateurById(idUtilisateur);
ModelAndView model = new ModelAndView("utilisateurForm");
model.addObject("utilisateur", utilisateur);
return model;
}
#RequestMapping(value="/deleteUtilisateur", method=RequestMethod.GET)
public ModelAndView deleteUtilisateur(HttpServletRequest request){
service.deleteUtilisateur(Integer.parseInt(request.getParameter("idUtilisateur")));
return new ModelAndView("redirect:/");
}
}
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com"/>
<mvc:annotation-driven/>
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
<context:property-placeholder location="classpath:application.properties"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/vues/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.show_format">${hibernate.show_format}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
<property name="packagesToScan" value="com.model"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
utilisateurForm.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit / Save Utilisateur</title>
</head>
<body>
<div align="center">
<h1> Edit / Save Utilisateur</h1>
<form:form action="saveUtilisateur" method="post" modelAttribute="utilisateur">
<table>
<form:hidden path="idUtilisateur"/>
<tr>
<td>Adresse email</td>
<td><form:input path="emailUtilisateur"/></td>
</tr>
<tr>
<td>Mot de passe</td>
<td><form:password path="motPasseUtilisateur"/></td>
</tr>
<tr>
<td>Nom d'utilisateur</td>
<td><form:input path="nomUtilisateur"/></td>
</tr>
<tr>
<td>Date d'inscription</td>
<td><form:input path="dateInscriptionUtilisateur"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
listeutilisateur.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Liste des utilisateurs</title>
<link rel="stylesheet" type="html/css" href="/WEB-INF/style.css"/>
</head>
<body>
<div align="center">
<h1>Liste des utilisateurs</h1>
<table border="1">
<tr>
<th>Id.</th>
<th>Nom d'utilisateur</th>
<th>Adresse email</th>
<th>Mot de passe</th>
<th>Date d'inscription</th>
<th>Action</th>
</tr>
<c:forEach items="${listeUtilisateur}" var="u">
<tr>
<td><c:out value="${u.idUtilisateur}"/></td>
<td><c:out value="${u.nomUtilisateur}"/></td>
<td><c:out value="${u.emailUtilisateur}"/></td>
<td><c:out value="${u.motPasseUtilisateur}"/></td>
<td><c:out value="${u.dateInscriptionUtilisateur}"/></td>
<td>Edit Delete</td>
</tr>
</c:forEach>
</table>
<h3>Nouveau ? Cliquer ici</h3>
</div>
</body>
</html>
application.properties
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/gestionutilisateur
database.username=root
database.password=1234
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.show_format=true
hibernate.hbm2ddl.auto=update
I finally find what's wrong. It's a matter of date format. I declare a Timestamsp in my model but type something like "2017-10-05" in my view.
Related
I'm trying to make an interface for my database created in MySQL Workbench, and i can't simply view the data from any table. I can add a client, and then it appears on Workbench, but not in .jsp file. What am i missing ?
pojo.Clienti
package pojo;
import java.util.HashSet;
import java.util.Set;
public class Clienti implements java.io.Serializable {
private Integer idclient;
private String nume_institutie_firma;
private String cod_unic;
private String adresa;
private Set angajats = new HashSet(0);
public Clienti() {
}
public Clienti(String nume_institutie_firma, String cod_unic, String adresa, Set angajats) {
this.nume_institutie_firma = nume_institutie_firma;
this.cod_unic = cod_unic;
this.adresa = adresa;
this.angajats = angajats;
}
public Integer getIdclient() {
return this.idclient;
}
public void setIdclient(Integer idclient) {
this.idclient = idclient;
}
public String getnume_institutie_firma() {
return this.nume_institutie_firma;
}
public void setnume_institutie_firma(String nume_institutie_firma) {
this.nume_institutie_firma = nume_institutie_firma;
}
public String getcod_unic() {
return this.cod_unic;
}
public void setcod_unic(String cod_unic) {
this.cod_unic = cod_unic;
}
public String getAdresa() {
return this.adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
public Set getAngajats() {
return this.angajats;
}
public void setAngajats(Set angajats) {
this.angajats = angajats;
}
}
pojo.Clienti.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="pojo.Clienti" table="clienti" catalog="tema"
optimistic-lock="version">
<id name="idclient" type="java.lang.Integer">
<column name="idclient" />
<generator class="identity" />
</id>
<property name="nume_institutie_firma" type="string">
<column name="nume_institutie_firma" length="45" />
</property>
<property name="cod_unic" type="string">
<column name="cod_unic" length="45" />
</property>
<property name="adresa" type="string">
<column name="adresa" length="45" />
</property>
<set name="angajats" table="angajati" inverse="true"
lazy="true" fetch="select">
<key>
<column name="idclient" />
</key>
<one-to-many class="pojo.Angajati" />
</set>
</class>
</hibernate-mapping>
*hibernate.cfg.xml*
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tema</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">pass</property>
<mapping resource="pojo/Angajati.hbm.xml"/>
<mapping resource="pojo/Clienti.hbm.xml"/>
<mapping resource="pojo/Proiecte.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="tema"/>
<table-filter match-name="proiecte"/>
<table-filter match-name="clienti"/>
<table-filter match-name="angajati"/>
</hibernate-reverse-engineering>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>ClientiController</servlet-name>
<servlet-class>Controller.ClientiController</servlet-class>
</servlet>
<servlet>
<servlet-name>ProiecteController</servlet-name>
<servlet-class>Controller.ProiecteController</servlet-class>
</servlet>
<servlet>
<servlet-name>AngajatiController</servlet-name>
<servlet-class>Controller.AngajatiController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ClientiController</servlet-name>
<url-pattern>/ClientiController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ProiecteController</servlet-name>
<url-pattern>/ProiecteController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AngajatiController</servlet-name>
<url-pattern>/AngajatiController</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
DAO.ClientiDao
/*
* 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 DAO;
import java.util.List;
import pojo.Clienti;
/**
*
* #author vali
*/
public interface ClientiDao {
public void adaugaClienti (Clienti client);
public List<Clienti> afiseazaClienti();
public void modificaClienti (int idclient, String nume_institutie_firma, String cod_unic, String adresa);
public void stergeClient (Clienti client);
}
DAOImpl.ClientiDaoImpl
/*
* 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 DAOImpl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Clienti;
import DAO.ClientiDao;
/**
*
* #author vali
*/
public class ClientiDaoImpl implements ClientiDao{
public void adaugaClienti(Clienti client) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.save(client);
transaction.commit();
session.close();
}
public List<Clienti> afiseazaClienti() {
List<Clienti> listaClienti = new ArrayList();
Session session = HibernateUtil.getSessionFactory().openSession();
org.hibernate.Query query = session.createQuery("From Clienti");
listaClienti = query.list();
return listaClienti;
}
public void modificaClienti(int idclient, String nume_institutie_firma, String cod_unic, String adresa) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Clienti detaliiclienti = (Clienti) session.load(Clienti.class, idclient);
detaliiclienti.setnume_institutie_firma(nume_institutie_firma);
detaliiclienti.setcod_unic(cod_unic);
detaliiclienti.setAdresa(adresa);
session.update(detaliiclienti);
transaction.commit();
session.close();
}
public void stergeClient(Clienti client) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(client);
transaction.commit();
session.close();
}
}
Controller.ClientiController
package Controller;
import DAO.ClientiDao;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pojo.Clienti;
import DAOImpl.ClientiDaoImpl;
/**
*
* #author vali
*/
public class ClientiController extends HttpServlet {
Clienti client = new Clienti();
ClientiDaoImpl clientDaoImpl = new ClientiDaoImpl();
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("adaugaClient") != null) {
String nume_institutie_firma = request.getParameter("nume_institutie_firma");
String cod_unic = request.getParameter("cod_unic");
String adresa = request.getParameter("adresa");
client.setnume_institutie_firma(nume_institutie_firma);
client.setcod_unic(cod_unic);
client.setAdresa(adresa);
clientDaoImpl.adaugaClienti(client);
RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
rd.forward(request, response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("afiseazaClienti") != null) {
List<Clienti> listaClienti = new ArrayList();
listaClienti = clientDaoImpl.afiseazaClienti();
request.setAttribute("listaClienti", listaClienti);
RequestDispatcher rd = request.getRequestDispatcher("tabela_Clienti.jsp");
rd.forward(request, response);
}
if (request.getParameter("modificaClient") != null) {
int id1 = Integer.parseInt(request.getParameter("idclient"));
String nume_institutie_firma = request.getParameter("nume_institutie_firma");
String cod_unic = request.getParameter("cod_unic");
String adresa = request.getParameter("adresa");
clientDaoImpl.modificaClienti(id1, nume_institutie_firma, cod_unic, adresa);
RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
rd.forward(request, response);
}
if (request.getParameter("stergeClient") != null) {
int id2 = Integer.parseInt(request.getParameter("idclient"));
client.setIdclient(id2);
clientDaoImpl.stergeClient(client);
RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
rd.forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
I am reviewing my Java skills and your support to the community is amazing, your tips have helped me a lot.
I am stuck in a Hibernate #OneToOne configuration, it is a very simple design and code but I can´t find the error. I´d really appreciate your help.
This is the user.java code, the user_id is generated by an autoincrement column at MySQL. I have omitted hash() and equals() code for simplicity. Hibernate understands the User class but something is missing to get to the Address class that is at the other side of the relationship.
Any help would be very appreciated.
Thank you
1) This is the user.java:
package myPackage;
import java.io.Serializable;
import java.util.Arrays;
import javax.persistence.*;
#Entity
#Table(name="user1")
public class User implements Serializable {
private static final long serialVersionUID = 3271213543123246487L;
#Id
#GeneratedValue
#Column(name="user_id")
private Integer user_id;
#Column(name="user_name", length=100, nullable=false)
private String user_name;
#OneToOne (cascade= CascadeType.ALL)
#PrimaryKeyJoinColumn(name="user_id")
private Address myAddress;
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public Address getMyAddress() {
return myAddress;
}
public void setMyAddress(Address myAddress) {
this.myAddress = myAddress;
}
}
2) This is the Address.java code:
package myPackage;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="address1")
public class Address implements Serializable {
private static final long serialVersionUID = 3605176021936036836L;
#Id
#GeneratedValue(generator="address_ibfk_2")
#org.hibernate.annotations.GenericGenerator(name="address_ibfk_2",
strategy="foreign",parameters =#Parameter(name="property",value="user1"))
#Column(name="user_id")
private Integer user_id;
#Column(name="address_line1", length=100, nullable=false)
private String address_line1;
public String getAddress_line1() {
return address_line1;
}
public void setAddress_line1(String address_line1) {
this.address_line1 = address_line1;
}
}
3) This is the very simple TestUser class
public class TestUser {
public static void main(String[] args) {
Session mySession = HibernateUtil.getSessionFactory().openSession();
System.out.println("Connection status"+mySession.isConnected());
System.out.println("Session status"+mySession.isOpen());
Transaction myTransaction = mySession.beginTransaction();
try {
User myUser = new User();
Address myAddress = new Address();
myUser.setUser_name("TesteO2O");
myAddress.setAddress_line1("Rua A");
myUser.setMyAddress(myAddress);
mySession.save(myUser);
myTransaction.commit();
System.out.println("myUser saved sucessfully");
} catch (Exception e) {
e.printStackTrace();
myTransaction.rollback();
} finally {
mySession.close();
}
}
}
4) This is the hibernate.cfg.xml config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--MySQL Config-->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/p2pl_dev?serverTimezone=UTC</property>
<property name="connection.username">xyz</property>
<property name="connection.password">blabla</property>
<property name="current_session_context_class">thread</property>
<!--Connection Pool Config: max_statements cached, idle time in seconds-->
<property name="c3po.min_size">2</property>
<property name="c3po.max_size">3</property>
<property name="c3po.timeout">300</property>
<property name="c3po.max_stamentes">50</property>
<property name="c3po.idle_test_period">3000</property>
<!--Debug Config, show_sql=console, format_sql=legible -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="generate_statistics">true</property>
<property name="use_sql_comments">true</property>
<!-- Classes -->
<mapping class="myPackage.User"/>
<mapping class="myPackage.Address"/>
</session-factory>
</hibernate-configuration>
5) Finally the error trace
Hibernate:
/* insert myPackage.User
*/ insert
into
user1
(user_name)
values
(?)
java.lang.NullPointerException
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValue(AbstractEntityTuplizer.java:650)
at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValue(AbstractEntityPersister.java:4736)
at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:96)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:117)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:684)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:676)
at org.hibernate.engine.spi.CascadingActions$5.cascade(CascadingActions.java:235)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:460)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:294)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at myPackage.TestUser.main(TestUser.java:26)
Emp.java
package com.javatpoint;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
EmpController.java
package com.javatpoint;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.javatpoint.Emp;
import com.javatpoint.EmpDao;
#Controller
public class EmpController {
#Autowired
EmpDao dao;//will inject dao from xml file
/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/
#RequestMapping("/empform")
public ModelAndView showform(){
return new ModelAndView("empform","command",new Emp());
}
/*It saves object into database. The #ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Emp emp){
dao.save(emp);
return new ModelAndView("redirect:/empform.jsp");//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
#RequestMapping("/viewemp")
public ModelAndView viewemp(){
List<Emp> list=dao.getEmployees();
return new ModelAndView("viewemp","list",list);
}
}
EmpDao.java
package com.javatpoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import
org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.javatpoint.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into emp(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from emp where name=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from emp",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setName(rs.getString(1));
e.setSalary(rs.getFloat(2));
e.setDesignation(rs.getString(3));
return e;
}
});
}
}
spring1-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.javatpoint"/>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/headway" />
<property name="username" value="root" />
<property name="password" value="toor" />
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.javatpoint.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring1</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring1</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
empform.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>Insert title here</title>
</head>
<body>
<h1>Add New Employee</h1>
<form method="post" action="save">
<table >
<tr>
<td>Name : </td>
<td><input path="name" /></td>
</tr>
<tr>
<td>Salary :</td>
<td><input path="salary" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><input path="designation" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
<form>
</body>
</html>
viewemp.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>Insert title here</title>
</head>
<body>
<h1>Employees List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit</th><th>Delete</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.id}</td>
<td>${emp.name}</td>
<td>${emp.salary}</td>
<td>${emp.designation}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
<br/>
Add New Employee
</body>
</html>
hi
I am trying to fetching the data from the database but it show's the only curd .
enter image description here it show the like that .
and it display the jsp file data. I am check the all possible way to display the data from the database.curd will be displayed but it show's the jsp file data.
please check the my code and provide the solution.
thank you.
I am not sure about this solution is gonna work in you case,
but i think you forget to add JSTL Core Tags
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
after this jstl know <c:forEach var="emp" items="${list}"> will render as for loop and in each iteration emp is your object variable
Emp.java
package com.management;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
EmpController.java
package com.management;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.management.Emp;
import com.management.EmpDao;
#Controller
public class EmpController {
#Autowired
EmpDao dao;//will inject dao from xml file
/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/
#RequestMapping("/empform")
public ModelAndView showform(){
return new ModelAndView("empform","command",new Emp());
}
/*It saves object into database. The #ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Emp emp){
dao.save(emp);
return new ModelAndView("redirect:/viewemp");//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
#RequestMapping("/viewemp")
public ModelAndView viewemp(){
List<Emp> list=dao.getEmployees();
return new ModelAndView("viewemp","list",list);
}
/* It displays object data into form for the given id.
* The #PathVariable puts URL data into variable.*/
#RequestMapping(value="/editemp/{id}")
public ModelAndView edit(#PathVariable int id){
Emp emp=dao.getEmpById(id);
return new ModelAndView("empeditform","command",emp);
}
/* It updates model object. */
#RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("emp") Emp emp){
dao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
/* It deletes record for the given id in URL and redirects to /viewemp */
#RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable int id){
dao.delete(id);
return new ModelAndView("redirect:/viewemp");
}
}
EmpDao.java
package com.management;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.management.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Emp99 set name='"+p.getName()+"', salary="+p.getSalary()+", designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Emp99",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}
servlet-management.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 = "com.spring" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://loclahost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.spring.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>management</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>management</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
hi
my trying to insert the value to the database by using the spring-mvc.
and using the mysql database.
while execution process it shows the error like that-org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.spring.EmpDao] for bean with name 'dao' defined in ServletContext resource [/WEB-INF/management-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.spring.EmpDao .
please provide the soluation.
thank you.
I've made a simple form and I am trying to validate it but I have some trouble. This is my controller:
import ninja.majewski.store.forms.ContactDTO;
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 javax.validation.Valid;
#Controller
public class MainController {
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public String contact(Model model) {
addBasicInfo(model);
model.addAttribute("form", new ContactDTO());
return "contact";
}
#RequestMapping(value = "/contact", method = RequestMethod.POST)
public String contact(Model model, #ModelAttribute("form") #Valid ContactDTO form, BindingResult result) {
addBasicInfo(model);
model.addAttribute("form", new ContactDTO());
// return false
System.out.println(result.hasErrors());
if (result.hasErrors()) {
return "contact";
} else {
return "redirect:/home";
}
}
}
This is my DTO class:
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class ContactDTO {
#NotEmpty
#Size(min = 3)
private String name;
#NotEmpty
#Email
private String email;
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And my form HTML:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
</body>
</html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>I AM A HORSE</title>
<spring:url value="/resources/css/bootstrap.css" var="bootstrapCss"/>
<link href="${bootstrapCss}" rel="stylesheet" type="text/css"/>
</head>
<body>
<jsp:include page="parts/header.jsp"/>
<jsp:include page="parts/leftMenu.jsp"/>
<table>
<td>
<form:form action="/contact" modelAttribute="form" method="post">
Name:
<form:input path="name" id="name"/>
<form:errors path="name" cssclass="error"/>
<br/>
Email:
<form:input path="email" id="email"/>
<form:errors path="email" cssclass="error"/>
<br/>
Message:
<form:input path="message" id="message"/>
<form:errors path="message" cssclass="error"/>
<br/>
<input type="submit" value="Send message"/>
</form:form>
</td>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="/resources/js/bootstrap.min.js"></script>
</body>
</html>
And my app configuration:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="ninja.majewski"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
The problem is that even when I submit empty form BindingResult.hasErrors() gives false. Where have I made a mistake?
#ModelAttribute should be first parameter of the method. Try to replace it with Model, and declare #Valid annotation before #ModelAttribute.
#RequestMapping(value = "/contact", method = RequestMethod.POST)
public String contact(#Valid #ModelAttribute("form") ContactDTO form, BindingResult result, Model model) {
addBasicInfo(model);