validation form using Spring 3 - spring

i'm creating validation form on Spring 3, My problem is, that i saw a lot of examples with validation form. I even created one. but my form passing "result.hasErrors()" method, even when there are errors.
My code is:
Controller:
package com.esb.sso;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.validation.BindingResult;
import java.util.Map;
import javax.validation.Valid;
import com.esb.sso.form.LoginForm;
import javax.servlet.http.HttpServletRequest;
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping(value = "/")
public class HomeController {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
return "home";
}
#RequestMapping(method = RequestMethod.POST)
public String validation(#Valid LoginForm loginForm, BindingResult result,
Map model) throws IOException {
logger.info("Login POST var");
logger.info(loginForm.getLogin());
logger.info(loginForm.getPassword());
if (result.hasErrors()) {
logger.info("error");
return "home";
}
model.put("loginForm", loginForm);
return "logged";
}
}
Validator:
package com.esb.sso.form;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class LoginForm {
#NotNull(message = "notNull")
#Size(min=1, max=50, message="mote charters")
private String login;
#NotNull(message = "notNull")
#Size(min=1, max=50, message="mote charters")
private String password;
public void setLogin(String login){
this.login = login;
}
public String getLogin(){
return login;
}
public void setPassword(String password){
this.password = password;
}
public String getPassword(){
return password;
}
}
View:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Home</title>
</head>
<body>
Autoryzacja!!!
<form:form action="" commandName="loginForm">
<table>
<tr>
<td>User Name:<FONT color="red"><form:errors path="login" /></FONT></td>
</tr>
<tr>
<td><form:input path="login" /></td>
</tr>
<tr>
<td>Password:<FONT color="red"><form:errors path="password" /></FONT></td>
</tr>
<tr>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
servlet-context:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.esb.sso" />
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="/WEB-INF/messages" />
</beans:bean>
</beans:beans>
and messages.properties:
NotNull.loginForm.login=must not be blank.
NotNull.loginForm.password=must not be blank.
Size.loginForm.login=Login size must be between 1 and 50 charters.
Size.loginForm.password=Password size must be between 1 and 50 charters.
I don't know where is the problem
Coul'd enybody help me ?

Assuming copy paste error in HomeController-get method of the "/" mapping method.
To answer your question - You must specify the LoginForm object as model attribute in order to bind validations on it with BindingResult. Below is the correct code
public String validation((#ModelAttribute("loginForm") #Valid LoginForm loginForm, BindingResult result,
Map model) throws IOException {
For reference see the documentation

Related

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute

When try to run spring sample application using maven i have got the exception mentioned.
Here is my program
Firstpage1.jsp [present in Webcontent]
<html>
<head>
<title>Finacle data retriever</title>
</head>
<body>
<h2>Enter the configuration details</h2>
<form:form method="POST" action="/formexample/Configgen" commandName="configbean">
<table>
<tr>
<td><form:label path="tnu">Total number of Users</form:label></td>
<td><form:input path="tnu" /></td>
</tr>
<tr>
<td><form:label path="cnu">Concurrent number of Users</form:label></td>
<td><form:input path="cnu" /></td>
</tr>
<tr>
<td><form:label path="kat">Keep Alive Timeout</form:label></td>
<td><form:input path="kat" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp [ Webcontent/WEB-INF/jsp]
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Result page</title>
</head>
<body>
<h2> Result page information</h2>
<table>
<tr>
<td>Total Number of users</td>
<td>${congibean.tnc}</td>
</tr>
<tr>
<td>Concurrent Number of users</td>
<td>${congibean.cnu}</td>
</tr>
<tr>
<td>Keep alive timeout</td>
<td>${congibean.kat}</td>
</tr>
</table>
</body>
</html>
**spring dependencies are present in 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_2_5.xsd"
id="WebApp_ID" version="2.5">
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/spring-form.tld</taglib-uri>
<taglib-location>spring-form.tld</taglib-location>
</taglib>
</jsp-config>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/formex-servlet.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>Firstpage1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>formex</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>formex</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
formex-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"
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-4.2.xsd">
<context:component-scan base-package="formexamplepack1"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
formexamplepack1 - package
configbean.java
package formexamplepack1;
public class configbean {
private int tuc;
private int cnu;
private int kat;
public int getTuc() {
return tuc;
}
public void setTuc(int tuc) {
this.tuc = tuc;
}
public int getCnu() {
return cnu;
}
public void setCnu(int cnu) {
this.cnu = cnu;
}
public int getKat() {
return kat;
}
public void setKat(int kat) {
this.kat = kat;
}
}
ConfigurationController.java
package formexamplepack1;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
#Controller
#RequestMapping(value = "/Configgen")
public class ConfigurationController {
#RequestMapping(method=RequestMethod.GET)
public String showform(ModelMap model) {
configbean configbean=new configbean();
model.addAttribute("configbean",configbean);
return "Firstpage";
}
#RequestMapping(method=RequestMethod.POST)
public String getdetails(#ModelAttribute("configbean")configbean configbean,ModelMap model,BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
}
Help me in resolving the below exception. I have gone through all the answers but not able to figure out. Using java 1.8 and spring jars latest [4.2.6]
tomcat- 7.0.68
Below is the exception
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:556)
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:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'configbean' available as request attribute
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005flabel_005f0(Firstpage1_jsp.java:216)
org.apache.jsp.Firstpage1_jsp._jspx_meth_form_005fform_005f0(Firstpage1_jsp.java:152)
org.apache.jsp.Firstpage1_jsp._jspService(Firstpage1_jsp.java:105)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
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:790)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Try:
without ModelAttribute annotation
Binding Result direct after the command object
like:
#RequestMapping(method=RequestMethod.POST)
public String getdetails(configbean configbean, BindingResult bindingResult){
model.addAttribute("tnu", configbean.getTuc());
model.addAttribute("cnu", configbean.getCnu());
model.addAttribute("kat",configbean.getKat());
return "result";
}
you are trying to use ${congibean.tnc} in your result.jsp file , but you are not passing it as a model attribute . Instead you are trying to pass "tnu","cnu" and "kat" .
As a result it's giving you a jasper exception , as the compiler is unable to find any model attribute called "configbean" .
To solve this either pass only "configBean" as your model Attribute in the getdetails() method , or change your result.jsp file to use only "${tnc}", "${cnu}" and "${kat}"

Spring4 MVC form validation result.hasErrors() is always false

I'm using validation-api-1.1.0.Final.jar to valid form input in Spring 4 MVC. But I'm stuck in here, the result.hasErrors() seems always false(it means #Valid doesn't work properly). I followed this guideValidating Form Input, but that guide validating form input using Spring Boot. I'm using Tomcat 8 instead of using Spring Boot. I've search a lot about this, but the issue still existed.
Seaking for help.
Thanks!
Project Structure:
UserController.java
package com.ro.user.controller;
import com.ro.user.model.UserModel;
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 javax.validation.Valid;
#Controller
public class UserController {
#RequestMapping(value = "/user", method = RequestMethod.GET)
public UserModel user(Model model) {
UserModel userModel = new UserModel();
model.addAttribute("userModel", userModel);
return userModel;
}
#RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public String userLogin(#Valid #ModelAttribute("userModel") UserModel userModel, BindingResult bindingResult) {
System.out.println("Before: bindingResult.hasErrors()");
if (bindingResult.hasErrors()) {
System.out.println("After: bindingResult.hasErrors()");
return "user";
}
return "result";
}
}
UserModel.java
package com.ro.user.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class UserModel {
#NotNull
#Size(min = 6, max = 12)
private String username;
#Size(min = 8, max = 16)
private String password;
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;
}
}
user.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>Spring MVC Form Handling</title>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body>
<h2>User Information</h2>
<form:form action="userLogin" modelAttribute="userModel" method="POST">
<form:errors path="*" cssClass="errorblock" element="div"/>
<table>
<tr>
<td><form:label path="username">Username:</form:label></td>
<td><form:input path="username"/></td>
<td><form:errors path="username" cssClass="error"/></td>
</tr>
<tr>
<td><form:label path="password">Password:</form:label></td>
<td><form:input path="password"/></td>
<td><form:errors path="username" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="3.1">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>UserLogin</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>UserLogin</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
UserLogin-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-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.ro.user.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
<property name="basename" value="com.ro.user.model.error"/>
</bean>
</beans>
This issue is caused by lack of the dependency of Hibernate Validator. It is supposed to add all Jars in a folder named required to project's lib(download zip from the official website and unzip it, you will see this folder). Not just the hibernate-validator.jar and validation-api.jar.
I guess you've created a custom HandlerAdapter, then you need to initialize the webBinding manually.
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator"/>
</bean>
</property>
</bean>
I had the same issue. I resolved it by changing hibernate validator version. In my case, it worked with version 6.2 and it didn't work with version 7.

Maven Spring WebApp HTTP Status 404

Try to run student_list.jsp and after running a I got HTTP Status 404.
Here I send photo of my maven project which is set up in Netbeans and the codes. Please for check if everything is set up right. I am the beginner in Spring.
Thanks
Code:
student_list.jsp
<%#page import="java.util.List"%>
<%#page import="cz.webapp.student.entity.Student"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="s" uri="http://www.springframework.org/tags"%>
<div>
<h2>List of Persons</h2>
<table title="List Of Persons" border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<%
List<Student> studentList = (List)request.getAttribute("students");
for(Student student: studentList){
out.println("<tr>");
out.println("<td>" + student.getId() + "</td>");
out.println("<td>" + student.getName() + "</td>");
out.println("<td>" + student.getAge() + "</td>");
out.println("</tr>");
}
%>
</table>
</div>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>StudentWebApp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>StudentWebApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
StudentWebApp-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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="cz.webapp.student" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
StudentController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cz.webapp.student.controllers;
import cz.webapp.student.entity.Student;
import cz.webapp.student.service.StudentService;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import org.springframework.web.bind.annotation.RequestParam;
/**
*
* #author Jenda
*/
#Controller
public class StudentController {
#Autowired
StudentService studentServiceImpl;
#RequestMapping(value="/students", method=GET)
public String showAllStudent(Map<String, Object> model){
List<Student> studentList = studentServiceImpl.findAll();
model.put("students", studentList);
return "student_list";
}
}
I THINK I may have found a problem. In your servlet.xml file, your base package seems wrong. Try this: <context:component-scan base-package="cz.webapp.student.*" />
Because I think Spring is looking for a package called cz.webapp.student when you have your package set to cz.webapp.student.controllers
There are a lot of causes for a 404 error and having a wrong base package is one of them, so I'm not exactly certain if this will fix it, but it's a good start.

How to fix "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'customer' available as request attribute"?

I'm trying to use Spring Validation with annotations and i keep encountering the same exception:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'customer' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:178)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
at org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
Truncated. see log file for complete stacktrace
I've looked at several tutorials and double checked everything i can think of to. I'm not sure where my problem is. The exception happens anytime the webpage is loaded. Any help would be appreciated.
spring-mvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="controllers"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property value="/" name="prefix"></property>
</bean>
</beans>
addCustomer.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>Add Customer</title>
</head>
<body>
<form:form action="addCustForm" method="POST" commandName="customer" modelAttribute="customer">
<table border="2">
<tr><td><form:label path="fname">Customer First Name: </form:label></td><td><form:input path="fname" id="fname"/><form:errors path="fname" cssClass="error"/> </td></tr>
<tr><td><form:label path="lname">Customer Last Name: </form:label></td><td><form:input path="lname" id="lname"/><form:errors path="lname" cssClass="error"/> </td></tr>
<tr><td><form:label path="phone">Customer Phone Number: </form:label></td><td><form:input path="phone" id="phone"/><form:errors path="phone" cssClass="error"/> </td></tr>
<tr><td><form:label path="address">Customer Address: </form:label></td><td><form:input path="address" id="address"/><form:errors path="address" cssClass="error"/> </td></tr>
<tr><td><form:label path="email">Customer E-Mail: </form:label></td><td><form:input path="email" id="email"/><form:errors path="email" cssClass="error"/> </td></tr>
</table>
<input type="submit" value="Submit Customer Info"/>
</form:form>
</body>
</html>
AddCustomerController.java
package controllers;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import dao.Customer;
#Controller
#RequestMapping("/addCustForm")
public class AddCustomerController {
#RequestMapping(method=RequestMethod.POST)
public String addCustomer(#Valid Customer customer, BindingResult result, ModelMap map, HttpServletRequest request) throws Exception{
if(result.hasErrors()){
return "addCustomer.jsp";
}
map.addAttribute("message",customer.getFname());
return "Menu.jsp";
}
}
Customer.java
package dao;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.xml.ws.BindingType;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
#Component
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
int custid;
#Column
#NotEmpty/*(message="First Name Is Required")*/
/*#Pattern(regexp="{a-zA-Z}", message="First Name must be all letters")*/
String fname;
#NotEmpty/*(message="Last Name Is Required")*/
/*#Pattern(regexp="{a-zA-Z}", message="Last Name must be all letters")*/
String lname;
#NotEmpty/*(message="Address Is Required")*/
/*#Pattern(regexp="{a-zA-Z0-9}", message="Address must be contain only letters and numbers")*/
String address;
#NotEmpty/*(message="Email is Required")*/
/*#Email(message="Invalid Email Address")*/
String email;
#NotEmpty/*(message="Phone Number is Required")*/
/*#Size(min=10,max=10)
#Pattern(regexp="{0-9}", message="Phone Number must be all Numbers(no '- or ()'")*/
String phone;
//Getters and Setters
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Inventory-Management-System</display-name>
<welcome-file-list>
<welcome-file>Menu.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name >spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
From you comments, it seems like you are sending your initial request to
localhost:7001/InventoryManagementProject/addCustomer.jsp
I'm going to assume this means that the JSP in question is at the root of the generated WAR. You can therefore access it directly without going through a Spring #Controller. That, however, is the issue.
Your JSP contains
<form:form action="addCustForm" method="POST" commandName="customer" modelAttribute="customer">
<form:form> is a tag from the Spring form tag library. When it is processed, it looks for request attribute named whatever is specified in the commandName or modelAttribute (note that specifying both is redundant, use only one of those). In this case, it will look for a request attribute named customer, but since you haven't set such a request attribute, processing this tag will fail.
One solution, is to have your request go through a #Controller handler method before rendering the JSP. First, move your JSP to within WEB-INF and fix your InternalResourceViewResolver to have an appropriate prefix and suffix. Then add a handler like
#RequestMapping(value = "/add-customer", method = RequestMethod.GET)
public String getAddCustomerForm(Model model) {
model.addAttribute("customer", new Customer());
return "addCustomer";
}
What this does is add a new Customer object in the model attributes (which end up being added as request attributes) so that it serves as a template while creating the form.

java.lang.ClassCastException: while typecasting the command object in onSubmit method

I am beginner in spring3 so i am creating a simple login application. In my loginController i am getting "java.lang.ClassCastException: org.springframework.web.bind.support.SimpleSessionStatus cannot be cast to com.forms.LoginForm" on the following line
LoginForm login = (LoginForm)command;
For the reference code is as follows:
LoginController.java:-
package com.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.Dao.LoginDaoUtil;
import com.forms.LoginForm;
#SuppressWarnings("deprecation")
#Controller
public class LoginController extends SimpleFormController {
public LoginController() {
setCommandClass(LoginForm.class);
}
#RequestMapping("/LoginAction")
protected ModelAndView onSubmit(Object command) {
try {
LoginForm login = (LoginForm) command;
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"SpringBlogger-servlet.xml");
LoginDaoUtil daoUtil = ctx.getBean("LoginDaoUtil",
LoginDaoUtil.class);
boolean isUserValid = daoUtil.isValidUser(login.getUsername(),
login.getPassword());
if (isUserValid)
return new ModelAndView("success").addObject("name",
login.getUsername());
else
return new ModelAndView("login", "loginForm", new LoginForm());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return new ModelAndView("login", "loginForm", new LoginForm());
}
}
}
login.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>${message}</h1>
<form:form action="LoginAction" method="post" commandName="loginForm">
Username:<form:input path="username"/>
<font color="red"><form:errors path="username"/></font><br/><br/>
Password:<form:password path="password"/>
<font color="red"><form:errors path="password"/></font><br/><br/>
<input type="submit" value="submit">
</form:form>
</body>
</html>
LoginForm.java:-
package com.forms;
public class LoginForm {
private String username;
private String password;
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;
}
}
HomeController.java:-
package com.beans;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.forms.LoginForm;
#Controller
public class HomeController {
#RequestMapping({"/","/home"})
public String showHomePage(ModelMap map){
map.addAttribute("message", "Welcome to Spring Blogger");
map.addAttribute("loginForm", new LoginForm());
return "login";
}
}
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>SpringBlogger</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SpringBlogger</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringBlogger</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringBlogger-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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<mvc:annotation-driven/>
<context:component-scan base-package="com.beans" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost/springblogger"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
Please help.
Thanks,
Manish
You cannot use Object type to bind your form, use its type instead decoreated with #ModelAttribute1
#RequestMapping("/LoginAction")
public ModelAndView onSubmit(#ModelAttribute("loginForm") LoginForm command) {
Also I saw you're trying to create a new application context inside the controller which seem unecessary, use dependency injection / autowiring instead to your controller class

Resources