liferay portlet spring mvc form is empty - java

I have a problem. The form submit is empty.
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
private String firstName;
private String middleName;
private String lastName;
private int age;
private String address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
PortletViewController
#Controller
#RequestMapping("VIEW")
public class PortletViewController {
#RenderMapping
public String viewHomePage(RenderRequest request, RenderResponse response) {
return "test/view";
}
#RenderMapping(params = "action=showForm")
public String viewByParameter(Map<String, Object> map) {
Customer customer = new Customer();
map.put("customer", customer);
return "test/form";
}
#RenderMapping(params = "action=success")
public String viewSuccess() {
return "test/success";
}
#ActionMapping(value = "handleCustomer")
public void getCustomerData(#ModelAttribute("customer") Customer customer,
ActionRequest actionRequest, ActionResponse actionResponse,
Model model) {
actionResponse.setRenderParameter("action", "success");
model.addAttribute("successModel", customer);
}
}
form.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL var="submitFormURL" name="handleCustomer"/>
<form:form name="customer" method="post" modelAttribute="customer" action=" <%=submitFormURL.toString() %>">
<br/>
<table style="margin-left:80px">
<tbody>
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td><form:input path="firstName"></form:input></td>
</tr>
<tr>
<td><form:label path="middleName">Middle Name</form:label></td>
<td><form:input path="middleName"></form:input></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input path="lastName"></form:input></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age"></form:input></td>
</tr>
<tr>
<td><form:label path="address">Address</form:label></td>
<td><form:input path="address"></form:input></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit Form">
</td>
</tr>
</tbody>
</table>
</form:form>
success.jsp
<div>
<h3>Form submitted successfully</h3>
</div>
<div>
First Name:
${successModel.firstName}
</div>
<div>
Middle Name:
${successModel.middleName}
</div>
<div>
Last Name:
${successModel.lastName}
</div>
<div>
Age:
${successModel.age}
</div>
<div>
Address:
${successModel.address}
</div>
view.jsp
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL var="renderURL">
<portlet:param name="action" value="showForm"/>
</portlet:renderURL>
<h3> Spring Form Submission Demo</h3>
<br/><br/>
Go to Form Page
web.xml
<?xml version="1.0"?>
<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"
>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-context/portlet-application-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>ViewRendererServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ViewRendererServlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
portlet.xml
<?xml version="1.0"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" version="2.0">
<portlet>
<portlet-name>test</portlet-name>
<display-name>test</display-name>
<portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/spring-context/portlet/test-portlet.xml</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<portlet-info>
<title>test</title>
<short-title>test</short-title>
<keywords>test</keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
<security-role-ref>
<role-name>guest</role-name>
</security-role-ref>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
</portlet-app>
portlet-application-context.xml
<?xml version="1.0"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
>
<context:annotation-config/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
</bean>
</beans>
test-portlet.xml
<?xml version="1.0"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
>
<context:component-scan base-package="test.**" />
</beans>
Can someone help me?
Why is the Customer submit empty?

I found the mistake. In liferay-portlet.xml following must be added.
<requires-namespaced-parameters>false</requires-namespaced-parameters>

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>

SEVERE: Context initialization failed and org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException

I new for spring mvc and jdo and I try to learn I got error of
HTTP ERROR 503
Problem accessing /add. Reason:
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 11 in XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 28; The prefix "mvc" for element "mvc:annotation-driven" is not bound.
my program of spring mvc is placed here:
person.java:
package com.web.project;
import java.util.Date;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
#PersistenceCapable
public class Person {
// ID or key unique variable
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
// String or integer or other variable related to person
#Persistent
private String name ;
#Persistent
private String email;
#Persistent
private Date date;
//getter and setter methods
public void setKey(Key key) {
this.key = key;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setDate(Date date) {
this.date = date;
}
public Key getKey() {
return key;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public Date getDate() {
return date;
}
#Override
public String toString() {
return "Person [key=" + key + ", name=" + name + ", email=" + email
+ ", date=" + date + "]";
}
}
personalcontroller.java:
package com.web.project;
import java.util.Date;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import com.web.project.Person;
import org.springframework.ui.ModelMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class Personalcontroller {
PersistenceManager pm = PMF.get().getPersistenceManager();
List<Person> results = null;
#RequestMapping(value="/add")
public ModelAndView add(HttpServletRequest request, ModelMap model)
{
System.out.println("inside the add service");
String name = request.getParameter("name");
String email = request.getParameter("email");
try
{
Person p = new Person();
p.setName(name);
p.setEmail(email);
p.setDate(new Date());
pm.makePersistent(p);
}
finally
{
pm.close();
}
return new ModelAndView("redirect:link");
}
#RequestMapping(value="/update")
public ModelAndView update(HttpServletRequest request, ModelMap model)
{
String name = request.getParameter("name");
String email = request.getParameter("email");
String key = request.getParameter("key");
try
{
Person p = pm.getObjectById(Person.class, key);
p.setName(name);
p.setEmail(email);
p.setDate(new Date());
}
catch (Exception e)
{
pm.close();
}
return new ModelAndView("redirect:link");
}
#RequestMapping(value = "/delete/{key}")
public ModelAndView delete(#PathVariable String key, HttpServletRequest request, ModelMap model) {
try {
Person p = pm.getObjectById(Person.class, key);
pm.deletePersistent(p);
} finally {
pm.close();
}
return new ModelAndView("redirect:list");
}
#SuppressWarnings("unchecked")
#RequestMapping(value = "/list", method = RequestMethod.GET)
public String listPerson(ModelMap model) {
Query q = pm.newQuery(Person.class);
q.setOrdering("date desc");
try {
results = (List<Person>) q.execute();
if (results.isEmpty()) {
model.addAttribute("list", null);
} else {
model.addAttribute("list", results);
}
} finally {
q.closeAll();
pm.close();
}
return "list";
}
}
PMF.java:
package com.web.project;
import javax.jdo.*;
public final class PMF {
private static final PersistenceManagerFactory pmfInstance = JDOHelper.getPersistenceManagerFactory("transactions-optional");
private PMF(){
}
public static PersistenceManagerFactory get()
{
return pmfInstance;
}
}
personal.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="com.google.appengine.api.datastore.KeyFactory, java.util.Date, java.util.List;" %>
<%# page import="com.web.project.Person" %>
<!DOCTYPE html>
<html>
<body>
<h1>GAE + Spring 3 MVC REST + CRUD Example with JDO</h1>
Function : Add Person
<hr />
<h2>All Person</h2>
<table border="1">
<thead>
<tr>
<td>Name</td>
<td>Email</td>
<td>Created Date</td>
<td>Action</td>
</tr>
</thead>
<%
if(request.getAttribute("list")!=null){
List<Person> person = (List<Person>) request.getAttribute("list");
if(!person.isEmpty()){
for(Person p : person){
%>
<tr>
<td><%=p.getName() %></td>
<td><%=p.getEmail() %></td>
<td><%=p.getDate() %></td>
<td>Update |
<a href="delete/<%=KeyFactory.keyToString(p.getKey()) %>">
Delete</a>
</td>
</tr>
<%
}
}
}
%>
</table>
</body>
</html>
add.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<h1>Add Person</h1>
<form method="GET" action="/add">
<table>
<tr>
<td>UserName :</td>
<td><input type="text" style="width: 185px;" maxlength="30"
name="name" id="name" /></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" style="width: 185px;" maxlength="30"
name="email" id="email" /></td>
</tr>
</table>
<input type="submit" class="save" title="Save" value="Save" />
</form>
</body>
</html>
update.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# page import="com.web.project.Person" %>
<%# page import="com.google.appengine.api.datastore.KeyFactory" %>
<html>
<body>
<h1>Update Customer</h1>
<%
Person person = new Person();
if(request.getAttribute("person")!=null){
person = (Person)request.getAttribute("person");
}
%>
<form method="post" action="../update" >
<input type="hidden" name="key" id="key"
value="<%=KeyFactory.keyToString(person.getKey()) %>" />
<table>
<tr>
<td>
UserName :
</td>
<td>
<input type="text" style="width: 185px;"
maxlength="30" name="name" id="name"
value="<%=person.getName() %>" />
</td>
</tr>
<tr>
<td>
Email :
</td>
<td>
<input type="text" style="width: 185px;"
maxlength="30" name="email" id="email"
value="<%=person.getEmail() %>" />
</td>
</tr>
</table>
<input type="submit" class="update" title="Update" value="Update" />
</form>
</body>
</html>
During excution
Error:
SEVERE: Context initialization failed
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 11 in XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 29; The prefix "mvc" for element "mvc:annotation-driven" is not bound.
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:398)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:335)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129)
at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:643)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:606)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:657)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:525)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:466)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:440)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:263)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.google.appengine.tools.development.JettyContainerService.startContainer(JettyContainerService.java:255)
at com.google.appengine.tools.development.AbstractContainerService.startup(AbstractContainerService.java:288)
at com.google.appengine.tools.development.AutomaticInstanceHolder.startUp(AutomaticInstanceHolder.java:26)
at com.google.appengine.tools.development.AbstractModule.startup(AbstractModule.java:87)
at com.google.appengine.tools.development.Modules.startup(Modules.java:105)
at com.google.appengine.tools.development.DevAppServerImpl.doStart(DevAppServerImpl.java:258)
at com.google.appengine.tools.development.DevAppServerImpl.access$000(DevAppServerImpl.java:47)
at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:213)
at com.google.appengine.tools.development.DevAppServerImpl$1.run(DevAppServerImpl.java:211)
at java.security.AccessController.doPrivileged(Native Method)
at com.google.appengine.tools.development.DevAppServerImpl.start(DevAppServerImpl.java:211)
at com.google.appengine.tools.development.DevAppServerMain$StartAction.apply(DevAppServerMain.java:277)
at com.google.appengine.tools.util.Parser$ParseResult.applyArgs(Parser.java:48)
at com.google.appengine.tools.development.DevAppServerMain.run(DevAppServerMain.java:219)
at com.google.appengine.tools.development.DevAppServerMain.main(DevAppServerMain.java:210)
Caused by: org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 29; The prefix "mvc" for element "mvc:annotation-driven" is not bound.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:441)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:289)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2786)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:347)
at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:76)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadDocument(XmlBeanDefinitionReader.java:428)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
... 46 more
please check your context xml. I think you have not defined schema for "mvc".
eg:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
check wether your project is building or not...also check out that Build Automatically is checked/selected under Project menu or not.
The problem lies in the file called /WEB-INF/mvc-dispatcher-servlet.xml
It seems that you have tried to use xml namespaces and you did not define them correctly.
Make sure that if you use an element prefixed with mvc that you have the line with xmlns:mvc="http://www.springframework.org/schema/mvc" in your namespace declaration like in the above example. You wil also need the schemaLocation like in the example below.
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns="http://www.springframework.org/schema/beans"
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">
<mvc:interceptors>
</mvc:interceptors>
</beans>
Following is the schema that I use for spring-mvc applications. I faced the same issue because I had missed out on adding the spring-mvc schema.
<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.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">
For more information on the schemas to use refer to this link:
https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/xsd-configuration.html

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