new to spring, not able to delete user using hibernate - java

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.

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:/");
}
}

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

SimpleUrlHandlerMapping do not map with controller (CONTROL IS NOT COMING TO THE CONTROLLER)

Here i am using urlMap property of SimpleUrlHandlerMapping to map with controller but it does not map with Controller.Here I have put my code of dispatcher,Jsp and controller.
I have include following Jar Files--:
com.springsource.org.apache.commons.fileupload-1.2.0.jar
com.springsource.org.apache.commons.httpclient-3.1.0.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.log4j-1.2.15.jar
com.springsource.org.codehaus.jackson.mapper-1.0.0.jar
jmxtools-1.2.1.jar
jstl-1.2 (1).jar
org.springframework.asm-3.0.1.RELEASE-A.jar
org.springframework.beans-3.0.1.RELEASE-A.jar
org.springframework.context-3.0.1.RELEASE-A.jar
org.springframework.core-3.0.1.RELEASE-A.jar
org.springframework.expression-3.0.1.RELEASE-A.jar
org.springframework.oxm-3.0.1.RELEASE-A.jar
org.springframework.web-3.0.1.RELEASE-A.jar
org.springframework.web.portlet-3.0.1.RELEASE-A.jar
org.springframework.web.servlet-3.0.1.RELEASE-A.jar
org.springframework.web.struts-3.0.1.RELEASE-A.jar
spring-webmvc-3.0.5.RELEASE.jar
dispatcher-servlet.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/JSPpages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/Registration.html">
<ref bean="RegistrationCon" />
</entry>
</map>
</property>
</bean>
<bean id="RegistrationCon" class="controllers.registrationController.RegistrationController">
<property name="commandName">
<value>RegistrationBean</value>
</property>
<property name="commandClass">
<value>formBeans.registrationBean.RegistrationBean</value>
</property>
<property name="sessionForm">
<value>false</value>
</property>
<property name="formView">
<value>Registration</value>
</property>
<property name="successView">
<value>RegistrationSuccess</value>
</property>
</bean>
</beans>
RegistrationController:
package controllers.registrationController;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import formBeans.registrationBean.RegistrationBean;
#SuppressWarnings("deprecation")
public class RegistrationController extends SimpleFormController {
protected ModelAndView onSubmit(HttpServletRequest req,HttpServletResponse res,Object command)throws ServletException //--OnSubmit Method Starts--//
{
System.out.println("In controller");
RegistrationBean regBean = (RegistrationBean) command;
String loginName=regBean.getLoginId();
System.out.println("Name---->"+loginName);
String pwd=req.getParameter("pwd");
System.out.println("PassWord---->"+pwd);
ArrayList<String> al=new ArrayList<String>();
al.add(loginName);
al.add(pwd);
ModelAndView mav=new ModelAndView("/RegistrationSuccess");
mav.addObject("ArrayList",al);
mav.addObject("regBean",regBean);
return mav;
}
}
Registration(JSP):
<%# taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head><title>User Personal Details</title>
<style>
table, th{
border: 1px solid black;
}
label{
font-family: "Trebuchet MS", Verdana, Halvetica, Arial;
font-size: 12px;
color: blue;
}
.textfield {
width: 250px;
border: 1px solid #AF9D72;
background-color: #F2ECD7;
}
</style></head>
<body bgcolor="#DDDDDD">
<h3>User Registration</h3>
<br/>
<form:form commandName="RegistrationBean" method="POST" name="RegistrationBean">
<div align="center" style="width:100%; height:100%">
<table style="height:250px; width:400px">
<tr>
<th>Heading</th>
<th>Input</th>
</tr>
<tr>
<td align="left"><label>Name:</label></td>
<td><form:input path="loginId" class="textfield"/></td>
</tr>
<tr>
<td align="left"><label>Password:</label></td>
<td><form:input path="pwd" class="textfield"/></td>
</tr>
<tr>
<td align="left"><label>Confirm Password:</label></td>
<td><form:input path="cpwd" class="textfield"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</div>
</form:form>
</body>
</html>
try this:
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<props>
<prop key="/Registration.html">RegistrationCon</prop>
</props>
</property>
</bean>
if URL lookup should always use the full path within the current servlet context, you may need to set this:
<property name = "alwaysUseFullPath" value = "true" />
to urlMapping bean
Later edit:
Use this for urlMap, the above code was for mappings, sorry.
<property name="urlMap">
<map>
<entry key="/Registration.html" value-ref="RegistrationCon"/>
</map>
...
Issue Solved:
Jar Files That I have Used--:
aopalliance-1.0.jar
commons-logging-api-1.1.1.jar
jstl.jar
org.springframework.asm-3.0.4.RELEASE.jar
org.springframework.beans-3.0.4.RELEASE.jar
org.springframework.context-3.0.4.RELEASE.jar
org.springframework.context.support-3.0.4.RELEASE.jar
org.springframework.core-3.0.4.RELEASE.jar
org.springframework.expression-3.0.4.RELEASE.jar
org.springframework.web-3.0.4.RELEASE.jar
org.springframework.web.servlet-3.0.4.RELEASE.jar
standard.jar
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>LogOutSystemChecking</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- View Resolver Starts -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jspViews/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- View Resolver Starts -->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/UserRegistration.html">
<ref bean="RegCon" /> <!-- Controller-1 Mapping -->
</entry>
</map>
</property>
</bean>
<bean id="RegCon" class="controllers.registerController.RegistrationController"> <!-- Controller-1 Mapping -->
<property name="commandName">
<value>registration</value> <!--form:form commandName="registration" method="post" In UserRegistration.JSP-->
</property>
<property name="commandClass">
<value>formBeans.registerBean.RegistrationBean</value>
</property>
<property name="sessionForm">
<value>false</value>
</property>
<property name="formView">
<value>UserRegistration</value>
</property>
<property name="successView">
<value>UserRegistrationSuccess</value>
</property>
<property name="validator">
<bean class="validatorsPackage.registrationValidator.RegistrationValidations"/> <!-- Validate Page If user Does't enter Username,Password,CompanyAddress -->
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <!-- To show Message If error in a jsp page like Plz enter Username -->
<property name="basename" value="message" />
</bean>
</beans>
RegistrationBean.java--:
package formBeans.registerBean;
public class RegistrationBean {
//--global variable declaration Starts--//
private String name;
private String comAdd;
private String pwd;
private String cpwd;
private char gender;
private int empNumber;
//--global variable declaration Ends--//
//--Getter & Setter Starts--//
public String getComAdd() {
return comAdd;
}
public void setComAdd(String comAdd) {
this.comAdd = comAdd;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getCpwd() {
return cpwd;
}
public void setCpwd(String cpwd) {
this.cpwd = cpwd;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public int getEmpNumber() {
return empNumber;
}
public void setEmpNumber(int empNumber) {
this.empNumber = empNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println("Name--:"+name);
}
//--Getter & Setter Ends--//
public RegistrationBean()
{
// TODO Auto-generated constructor stub
}
} //--Class Ends--//
RegistrationController.java--:
package controllers.registerController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import formBeans.registerBean.RegistrationBean;
public class RegistrationController extends SimpleFormController { //-- Class Starts--//
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception //--onSubmit() Method Starts--//
{
System.out.println("into the doSubmitAction() method.......");
RegistrationBean regBean = (RegistrationBean) command;
System.out.println("studentBea"+regBean.getName());
ModelAndView mv = new ModelAndView(this.getSuccessView());
mv.addObject("regBean", regBean);
return mv;
}//--onSubmit() Method Starts--//
public RegistrationController()
{
// TODO Auto-generated constructor stub
}
} //-- Class Ends --//
UserRegistration.jsp--:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1" isELIgnored="FALSE"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!-- error remove after add Standard.jar -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style>
table, th{
border: 1px solid black;
}
label{
font-family: "Trebuchet MS", Verdana, Halvetica, Arial;
font-size: 12px;
color: blue;
}
.textfield {
width: 250px;
border: 1px solid #AF9D72;
background-color: #F2ECD7;
}
.error {
color: #ff0000;
font-style: italic;
}
.errorblock{
color: #ff0000;
background-color: black;
width:400px;
text-align: center;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SignUp</title>
</head>
<body bgcolor="#DDDDDD">
<form:form commandName="registration" method="post">
<div align="center" style="width:100%; height:100%"> <!-- Div tag ka data center me(meaning of aling) -->
<form:errors path="*" cssClass="errorblock" element="div"/>
<table style="height:250px; width:400px">
<tr>
<th>Heading</th>
<th>Input</th>
</tr>
<tr>
<td align="left"><label>Employee Name:</label></td>
<!--<td>Name:</td>-->
<td align="left"><form:input path="name" class="textfield"/></td> <!-- Insted of NAME Attribute we use PATH in Spring -->
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Employee Number:</label></td>
<!--<td>Name:</td>-->
<td align="left"><form:input path="empNumber" class="textfield"/></td> <!-- Insted of NAME Attribute we use PATH in Spring -->
<td><form:errors path="empNumber" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Company Address:</label></td>
<!--<td>Name:</td>-->
<td align="left"><form:textarea path="comAdd" class="textfield"/></td> <!-- Insted of NAME Attribute we use PATH in Spring -->
<td><form:errors path="comAdd" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Gender:</label></td>
<td align="left">
<form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" />
</td>
<td><form:errors path="gender" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Password:</label></td>
<!--<td>Password:</td>-->
<td align="left"><form:password path="pwd" class="textfield"/></td>
<td><form:errors path="pwd" cssClass="error"/></td>
</tr>
<tr>
<td align="left"><label>Confirm Password:</label></td>
<!--<td>Password:</td>-->
<td align="left"><form:password path="cpwd" class="textfield"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Rigester/Save"/>
</td>
</tr>
</table>
</div>
</form:form>
</body>
</html>

edit method thrown nullpointer Exception delete method is not working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This is a addBook.jsp when click on edit, it throws null pointer exception
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Add booK Data</h2>
<form:form method="POST" action="/sdnext/save.html">
<table>
<tr>
<td><form:label path="bookCode">Book Code:</form:label></td>
<td><form:input path="bookCode" value="${book.bookCode}" readonly="true"/></td>
</tr>
<tr>
<td><form:label path="bookName">Book Name:</form:label></td>
<td><form:input path="bookName" value="${book.bookName}" /></td>
</tr>
<tr>
<td><form:label path="author">Book Author Name:</form:label></td>
<td><form:input path="author" value="${book.author}"/></td>
</tr>
<tr>
<td><form:label path="dateOfArrival">Date Of Arrival:</form:label></td>
<td><form:input path="dateOfArrival" value="${book.dateOfArrival}"/></td>
</tr>
<tr>
<td><form:label path="price">Price Of Book:</form:label></td>
<td><form:input path="price" value="${book.price}"/></td>
</tr>
<tr>
<td><form:label path="rackId">Book Rack Id:</form:label></td>
<td><form:input path="rackId" value="${book.rackId}"/></td>
</tr>
<tr>
<td><form:label path="numberOfBooks">Number of Books:</form:label></td>
<td><form:input path="numberOfBooks" value="${book.numberOfBooks}"/></td>
</tr>
<tr>
<td><form:label path="subjectCode">Book Subject Code:</form:label></td>
<td><form:input path="subjectCode" value="${book.subjectCode}"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
<c:if test="${!empty books}">
<h2>List Books</h2>
<table align="left" border="1">
<tr>
<th>NameOfBook</th>
<th>BookCode</th>
<th>AuthorName</th>
<th>DateOfArrival</th>
<th>PriceOfBook</th>
<th>BookRackId</th>
<th>NumberofBooks</th>
<th>BookSubjectCode</th>
<th>Actions on Row</th>
</tr>
<c:forEach items="${books}" var="book">
<tr>
<td><c:out value="${book.bookName}"/></td>
<td><c:out value="${book.bookCode}"/></td>
<td><c:out value="${book.author}"/></td>
<td><c:out value="${book.dateOfArrival}"/></td>
<td><c:out value="${book.price}"/></td>
<td><c:out value="${book.rackId}"/></td>
<td><c:out value="${book.numberOfBooks}"/></td>
<td><c:out value="${book.subjectCode}"/></td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
after submition exception thrown. because in controller the value of bookCode field is not recieve in bean class object.
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error (Request processing failed; nested exception is java.lang.NullPointerException) that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
com.tcs.controller.BookController.editBook(BookController.java:76)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.29 logs.
This is my Controller class where i gets the value of bookCode field in edit mehod and get method is null;
package com.tcs.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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.springframework.web.servlet.ModelAndView;
import com.tcs.bean.BookBean;
import com.tcs.model.Book;
import com.tcs.service.BookService;
#Controller
public class BookController {
#Autowired
private BookService bookService;
#RequestMapping(method=RequestMethod.POST, value = "/save")
public ModelAndView saveBook(#ModelAttribute("command") BookBean bookBean, BindingResult result) {
Book book = prepareModel(bookBean);
bookService.addBook(book);
return new ModelAndView("redirect:/add.html");
}
#RequestMapping(value="/books", method = RequestMethod.GET)
public ModelAndView listBooks() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("booksList", model);
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addBook(#ModelAttribute("command") BookBean booksBean, BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("addBook", model);
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("index");
}
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView deleteBook(#ModelAttribute("command") BookBean bookBean, BindingResult result) {
System.out.println(bookBean.getBookCode());
bookService.deleteBook(prepareModel(bookBean));
Map<String, Object> model = new HashMap<String, Object>();
model.put("book", null);
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("addBook", model);
}
#RequestMapping(value = "/edit" , method=RequestMethod.GET)
public ModelAndView editBook(#ModelAttribute("command") BookBean bookBean, BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
System.out.println(bookBean.getBookCode());
model.put("book", prepareBooksBean(bookService.getBook(bookBean.getBookCode())));
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("addBook", model);
}
private Book prepareModel(BookBean bookBean){
Book book = new Book();
book.setBookName(bookBean.getBookName());
book.setBookCode(bookBean.getBookCode());
book.setAuthor(bookBean.getAuthor());
book.setDateOfArrival(bookBean.getDateOfArrival());
book.setPrice(bookBean.getPrice());
book.setRackId(bookBean.getRackId());
book.setNumberOfBooks(bookBean.getNumberOfBooks());
book.setSubjectCode(bookBean.getSubjectCode());
return book;
}
private List<BookBean> prepareListofBean(List<Book> books){
List<BookBean> beans = null;
if(books != null && !books.isEmpty()) {
beans = new ArrayList<BookBean>();
BookBean bean = null;
for(Book book : books){
bean = new BookBean();
bean.setBookName(book.getBookName());
bean.setBookCode(book.getBookCode());
bean.setAuthor(book.getAuthor());
bean.setDateOfArrival(book.getDateOfArrival());
bean.setPrice(book.getPrice());
bean.setRackId(book.getRackId());
bean.setNumberOfBooks(book.getNumberOfBooks());
bean.setSubjectCode(book.getSubjectCode());
beans.add(bean);
}
}
return beans;
}
private BookBean prepareBooksBean(Book book){
BookBean bean = new BookBean();
bean.setBookName(book.getBookName());
bean.setBookCode(book.getBookCode());
bean.setAuthor(book.getAuthor());
bean.setDateOfArrival(book.getDateOfArrival());
bean.setPrice(book.getPrice());
bean.setRackId(book.getRackId());
bean.setNumberOfBooks(book.getNumberOfBooks());
bean.setSubjectCode(book.getSubjectCode());
return bean;
}
}
this is a service class of my controller
package com.tcs.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.tcs.dao.BookDao;
import com.tcs.model.Book;
#Service("bookService")
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class BookServiceImpl implements BookService {
#Autowired
private BookDao bookDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addBook(Book book) {
bookDao.addBook(book);
}
public List<Book> listBooks() {
return bookDao.listBooks();
}
public Book getBook(int bookCode) {
return bookDao.getBook(bookCode);
}
public void deleteBook(Book book) {
bookDao.deleteBook(book);
}
}
this is a setting of 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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:resources/database.properties" />
<context:component-scan base-package="com.tcs" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<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.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.tcs.model.Book</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
this is a web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
You edit method
#RequestMapping(value = "/edit" , method=RequestMethod.GET)
public ModelAndView editBook(#ModelAttribute("command") BookBean bookBean,
BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
System.out.println(bookBean.getBookCode()); // bookbean is null
model.put("book", prepareBooksBean(bookService.getBook(bookBean.getBookCode())));
model.put("books", prepareListofBean(bookService.listBooks()));
return new ModelAndView("addBook", model);
}
accepts a BookBean instance. For spring to create this bean for you, it needs to have request parameters that map to the fields of the object. You're making your request through an <a href> anchor.
Edit
The only parameter in the request is id, which doesn't even match the bookCode field name. Spring won't be able to create a bean and will therefore pass null. You can read more about the process here.
We can assume something similar occurs for deleteBook.

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();
}

Categories

Resources