Tomcat, JPA, Eclipse - Name is not bound in this Context - java

Hi I wrote simple phonebook app, and when I type id in form and click button for search record from database I have this exception
javax.naming.NameNotFoundException: Name
[com.kamil.controller.PersonServlet/personDao] is not bound in this
Context. Unable to find [com.kamil.controller.PersonServlet].
org.apache.naming.NamingContext.lookup(NamingContext.java:819)
org.apache.naming.NamingContext.lookup(NamingContext.java:167)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Unknown Source)
It's apepar only first time when I run app on server, next times i have statement: The requested resource is not available.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="test">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.kamil.model.Person</class>
<properties>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/phonebook?charsetEncoding=utf8"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>test</display-name>
<welcome-file-list>
<welcome-file>personinfo.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>ds/phonebook</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
PersonServlet.java
package com.kamil.controller;
import com.kamil.dao.PersonDaoLocal;
import com.kamil.model.Person;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "PersonServlet", urlPatterns = {"/PersonServlet"})
public class PersonServlet extends HttpServlet {
#EJB
private PersonDaoLocal personDao;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
String personIdStr = request.getParameter("personId");
int personId=0;
if(personIdStr!=null && !personIdStr.equals("")){
personId=Integer.parseInt(personIdStr);
}
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String numberStr = request.getParameter("number");
int number=0;
if(numberStr!=null && !numberStr.equals("")){
number=Integer.parseInt(numberStr);
}
Person person = new Person(personId, firstname, lastname, number);
if("Add".equalsIgnoreCase(action)){
personDao.addPerson(person);
}else if("Edit".equalsIgnoreCase(action)){
personDao.editPerson(person);
}else if("Delete".equalsIgnoreCase(action)){
personDao.deletePerson(personId);
}else if("Search".equalsIgnoreCase(action)){
person = personDao.getPerson(personId);
}
request.setAttribute("person", person);
request.setAttribute("allPersons", personDao.getAllPersons());
request.getRequestDispatcher("personinfo.jsp").forward(request, response);
}
Person.java
package com.kamil.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#Entity
#Table(name="person")
#NamedQueries({#NamedQuery(name="Person.getAll",query="SELECT e FROM Person e")})
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column
private int personId;
#Column
private String firstname;
#Column
private String lastname;
#Column
private int number;
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
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 int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Person(int personId, String firstname, String lastname, int number) {
super();
this.personId = personId;
this.firstname = firstname;
this.lastname = lastname;
this.number = number;
}
Person(){}
}
PersonDao.java
package com.kamil.dao;
import com.kamil.model.Person;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
#Stateless
public class PersonDao implements PersonDaoLocal {
#PersistenceContext
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
private EntityManager em = emf.createEntityManager();
#Override
public void addPerson(Person person) {
em.persist(person);
}
#Override
public void editPerson(Person person) {
em.merge(person);
}
#Override
public void deletePerson(int personId) {
em.remove(getPerson(personId));
}
#Override
public Person getPerson(int personId) {
return em.find(Person.class, personId);
}
#Override
public List<Person> getAllPersons() {
return em.createNamedQuery("Person.getAll").getResultList();
}
}
PersonDaoLocal.java
package com.kamil.dao;
import com.kamil.model.Person;
import java.util.List;
import javax.ejb.Local;
#Local
public interface PersonDaoLocal {
void addPerson(Person person);
void editPerson(Person person);
void deletePerson(int personId);
Person getPerson(int personId);
List<Person> getAllPersons();
}
personinfo.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Information</title>
</head>
<body>
<h1>Person Information</h1>
<form action="./PersonServlet" method="POST">
<table>
<tr>
<td>Person ID</td>
<td><input type="text" name="personId" value="${person.personId}" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname" value="${person.firstname}" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname" value="${person.lastname}" /></td>
</tr>
<tr>
<td>Number</td>
<td><input type="text" name="number" value="${person.number}" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="action" value="Add" />
<input type="submit" name="action" value="Edit" />
<input type="submit" name="action" value="Delete" />
<input type="submit" name="action" value="Search" />
</td>
</tr>
</table>
</form>
<br>
<table border="1">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Number</th>
<c:forEach items="${allPersons}" var="pers">
<tr>
<td>${pers.personId}</td>
<td>${pers.firstname}</td>
<td>${pers.lastname}</td>
<td>${pers.yearLevel}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
View full project on github

Related

Spring Mvc Student registrationform

I am novice user to spring. I have tried to code the below program however it is giving 404 error. I am unable to track where the exact error is
throwing HTTP Status 404 - /submitAdmissionForm.html.
HTTP Status 404 - /submitAdmissionForm.html
type Status report
message /submitAdmissionForm.html
description The requested resource is not available.
Apache Tomcat/8.0.28
my files:
welcome page - index.jsp
<html>
<body>
<h3> STUDENT ADMISSION FORM FOR ENGINEERING COURSES</h3>
<form action="/submitAdmissionForm.html" method="post">
Student's Name : <input type="text" name="studentName" />
Student's Hobby :<input type="text" name="studentHobby" />
Student's Mobile :<input type="text" name="studentMobile" />
Student's DOB :<input type="text" name="studentDOB" />
Student's Skills set
<select name="studentSkills" >
<option value="Java Core">Java Core</option>
<option value="Spring Core">Spring Core</option>
<option value="Spring MVC">Spring MVC</option>
</select>
Student's Address :
country: <input type="text" name="studentAddress.country"/>
city: <input type="text" name="studentAddress.city" />
street: <input type="text" name="studentAddress.street" />
pincode:<input type="text" name="studentAddress.pincode" />
<input type="submit" value="Submit this form by clicking here" />
</form>
</body>
</html>
descriptor
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" 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>praygod</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>student</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>student</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
student-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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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="com.gappu.student" />
<mvc:annotation-driven/>
<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>
</bean>
</beans>
Controller.java
package com.gappu.student;
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;
#Controller
public class studentcontroller {
#RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm() {
ModelAndView model1 = new ModelAndView();
model1.setViewName("AdmissionSuccess");
return model1;
}
}
here is my success page
AdmissionSuccess.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>
Hello there
</body>
</html>
when I try running this program it gives me error as 404 suggested URL is not present.
I think that the problem is that your project doesn't include all the libraries. so If you'are using Eclipse and Maven go to
Project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Maven Dependencies.
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>HelloWorldWebApp</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
messages.properties
NotEmpty.student.studentName={0} can't be empty
Pattern.student.studentName=Number is not allowed for {0}
Size.student.studentName={0} field is between {2} and {1}
NotEmpty.student.gender=Please select gender {0}
NotNull.student.technology=Select at least one technology
Size.student.technology=Select at least one {0}
NotEmpty.student.city=Please select {0}
NotEmpty.student.email={0} can't be empty
Email.student.email=Please enter valid {0}
NotEmpty.student.password={0} can't be empty
NotNull.student.phone={0} no can't be empty
Min.student.phone=Please enter valid {0}
NotEmpty.studentCredential.email={0} can't be empty
Email.studentCredential.email=Please enter valid {0}
NotEmpty.studentCredential.password={0} can't be empty
dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.infotech.controller"></context:component-scan>
<context:component-scan base-package="com.infotech.service.impl"></context:component-scan>
<context:component-scan base-package="com.infotech.dao.impl"></context:component-scan>
<context:component-scan base-package="com.infotech.util"></context:component-scan>
<mvc:resources mapping="/image/**" location="/image/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/view/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver.class.name}"></property>
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<array>
<value>com.infotech.model.Student</value>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>/WEB-INF/database.properties</value>
</array>
</property>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages"></property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20848820" />
</bean>
</beans>
database.properties
driver.class.name=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/da
db.username=root
db.password=root
view folder
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Management Screen</title>
</head>
<body>
<div align="center">
<h1>Employee List</h1>
<h3>
New Employee
</h3>
<table border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Telephone</th>
<th>Action</th>
<th>Action</th>
<th>Action</th>
<th>Action</th>
</tr>
<c:forEach var="student" items="${listEmployee}">
<tr>
<td>${student.studentName}</td>
<td>${student.gender}</td>
<td>${student.technology}</td>
<td>${student.city}</td>
<td>${student.email}</td>
<td>${student.password}</td>
<td>${student.phone}</td>
<td>${student.image}</td>
<td>Edit
Delete</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
register.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 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>Registration Page</title>
<style type="text/css">
.error {
color: red;
}
</style>
</head>
<body>
<h3 align="center">${headerMessage}</h3>
<form:form action="registerSuccess"
method="post" modelAttribute="student" enctype="multipart/form-data">
<table align="center">
<caption align="top">Student registration form</caption>
<tr>
<td>Enter Email:</td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssClass="error"/></td>
</tr>
<tr>
<td>Enter Password:</td>
<td><form:password path="password"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td>Enter your Name:</td>
<td><form:input path="studentName"/></td>
<td><form:errors path="studentName" cssClass="error"/></td>
</tr>
<tr>
<td>Enter Phone No:</td>
<td><form:input path="phone"/></td>
<td><form:errors path="phone" cssClass="error"/></td>
</tr>
<tr>
<td>Gender:</td>
<td><form:radiobutton path="gender" value="Male" label="Male" />
<form:radiobutton path="gender" value="Female" label="Female" /></td>
<td><form:errors path="gender" cssClass="error" /></td>
</tr>
<tr>
<td>Select Technology:</td>
<td><form:select path="technology">
<form:options items="${technologyList}" />
</form:select></td>
<td><form:errors path="technology" cssClass="error" /></td>
</tr>
<tr>
<td>Select city:</td>
<td><form:select path="city">
<form:options items="${citesList}" />
</form:select></td>
<td><form:errors path="city" cssClass="error" /></td>
</tr>
<td><input type="submit" value="Register"></td>
</tr>
</table>
</form:form>
<br>
VewAll
</body>
</html>
welcome.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>Welcome Page</title>
</head>
<body>
<h3 align="right">Back</h3>
<h2 align="center">${headerMessage}</h2>
<h3 align="center">You have registered with following Info::::</h3>
<table align="center" border="5px">
<tr>
<td>Student email:</td>
<td>${student.email}</td>
</tr>
<tr>
<td>Student Name:</td>
<td>${student.studentName}</td>
</tr>
<tr>
<td>Student Phone:</td>
<td>${student.phone}</td>
</tr>
<tr>
<td>Student Gender</td>
<td>${student.gender}</td>
</tr>
<tr>
<td>Selected Technology:</td>
<td>${student.technology}</td>
</tr>
<tr>
<td>City</td>
<td>${student.city}</td>
</tr>
<tr>
<td>City</td>
<td>${student.image}</td>
</tr>
</table>
</body>
</html>
package com.infotech.dao;
import com.infotech.model.Student;
import java.util.List;
public interface StudentDAO {
public void addEmployee(Student student);
public List<Student> getAllStudent();
public void deleteStudent(Integer id);
public Student updateStudent(Student student);
public Student getStudent(int id);
}
package com.infotech.dao.impl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.infotech.dao.StudentDAO;
import com.infotech.model.Student;
#Repository
public class StudentDAOImpl implements StudentDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addEmployee(Student student) {
sessionFactory.getCurrentSession().saveOrUpdate(student);
}
#Override
#SuppressWarnings("unchecked")
public List<Student> getAllStudent() {
// TODO Auto-generated method stub
return sessionFactory.getCurrentSession().createQuery("from Student").list();
}
#Override
public void deleteStudent(Integer id) {
// TODO Auto-generated method stub
Student student=(Student) sessionFactory.getCurrentSession().load(Student.class, id);
if (null != student) {
this.sessionFactory.getCurrentSession().delete(student);
}
}
#Override
public Student updateStudent(Student student) {
sessionFactory.getCurrentSession().update(student);
return student ;
}
#Override
public Student getStudent(int id) {
// TODO Auto-generated method stub
return (Student) sessionFactory.getCurrentSession().get(
Student.class, id);
}
}
package com.infotech.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name = "student_table")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#NotEmpty
#Pattern(regexp="[^0-9]+")
#Size(min=6,max=20)
#Column(name = "student_name")
private String studentName;
#NotEmpty
#Column(name = "gender")
private String gender;
#Size(min=1)
#NotNull
#Column(name = "technology")
private String technology;
#NotEmpty
#Column(name = "city")
private String city;
#NotEmpty
#Email
#Column(name = "email")
private String email;
#NotEmpty
#Column(name = "password")
private String password;
#NotNull
#Min(value = 1000000000)
#Column(name = "phone")
private Long phone;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setPhone(Long phone) {
this.phone = phone;
}
public Long getPhone() {
return phone;
}
public String getTechnology() {
return technology;
}
public void setTechnology(String technology) {
this.technology = technology;
}
}
package com.infotech.service;
import com.infotech.model.Student;
import java.util.List;
public interface StudentService {
public void addStudent(Student student);
public List<Student> getAllStudent();
public void deleteStudent(Integer id);
public Student getStudent(int id);
public Student updateEmployee(Student student);
}
package com.infotech.service.impl;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.infotech.dao.StudentDAO;
import com.infotech.model.Student;
import com.infotech.service.StudentService;
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentDAO studentdao;
#Override
public void addStudent(Student student) {
// TODO Auto-generated method stub
studentdao.addEmployee(student);
}
#Override
#Transactional
public List<Student> getAllStudent() {
// TODO Auto-generated method stub
return studentdao.getAllStudent();
}
#Override
#Transactional
public void deleteStudent(Integer id) {
// TODO Auto-generated method stub
studentdao.deleteStudent(id);
}
#Override
#Transactional
public Student getStudent(int id) {
// TODO Auto-generated method stub
return studentdao.getStudent(id);
}
#Override
#Transactional
public Student updateEmployee(Student student) {
// TODO Auto-generated method stub
return studentdao.updateStudent(student);
}
}
package com.infotech.controller;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.infotech.model.Student;
import com.infotech.service.StudentService;
#Controller
public class MyController {
#Autowired
private StudentService studentService;
public static String uploadDirectory = System.getProperty("user.dir")+"/uploads";
#RequestMapping(value = {"/","/register"} ,method=RequestMethod.GET)
public String registerPage(Model model){
model.addAttribute("student", new Student());
return "register";
}
#RequestMapping(value ="/registerSuccess" ,method=RequestMethod.POST)
public ModelAndView registerSuccess(#Valid #ModelAttribute("student") Student student,BindingResult bindingResult ){
if(bindingResult.hasErrors()){
return new ModelAndView("register");
}
studentService.addStudent(student);
ModelAndView modelAndView = new ModelAndView("welcome");
modelAndView.addObject("student", student);
return modelAndView;
}
#ModelAttribute
public void headerMessage(Model model){
model.addAttribute("headerMessage", "Welcome to Starve Technology");
List<String> techList = new ArrayList<>();
techList.add("Hibernate");
techList.add("Spring");
techList.add("JSP");
techList.add("Servlet");
techList.add("Struts");
List<String> citesList = new ArrayList<>();
citesList.add("Pune");
citesList.add("Chennai");
citesList.add("Delhi");
citesList.add("Other");
model.addAttribute("technologyList", techList);
model.addAttribute("citesList", citesList);
}
#RequestMapping(value = "/home" )
public ModelAndView vewPage(ModelAndView model){
List<Student> liststudents=studentService.getAllStudent();
model.addObject("listEmployee", liststudents);
model.setViewName("home");
return model;
}
#RequestMapping(value = "/editEmployee", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int id = Integer.parseInt(request.getParameter("id"));
Student student = studentService.getStudent(id);
ModelAndView model = new ModelAndView("register");
model.addObject("student", student);
return model;
}
#RequestMapping(value = "/deleteEmployee", method = RequestMethod.GET)
public ModelAndView deleteEmployee(HttpServletRequest request) {
int id = Integer.parseInt(request.getParameter("id"));
studentService.deleteStudent(id);
return new ModelAndView("redirect:/");
}
}

I am beginner in Spring framework.I try custom form validation annotation in my project but custom validation annotation can not work

FormValidationController.java
package com.binod.formvalidation;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
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.binod.formvalidation.Entity.Student;
#Controller
public class FormValidationController {
#RequestMapping(value="/form.html" ,method=RequestMethod.GET)
ModelAndView sendLoginForm() {
ModelAndView andView=new ModelAndView("AdmissionForm");
return andView;
}
#ModelAttribute
public void addCommonError(Model model) {
model.addAttribute("commonError", "Welcome Spring MVC Zone"); }
#RequestMapping(value="/submit.html", method=RequestMethod.POST)
ModelAndView sendSuccessForm(#Valid #ModelAttribute("student")
Student student, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
ModelAndView andView=new ModelAndView("AdmissionForm");
return andView;
}
ModelAndView andView=new ModelAndView("AdmissionSuccess");
return andView;
}
}
Custom form validation annotation is IsValidHobby.java
package com.binod.formvalidation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import org.springframework.messaging.handler.annotation.Payload;
#Documented
#Constraint(validatedBy=HobbyValidator.class)
#Target({ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
public #interface IsValidHobby {
String message() default "Please provide a valid hobby accepted
hobbies are football, volleyball,cricket";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default{};
}
The HobbyValidator.java
package com.binod.formvalidation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class HobbyValidator implements
ConstraintValidator<IsValidHobby, String> {
#Override public void initialize(IsValidHobby iSvalidHobby) {
}
#Override public boolean isValid(String studentHobby,
ConstraintValidatorContext ctx) {
if(studentHobby==null) {
return false;
}
if (studentHobby.matches("cricket|volleyBall|football")) {
return true;
}
else {
return false;
}
}
}
Student.java
package com.binod.formvalidation.Entity;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import com.sun.istack.internal.NotNull;
public class Student {
#Size(min=4,max=9)
private String firstName;
private String lastName;
#NotNull
private int rollNo;
private StudentDetail studentDetail;
public String getFirstName() {
return firstName; }
public StudentDetail getStudentDetail() {
return studentDetail;
}
public void setStudentDetail(StudentDetail studentDetail) {
this.studentDetail = studentDetail;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
}
StudentDetail.java
package com.binod.formvalidation.Entity;
import com.binod.formvalidation.IsValidHobby;
import com.sun.istack.internal.NotNull;
public class StudentDetail {
#IsValidHobby
private String studentHobby;
#NotNull private String faculty,address;
#NotNull
private long phoneNo;
public String getStudentHobby() {
return studentHobby;
}
public void setStudentHobby(String studentHobby) {
this.studentHobby = studentHobby;
}
public String getFaculty() {
return faculty;
}
public void setFaculty(String faculty) {
this.faculty = faculty;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(long phoneNo) {
this.phoneNo = phoneNo; }
}
AdmissionForm.jsp
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form%>
<html>
<head>
<title>Admission Form</title> </head>
<body>
<form:errors path="student.*"/>
<h1 align="center">Student Submission Form</h1> <br/><br/>
<h2 align="center">${commonError}</h2>
<form action="submit.html" method="POST">
<table align="center">
<tr>
<td>First Name</td>
<td><input type="text" name="firstName" />
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastName" />
</tr>
<tr>
<td>Faculty</td>
<td><input type="text" name="studentDetail.faculty" />
</tr>
<tr>
<td>RollNo</td>
<td><input type="text" name="rollNo" />
</tr>
<tr>
<td>Phone NO</td>
<td><input type="text" name="StudentDetail.phoneNo" />
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="studentDetail.address" />
</tr>
<tr>
<td>Student Hobby</td>
<td><input type="text" name="studentDetail.studentHobby"/>
</tr>
<tr >
<td colspan="2" align="center">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
AdmissionSuccess.jsp
<html>
<head>
<title>Admission Success</title>
</head>
<body>
<h1 align="center">Your Detail information!!!</h1>
<table align="center">
<tr>
<td>First Name:</td>
<td>${student.firstName }</td>
</tr>
<tr>
<td>Last Name:</td>
<td>${student.lastName }</td>
</tr>
<tr>
<td>Roll No:</td>
<td>${student.rollNo }</td>
</tr>
<tr>
<td>Address:</td>
<td>${student.studentDetail.address }</td>
</tr>
<tr>
<td>Faculty :</td>
<td>${student.studentDetail.faculty}</td>
</tr>
<tr>
<td>PhoneNo:</td>
<td>${student.studentDetail.phoneNo }</td>
</tr>
<tr>
<td>Student HObby</td>
<td>${student.studentDetail.studentHobby}</td>
</tr>
</table>
</body>
SpringFormValidation-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: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.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">
<context:component-scan base-package="com.binod.formvalidation" />
<mvc:annotation-driven />
<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>
</bean>
<bean id="messageSource"
class="org.springframework.context.support.
ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/studentMessage" />
</bean>
</beans>
In my code #IsValidHobby is not working in form custom validation. Where is error in my code.

Spring MVC HTTP Status 400 - Bad Request

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
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
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="RegisterInfo" />
<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 submit the form, I always gets this error
Error:
HTTP Status 400 - Bad Request
The request sent by the client was syntactically incorrect
What is wrong with the code?
You must bind the Date when you submit a HTTP POST. Spring does not know that this is a Date, it sees it as a String.
Add this:
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
To your controller.
According to your code you are using
<prop key="index.htm">indexController</prop>
click
in above code spelling is not correct (htm instead of HTML).
<prop key="index.html">indexController</prop>
click

How to save entity into database?

I have a simple spring mvc project for adding users into database.
I use hibernate 4.1.9, spring framework 3.2.0 and PostgreSQL 9.2.
See my code below
User bean
package org.vdzundza.beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
#SequenceGenerator(name = "user_seq", sequenceName = "user_seq")
#Column(name = "id")
private Long id;
#Column(name = "network")
private String network;
#Column(name = "photo")
private String photo;
#Column(name = "identity")
private String identity;
#Column(name = "firstname")
private String firstName;
#Column(name = "lastname")
private String lastName;
#Column(name = "hash")
private String hash;
#Column(name = "isonline")
private Boolean isOnline;
public User() {
}
//getters and setters
#Override
public String toString(){
StringBuilder out = new StringBuilder();
out.append("[");
out.append("name: " + firstName + " " + lastName);
out.append("\tnetwork: " + network);
out.append("\t Is online: " + isOnline);
return out.toString();
}
}
UserDAO
package org.vdzundza.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.vdzundza.beans.User;
#Repository
public class UserDAOImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.openSession().save(user);
}
#SuppressWarnings("unchecked")
#Override
public List<User> listUser() {
return sessionFactory.openSession().createCriteria(User.class).list();
}
}
UserService
package org.vdzundza.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.vdzundza.beans.User;
import org.vdzundza.dao.UserDao;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDAO;
#Transactional
public void addUser(User user) {
userDAO.addUser(user);
}
#Transactional
public List<User> listUser() {
return userDAO.listUser();
}
}
root-context.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:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:annotation-config />
<context:component-scan base-package="org.vdzundza.dao" />
<context:component-scan base-package="org.vdzundza.service" />
<bean id="propertiesConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
lazy-init="false">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan" value="org.vdzundza.beans" />
</bean>
<bean id="transactionalManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
UserController
package org.vdzundza.web;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.vdzundza.beans.User;
import org.vdzundza.service.UserService;
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
private UserService userService;
#RequestMapping("/")
public String index(){
return "redirect:/user/index";
}
#RequestMapping("/index")
public String listUsers(Map<String, Object> map){
map.put("user", new User());
map.put("userList", userService.listUser());
return "user";
}
#RequestMapping(value = "/add",method = RequestMethod.POST)
public String addUser(#ModelAttribute("user") User user, BindingResult result){
userService.addUser(user);
return "redirect:/user/index";
}
}
user.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>user test spring and hibernate</title>
</head>
<body>
Go back
<br />
<form:form method="post"
action="${pageContext.request.contextPath}/user/add"
commandName="user">
<table>
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="network">network</form:label></td>
<td><form:input path="network" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="add user" /></td>
</tr>
</table>
</form:form>
<c:if test="${empty userList}">
<h2>user list is empty</h2>
</c:if>
<c:if test="${!empty userList}">
<h2>user list</h2>
<table>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Network</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.network}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
New user isn't saved in database.
When I click "add user" I see this in console:
Hibernate: select nextval ('user_seq')
Hibernate: select this_.id as id0_0_, this_.firstname as firstname0_0_, this_.hash as hash0_0_, this_.identity as identity0_0_, this_.isonline as isonline0_0_, this_.lastname as lastname0_0_, this_.network as network0_0_, this_.photo as photo0_0_ from users this_
How to fix this problem?
After you open the session and save the object... flush the session, then close it.
Session session = sessionFactory.openSession();
session.save(user);
session.flush();
session.close();
Get the Advantage of Hibernate Transaction:
Within one transaction you can do several operations and can commit transaction once after successfully completed all operations. The advantage here is you can rollback all previous operations if one operation is fail in your operation batch.
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(user);
tx.commit(); // Flush happens automatically
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close();
}

new to spring, not able to delete user using hibernate

I am new to spring, was working on an example. The example shows how to add data to table using hibernate and list it also, I tried to add extra delete option but its updating record instead. I will post complete code below. ( 2 ) I develop simple web apps using jsp and servlets and lots of jquery ajax, I want to use ajax also with spring, will I be able to code the same way or its something different which i have to learn. To be frank I am scared after seeing the spring pattern.. :).
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"
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">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
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" />
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/production"/>
<property name="username" value="tpsl_admin"/>
<property name="password" value="admin"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.org.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myUserDAO" class="com.org.dao.UserDAOImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean name="/user/*.htm" class="com.org.web.UserController" >
<property name="userDAO" ref="myUserDAO" />
</bean>
<!--
The index controller.
-->
<bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
UserDAO.java
package com.org.dao;
import com.org.domain.User;
import java.util.List;
public interface UserDAO {
public void saveUser(User user) ;
public List<User> listUser() ;
public void deleteUser(User user) ;
}
UserDAOImpl.java
package com.org.dao;
import com.org.domain.User;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class UserDAOImpl implements UserDAO {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Override
public void saveUser(User user) {
hibernateTemplate.saveOrUpdate(user);
}
#Override
#SuppressWarnings("unchecked")
public List<User> listUser() {
return hibernateTemplate.find("from User");
}
#Override
public void deleteUser(User user) {
hibernateTemplate.delete(user);
}
}
User.java
package com.org.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="USER")
public class User {
private Long id;
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
#Id
#GeneratedValue
#Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="USER_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="USER_PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="USER_GENDER")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name="USER_COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Column(name="USER_ABOUT_YOU")
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
#Column(name="USER_COMMUNITY")
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
#Column(name="USER_MAILING_LIST")
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
UserController.java
package com.org.web;
import com.org.dao.UserDAO;
import com.org.domain.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#RequestMapping(params = "add", method = RequestMethod.POST)
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
userDAO.saveUser(user);
return new ModelAndView("redirect:list.htm");
}
#RequestMapping(params = "delete", method = RequestMethod.POST)
#Transactional
public ModelAndView delete(HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
userDAO.deleteUser(user);
return new ModelAndView("redirect:list.htm");
}
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("userList", userDAO.listUser());
modelMap.addAttribute("user", new User());
return new ModelAndView("userForm", modelMap);
}
}
ok thats all with the code, the ide i am using is netbeans, sprinf ver is 3.1.1. Hibernate 3.0. Some one please show me where i need to change I am trying since 2 days with fail. Also explain my own code if possible I have many doubts.
Thankyou
userForm.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"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<style type="text/css">
.even {
background-color: silver;
}
</style>
<title>Registration Page</title>
</head>
<body>
<form:form action="add.htm" commandName="user" method="post">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="India" label="India" />
<form:option value="USA" label="USA" />
<form:option value="UK" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><form:checkbox path="community" value="Spring" label="Spring" />
<form:checkbox path="community" value="Hibernate" label="Hibernate" />
<form:checkbox path="community" value="Struts" label="Struts" />
</td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList" label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="add" value="Register"></td>
<td colspan="2"><input type="button" name="delete" value="Delete"></td>
</tr>
</table>
</form:form>
<c:if test="${fn:length(userList) > 0}">
<table cellpadding="5">
<tr class="even">
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Country</th>
<th>About You</th>
<th>Mailing List</th>
<th>Community</th>
</tr>
<c:forEach items="${userList}" var="user" varStatus="status">
<tr class="<c:if test="${status.count % 2 == 0}">even</c:if>">
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.gender}</td>
<td>${user.country}</td>
<td>${user.aboutYou}</td>
<td>${user.mailingList}</td>
<td>${user.community}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
In your dispatcherservlet.xml please comment the below line
<prop key="hibernate.hbm2ddl.auto">create</prop>
as everytime when you restart your server, it will auto create the table when server starts. Please check the mapping correctly for deleting the user and have print or breakpoints and debug the issue, seeing your code hibernateTemplate.delete(user) should work fine.

Categories

Resources