Hibernate Validator #NotNull not working properly - java

I am trying to make simple validation form using Hibernate Validator. I have two fields in my Customer class, and i want one of them to be required (lastName).
The point is that even when im not filling this field I am not getting error message and BindingResult does not contain any errors. Is there anything im missing in my code?
Here is my Customer class snippet.
public class Customer {
private String firstName;
#NotNull(message = "is required")
#Size(min = 1, message = "is required")
private String lastName;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Here is Controller
#Controller
#RequestMapping("/customer")
public class CustomerController {
//adding new customer to model
#RequestMapping("/showForm")
public String showForm(Model theModel){
theModel.addAttribute("customer", new Customer());
return "customer-form";
}
//Validating passed customer attribute/object
//Biding result object holds validation results
#RequestMapping("/processForm")
public String processForm(
#Valid #ModelAttribute("customer") Customer theCustomer, BindingResult theBindingResult) {
if (theBindingResult.hasErrors()){
return "customer-form";
}
return "customer-confirmation";
}
}
EDIT: form code:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Customer Registration Form</title>
</head>
<body>
<style>
.error{color: red}
</style>
<i> Fill out the form. Asteriks (*) means required. </i>
<br><br>
<form:form action="processForm" modelAttribute="customer">
First name: <form:input path="firstName" />
<br><br>
Last name (*): <form:input path="lastName"/>
<form:errors path="lastName" cssClass="error" />
<input type="submit" value="Submit"/>
</form:form>
</body>
</html>
EDIT 2:
I added to classpath validation-api.jar (contains the abstract API and the annotation scanner).
Also inserted #InitBinnder just to make sure that empty form field will always be null not empty String.
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
}
But it still seems that those annotations never get triggered at all
EDIT 3: After calling validator on Entity I am getting error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.NoProviderFoundException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
although i have added it to classpath
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
validator.validate(theCustomer);
EDIT 4: Adding Spring Configuration files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>mvc-validation-demo</display-name>
<!-- Spring MVC Configs -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-validation-demo.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
mvc-validation-demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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/">
<context:component-scan base-package="com.lobo.mvc" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
EDIT 5: According to what #eis said i added to my mvc-validation-demo.xml:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalVa‌​lidatorFactoryBean"/‌​>
And i also have Hibernate Validator in my classpath:
Classpath
but the error still remains

Deleteing .idea , clearing cache and new configuration did the job for me. It seems that somehow it didn't saw hibernate-validator.jar.
Thank you to everyone who contributed.

Related

I am getting this error "Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister"?

I am trying to make a spring-hibernate application but I am getting this error
Request processing failed; nested exception is org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
I know this error comes when it tries to find getters and setters and couldn't get them. But i checked my getters and setters properly they are correct.
Please help me with this.
My Structure is like this
And code is
Employee.java
package com.wipro.config;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="empdata")
public class Employee {
#Id
private String empname;
#Column(name="designation",length=15)
private String designation;
#Column(name="email",length=25)
private String email;
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
EmployeeDao.java
package com.wipro.config;
import java.io.File;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmployeeDao {
private SessionFactory factory;
private Session session;
private Transaction t;
public EmployeeDao() {
}
public void saveData(Employee e) {
factory =new Configuration().configure(new File("F:/Wipro teachings/springg/crud/src/main/java/com/wipro/config/hibernate.cfg.xml")).buildSessionFactory();
session=factory.openSession();
t=session.beginTransaction();
session.save(e);
t.commit();
}
}
ControllerDemo.java
package com.wipro.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wipro.config.Employee;
import com.wipro.config.EmployeeDao;
#Controller
public class ControllerDemo {
private ApplicationContext conn;
public ControllerDemo() {
}
#RequestMapping("/home")
public String view1() {
return "home";
}
#RequestMapping("/register")
public String view2(Model m) {
conn=new ClassPathXmlApplicationContext("ApplicationContext.xml");
Employee emp=conn.getBean("info",Employee.class);
m.addAttribute("bean",emp);
return "register";
}
#RequestMapping("/store")
public String view3(#ModelAttribute("bean") Employee e,Model m) {
conn=new ClassPathXmlApplicationContext("ApplicationContext.xml");
EmployeeDao obj=conn.getBean("dao",EmployeeDao.class);
obj.saveData(e);
m.addAttribute("msg","Record Inserted Successfully");
return "register";
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">Musu</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#Localhost:1521:orcl</property>
<property name="hibernate.connection.username">sys as sysdba</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle8iDialect</property>
<property name="dialect">org.hibernate.dialect.Oracle8iDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.wipro.config.Employee"/>
</session-factory>
</hibernate-configuration>
ApplicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="info" class="com.wipro.config.Employee"></bean>
<bean id="dao" class="com.wipro.config.EmployeeDao"></bean>
</beans>
home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Register
</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" %>
<%#page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Register Page</h1>
<form:form action="store" method="post" modelAttribute="bean">
Enter name=<form:input path="empname"/><br><br>
Enter designation=<form:input path="designation"/><br><br>
Enter email=<form:input path="email"/><br><br>
<input type="submit" value="register">
</form:form>
<br>
<h2>${msg}</h2>
</body>
</html>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns: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">
<context:component-scan base-package="com.wipro"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean id="vr" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<html>
<body>
<h2>Hello World!</h2>
Home
</body>
</html>
I solved this issue by adding a no argument constractor. If you are using Lombok, you only need to add #NoArgsConstructor annotation:
#AllArgsConstructor
#NoArgsConstructor
#Getter
#ToString
#EqualsAndHashCode
public class User {
private Long userId;
private String shortName;
}

Spring mvc throwing exception- IllegalStateException: Neither BindingResult nor plain target object for bean , when using form tld in jsp page

When i use plain html in jsp page , then app works fine , as i add form tag in jsp , it gives the exception , i have pasted my code and exception here , please help me out .i am not able able to resolve this and stuck from 3 days now. Whats going wrong here
my dispatcher-servlet :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven />
<context:component-scan
base-package="com.shweta.*" />
<mvc:default-servlet-handler />
<mvc:view-controller path="/" view-name="index"/>
<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>
</beans>
my 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>SpringMVCForm</display-name>
<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>/</url-pattern>
</servlet-mapping>
</web-app>
my Controller class:
package com.shweta.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
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.servlet.ModelAndView;
import com.shweta.model.Employee;
import com.shweta.model.Test;
#Controller
//#ControllerAdvice
#RequestMapping("/employee")
public class EmployeeController {
#RequestMapping(value="/submitForm", method=RequestMethod.POST)
public String formSubmission(#ModelAttribute("employee") Employee employee,BindingResult bindingResult)
{
System.out.println("entered in #RequestMapping");
System.out.println("printing employee from modelattribute");
System.out.println(employee.getEmail());
System.out.println(employee.getFirstName());
System.out.println(employee.getLastName());
System.out.println(employee.getSalary());
//modelMap.addAttribute("employee", employee);
return "EmployeeWelcome";
}
}
my employee jsp page :
<%# 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">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee page</title>
</head>
<body>
<h1>${msg}</h1>
<%-- <form:form action="employee/submitForm" method="post" > --%>
<form:form action="${pageContext.request.contextPath}/employee/submitForm" method="post" modelAttribute="employee">
<!-- <div>
First name:
<input type="text" name="firstName">
</div> -->
<div>
First name:
<form:input path="firstName"/>
</div>
<div>
Last name:
<input type="text" name="lastName">
</div>
<div>
E-mail:
<input type="email" name="email">
</div>
<div>
Salary:
<input type="text" name="salary">
</div>
<div class="button">
<button type="submit">Submit</button>
</div>
</form:form>
</body>
</html>
my employee model class
package com.shweta.model;
public class Employee {
String email;
String firstName;
String lastName;
Address address;
long salary;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}
HTTP Status 500 – Internal Server Error
Type Exception Report
Message An exception occurred processing JSP page /WEB-INF/jspPages/EmployeeForm.jsp at line 22
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jspPages/EmployeeForm.jsp at line 22
19: </div> -->
20: <div>
21: First name:
22: <form:input path="firstName"/>
23: </div>
24: <div>
25: Last name:
Exception snippet
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:613)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:505)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'employee' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:177)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:163)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:148)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:138)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:121)
org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:459)
org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:356)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:86)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:83)
org.apache.jsp.WEB_002dINF.jspPages.EmployeeForm_jsp._jspx_meth_form_005finput_005f0(EmployeeForm_jsp.java:214)
org.apache.jsp.WEB_002dINF.jspPages.EmployeeForm_jsp._jspx_meth_form_005fform_005f0(EmployeeForm_jsp.java:158)
org.apache.jsp.WEB_002dINF.jspPages.EmployeeForm_jsp._jspService(EmployeeForm_jsp.java:104)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/7.0.94
You have to put bean into model before rendering the jsp.
For example, you need to declare a method below at EmployeeController and access the jsp through the method.
#RequestMapping("index")
public String index(Model model) {
model.addAttribute("employee", new Employee());
return "EmployeeForm";
}
Similar question: Neither BindingResult nor plain target object for bean name available as request attribute
You have not put a bean with the name "employee" into the model. You should inject one before rendering the view. Add a method to your controller to do that.

Getting java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute [duplicate]

This question already has answers here:
What causes "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute"?
(7 answers)
Closed 6 years ago.
Getting java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute error in spring 3.0. How can I resolve it?
Below is the code for the files
index.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"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form handling</title>
</head>
<body>
<form:form action="/emp/showEmployee" method="POST">
<table>
<tbody>
<tr><td>Employee Name: </td><td><form:input path="empName"/></td></tr>
<tr><td>Employee Skill: </td><td><form:input path="empSkill"/></td></tr>
<tr><td><input type="submit" value = "Submit"></td></tr>
</tbody>
</table>
</form:form>
</body>
</html>
web.xml
<web-app 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"
version="3.0">
<!-- Processes application requests -->
<servlet>
<servlet-name>emp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>emp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/context-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
context-config.xml
<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">
EmployeeController.java
package com.springmvctut.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.springmvctut.bean.EmployeeForm;
#Controller
public class EmployeeController {
#RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView employee() {
return new ModelAndView("employeeForm", "command", new EmployeeForm());
}
#RequestMapping(value = "/showEmployee", method = RequestMethod.POST)
public String showEmployee(#ModelAttribute("SpringWeb")EmployeeForm employeeForm, ModelMap modelMap){
modelMap.addAttribute("name", employeeForm.getEmpName());
modelMap.addAttribute("skill", employeeForm.getEmpSkill());
return "employeedetails";
}
}
EmployeeForm.java(Bean class)
package com.springmvctut.bean;
public class EmployeeForm {
private String empName;
private String empSkill;
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpSkill() {
return empSkill;
}
public void setEmpSkill(String empSkill) {
this.empSkill = empSkill;
}
public String toString(){
return "Employee name-"+empName+" Employee Skill-"+empSkill;
}
}
add this to your form element :
<form:form action="/emp/showEmployee" method="POST" modelAttribute="employee">
update your controller
#ModelAttribute
public void addEmplployeeTomModel(Model model){
model.addAttribute("employee",new EmployeeForm())
}
#RequestMapping(value = "/showEmployee", method = RequestMethod.POST)
public String showEmployee(#ModelAttribute("employee")EmployeeForm employeeForm, ModelMap modelMap){
modelMap.addAttribute("name", employeeForm.getEmpName());
modelMap.addAttribute("skill", employeeForm.getEmpSkill());
return "employeedetails";
}

Spring Mvc Form Post HTTP Status 400 The request sent by the client was syntactically incorrect

I have been trying to add users to mysql database with form but i get:
HTTP Status 400 The request sent by the client was syntactically incorrect.
my codes
User.java
public class User {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int id;
private String name;
}
UserDAO.java
public class UserDAO {
public void insert(User u) throws SQLException, ClassNotFoundException {
Connection conn=Database.newDatabase().getConnection();
PreparedStatement ps=conn.prepareStatement("insert into user values (?)");
ps.setString(1,u.getName());
ps.execute();
ps.close();
conn.close();
}
public List<User> getUsers() throws SQLException, ClassNotFoundException {
List<User> list=new ArrayList<User>();
Connection conn=Database.newDatabase().getConnection();
PreparedStatement ps=conn.prepareStatement("select *from user");
ResultSet rs=ps.executeQuery();
while (rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
list.add(u);
}
rs.close();
ps.close();
conn.close();
return list;
}
}
UserController.java
package com.springapp.mvc.Controller;
import java.sql.SQLException;
import com.springapp.mvc.Model.User;
import com.springapp.mvc.Service.UserDAO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class UserController {
#RequestMapping(value = "user",method = RequestMethod.GET)
public ModelAndView getUser() throws ClassNotFoundException, SQLException {
UserDAO udao=new UserDAO();
ModelAndView mav=new ModelAndView();
mav.setViewName("userControl");
mav.addObject("userList",udao.getUsers());
return mav;
}
#RequestMapping(value = "save", method = RequestMethod.POST)
public String createUser(#ModelAttribute(value = "user") User u) throws SQLException, ClassNotFoundException {
UserDAO udao=new UserDAO();
udao.insert(u);
return "redirect:user.html" ;
}
}
userControl.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>User</title>
</head>
<body>
<h1>
Users
</h1>
<form:form action="save.html" method="post" commandName="user">
<input type="hidden" name="id">
<label for="name">User Name</label>
<input type="text" id="name" name="name"/>
<input type="submit" value="Submit"/>
</form:form>
<table border="1">
<c:forEach var="user" items="${userList}">
<tr>
<td>${user.name}</td><td>${user.id}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
web.xml
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
</web-app>
mvc-dispatcher-servlet.xml
<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"
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">
<context:component-scan base-package="com.springapp.mvc.Controller,com.springapp.mvc.Service"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
I assume the problem is in your JSP at this line:
<input type="hidden" name="id">
Your id has no value, so there will be a NumberFormatException when trying to convert an empty string to an int.
#RequestMapping(value = "save", method = RequestMethod.POST)
I think "save.html" should be changed to just "save".
Change
<form:form action="save.html" method="post" commandName="user">
use:
<form:form action="save" method="post" commandName="user">
Because #RequestMapping value is url format.
Make changes at Controller:
#RequestMapping(value = "save", method = RequestMethod.POST)
public String createUser(#ModelAttribute(value = "user") User u) throws SQLException, ClassNotFoundException {
UserDAO udao=new UserDAO();
udao.insert(u);
return "redirect:user.html" ;
Return View Name only not an extension:
return "redirect:user" ;

How to add entry to MS SQL table?

I have a task that must keep data in MS SQL server. That is like simple registration form. I have to enter name, last name, address, and birthday and press submit button. After that the inputting data should be save in database. I don't know how to make it. Here is my code:
JSP PAGE:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!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 Test Project</title>
</head>
<body>
Customer List
<h:form>
<h1>Add person</h1>
<p>Please fill in all fields and click Submit</p>
<label id="firstNameLabel">First name</label>
<input id="inputFirstName" value="${customerBean.firstName}"/>
<label id="lastNameLabel">Last name</label>
<input id="inputLastName" value="${customerBean.lastName}"/>
<label id="nirthdayLabel">Birthday name</label>
<input id="inputBirthday" value="${customerBean.birthday}"/>
<label id="addressLabel">Address name</label>
<input id="inputAddress" value="${customerBean.address}"/>
<button id="addAddPerson" value="#{customerBean., hsr1)">Add new person</button>
</h:panelGrid>
</h:form>
</body>
</html>
Another JSP page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Customer List</title>
</head>
<body>
<h1>Customer List</h1>
<table border="1">
<th>First Name</th><th>Last Name</th><th>Birthday</th><th>Address</th>
<c:forEach items="${customerList}" var="customer">
<tr>
<td>${customer.firstName}</td><td>${customer.lastName}</td>
<td>${customer.birthday}</td><td>${customer.address}</td>
</tr>
</c:forEach>
</table>
Add new person
Home
</body>
</html>
Spring bean 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-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">
<!--bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /-->
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
</beans>
More 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-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">
<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" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<bean name="customerController"
class="Controller.CustomerController"/>
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<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>
Hibernate configuration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost\TARAS-PC\SQLEXPRESS:1433;databaseName=Test</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">test</property>
<!--Add by myself-->
<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
<mapping resource="Model/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Java controller:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import Model.Customer;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
*
* #author Taras
*/
public class CustomerController implements Controller{
#Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
ModelAndView mv = new ModelAndView("customerList");
List<Customer> customerList;
try{
//import from package Util
Session session = Util.HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
customerList = session.createQuery("from Customer").list();
// customerList.add(new Customer(new Customer().getFirstName(), new Customer().getLastName(),
// new Customer().getAddress(), new Customer().getBirthday()));
mv.addObject("customerList", customerList);
session.getTransaction().commit();
}
catch (Exception e){
e.printStackTrace();
}
//customerList.add(new Customer("ds", "sf", "sfs", "sf"));
return mv;
}
}
Generated java class:
package Model;
// Generated Mar 4, 2014 11:21:14 PM by Hibernate Tools 3.2.1.GA
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Test generated by hbm2java
*/
#Entity
#ManagedBean (name = "customerBean")
#Table(name="Test"
,schema="dbo"
,catalog="Test"
)
public class Customer implements java.io.Serializable {
private int id;
private String firstName;
private String lastName;
private String address;
private String birthday;
public Customer() {
}
public Customer(String firstName, String lastName, String address, String birthday) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.birthday = birthday;
}
#Id
#Column(name="ID", unique=true, nullable=false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="FirstName")
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="LastName")
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name="Address")
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name="Birthday")
public String getBirthday() {
return this.birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
// public String addEntry(){
// if (firstName != null && lastName != null && birthday != null && address != null)
// return "";
// else
// return "";
// }
}

Categories

Resources