How to send form data to controller - spring

I have a simple J2ee application.
I want to create a simple form of registration, then send the data at controller to storage the data in mysql database.
So I have this jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8">
<title>Registrazione</title>
</head>
<body>
<h2>${msg}</h2>
<form action="/sendDati" method="POST">
<label>Nome <span class="color-red">*</span></label>
<input type="text" class="form-control margin-bottom-20" name="nome" required></input>
<label>Email <span class="color-red">*</span></label>
<input type="email" class="form-control margin-bottom-20" name="email" required></input>
<label>Password <span class="color-red">*</span></label>
<input type="password" class="form-control margin-bottom-20" name="password" required></input>
<label>Conferma Password <span class="color-red">*</span></label>
<input type="password" class="form-control margin-bottom-20" name="password1" required></input>
<button type="submit" class="btn btn-primary">REGISTRATI</button>
</form>
</body>
</html>
and this is the controller:
package com.springmvcapp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class RegistrazioneController {
#RequestMapping("/registrazione")
public ModelAndView helloWorld(){
ModelAndView model = new ModelAndView("registrazione");
model.addObject("msg", "hello world");
return model;
}
#RequestMapping(value = "/sendDati")
public String getDataFromForum(#RequestParam String nome){
System.out.println("pippo");
return nome;
}
}
But when I try to click on Registrazione button I received this error
HTTP Status 404 - /sendDati
How can I fixed this error?
EDIT:
springmvcapp-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"
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="com.springmvcapp.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
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">
<display-name>SpringMVCApp</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springmvcapp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvcapp</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
EDIT 2
I have change this. When I try to open my registrazione.jsp page I use this method:
<form action="RegistrazioneController/registrazione.html">
<button class="btn btn-primary btn-lg" data-toggle="modal" onclick="submit">
Registrazione
</button>
</form>
My Jsp form is this:
<form action="RegistrazioneController/sendDati" method="POST"/>
My RegistrazioneController class is this:
#Controller
#RequestMapping("/RegistrazioneController")
public class RegistrazioneController {
#RequestMapping("/registrazione")
public ModelAndView helloWorld(){
ModelAndView model = new ModelAndView("registrazione");
model.addObject("msg", "hello world");
return model;
}
#RequestMapping(value = "/sendDati")
public String getDataFromForum(#RequestParam String nome){
System.out.println("pippo");
return nome;
}
}

Subject:
POST Html-Form data towards Spring-Boot #Controller as one DTO Object example
The following demonstrates:
- SPRING BOOT Application
- Html-Form with 2 fields. The Form POSTs data towards the controller single method.
- TestController with test() method that Receives an object TestObj
that includes the 2 fields.
Hope that it helps..
Y.Lev
HTML
<form action="/test" method="post">
f name:<input name="fname" value="yosi"/><br>
L name:<input name="lname" value="lev"/><br>
<input type="submit"/>
</form>
APPLICATION MAIN
#SpringBootApplication
public class ApplicationMain {
public static void main(String[] args) {
SpringApplication.run(ApplicationMain.class, args);
}
}
CONTROLLER
#Controller
public class TestController {
#RequestMapping(value="/test", method=RequestMethod.POST)
public #ResponseBody String test( TestObj testObj){
return "HELLO TEST : " + testObj;
}
}
DTO Object
public class TestObj {
public String fname;
public String lname;
public String getFname() { return fname;}
public void setFname(String fname) { this.fname = fname; }
public String getLname() { return lname; }
public void setLname(String lname) { this.lname = lname; }
#Override
public String toString() {
return "TestObj [fname=" + fname + ", lname=" + lname + "]";
}
}
Enjoy..

On your form action add ${pageContext.request.contextPath}/NameOfTheProject/sendDati
then execute your code inside
#RequestMapping(value = "/sendDati")
public String getDataFromForum(#RequestParam String nome){
System.out.println("pippo"); //execute code here
return nome;
}

It is a 404 error which means the web app server didn't find the resource.
The reason is, you have not given your controller a name.
You have to define the name of the controller like
#Controller
#RequestMapping("/controllerName")
and you need to modify the action value in the form as well.
action="appName/controllerName/methodName"

Related

Spring MVC - Uploading File Status 400 - Required MultipartFile parameter 'file' is not present

I'm new in Spring. I have excercise to make a Web app where the file is uploaded and then written to database. I'm making it with Spring MVC and Maven in Netbeans.
I made a fully working basic project based on this tutorial
https://saarapakarinen.wordpress.com/2015/01/11/building-a-basic-spring-3-web-project-netbeans-and-maven/
And tried to expand it for my application, wanted to make file uploading component based of official Spring tutorial
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-multipart
but its not working, got an error:
HTTP Status 400 - Required MultipartFile parameter 'file' is not present
I've expanded this project with wyslij.jsp (form for upload file)
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Wysylanie pliku</title>
</head>
<body>
<form method="get" action="http://localhost:8084/Hello/application/wyslij" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
And added Controller for uplading file called UpladController.java
package helloweb;
import java.io.IOException;
import org.springframework.stereotype.Controller;
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;
#Controller
public class UploadController
{
#RequestMapping(value = "wyslij", method = RequestMethod.GET)
public String handleFormUpload(#RequestParam("file") MultipartFile file) throws IOException
{
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:tak";
} else
{
return "redirect:nie";
}
}
}
web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- name of the project//-->
<display-name>HelloProject</display-name>
<servlet>
<servlet-name>front-controller</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>front-controller</servlet-name>
<url-pattern>/application/*</url-pattern>
</servlet-mapping>
<!-- max time of the session //-->
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<!-- default page //-->
<welcome-file-list>
<welcome-file>application/wyslij.jsp</welcome-file>
</welcome-file-list>
</web-app>
and front-controller-serlvet.xml file:
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- configuration to fetch jsp files automatically from WEB-INF/jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
<context:component-scan base-package="helloweb" />
</beans>
Could someone tell, why is an error and explain?
EDIT:
I decided to use form.jsp and HelloController.java made in tutorial and convert it to file upload (they were working more than my code)
form.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Page</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="http://localhost:8084/Hello/application/form">
<label>file to send: <input type="file" name="file" /></label>
<input type="submit" />
</form>
</body>
</html>
and HelloController.java
package helloweb;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
#Controller
public class HelloController
{
#RequestMapping(value = "form", method = RequestMethod.POST)
public String login(#RequestParam(value = "file", required = true) MultipartFile file) throws IOException
{
if (!file.isEmpty())
{
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:tak";
}
else
{
return "redirect:nie";
}
}
#RequestMapping("form")
public String viewLoginPage(Model model)
{
return "form";
}
}
Now I have at least file upload form displayed properly at start page, but after selecting a file and click button, I get antoher error:
HTTP Status 500 - Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
Chnaged and Controller now is:
#Controller
public class UploadController
{
#RequestMapping(value = "wyslij", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("file") MultipartFile file) throws IOException
{
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:tak";
} else
{
return "redirect:nie";
}
}
}
and the jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Wysylanie pliku</title>
</head>
<body>
<form method="post" action="http://localhost:8084/Hello/application/wyslij" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
tested service with postman
result for GET test:
HTTP Status 405 - Request method 'GET' not supported
type Status report
message Request method 'GET' not supported
description The specified HTTP method is not allowed for the requested resource.
result for POST test:
HTTP Status 400 - Required MultipartFile parameter 'file' is not present
type Status report
message Required MultipartFile parameter 'file' is not present
description The request sent by the client was syntactically incorrect.
You are sending file with multipart/form data encoding which needs Http POST. In your controller change it to post like below.
#RequestMapping(value = "wyslij", method = RequestMethod.POST)
And in your jsp as well.
<form method="post" action="http://localhost:8084/Hello/application/wyslij" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>

No mapping found for HTTP request with URI [/Project_Tracker/] in DispatcherServlet with name 'spring'

I am a beginner and trying to run simple code and I encounter the warning No mapping found for HTTP request with URI [/Project_Tracker/] in DispatcherServlet with name 'spring
Any help would be great! Thanks!!!
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Project Tracker</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>
spring-dispatcher.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.projecttrack" />
<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>
AnnotationController.java
package com.projecttracker.controllers;
import org.springframework.stereotype.Controller;
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;
#Controller
public class AnnotationController {
#RequestMapping(value="/LoginPage.html", method=RequestMethod.GET)
public ModelAndView getLoginRequest(){
ModelAndView model=new ModelAndView("LoginPage");
model.addObject("projectTitle","Project Track");
return model;
}
#RequestMapping(value="/LoginSuccess.html", method=RequestMethod.POST)
public ModelAndView getLoginResponse(#RequestParam("userName") String name,
#RequestParam("passWord") String password){
UserInfo userinfo1=new UserInfo();
userinfo1.setuserName(name);
userinfo1.setpassWord(password);
ModelAndView model=new ModelAndView("LoginSuccess");
model.addObject("userinfo1",userinfo1);
return model;
}
}
UserInfo.java (POJO class)
package com.projecttracker.controllers;
public class UserInfo {
private String userName;
private String passWord;
public String getuserName(){
return userName;
}
public void setuserName(String name){
userName=name;
}
public String getpassWord(){
return passWord;
}
public void setpassWord(String password){
passWord=password;
}
}
LoginPage.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>
<h2>${projectTitle}</h2>
<body>
<form action="/ProjectTrack/LoginSuccess.html" method="post">
<fieldset>
<h3>Sign In</h3>
User name:
<input type="text" name="userName"><br><br>
Password:
<input type="text" name="passWord"><br><br>
<input type="submit" value="Login"><br><br>
</fieldset>
</form>
</body>
</html>
LoginSuccess.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>Project Track</title>
</head>
<body>
<br>
${userinfo1.userName}<br>
${userinfo1.passWord}<br>
</body>
</html>
You can add / to
#RequestMapping(value="/LoginPage.html", method=RequestMethod.GET) like:
#RequestMapping(value= {"/", "/LoginPage.html"), method=RequestMethod.GET)
Or you can create a index page or welcome page in root path. What you met is just there is not a controller method which is mapped to /.

Spring using Netbeans-Neither BindingResult nor plain target object for bean name Netbeans

I am very much new to developing java applications using Spring framework. I have previously developed applications using MVC architecture but this Spring is really killing me.
I mean I can't a get a single new thing right in less than hour. Anyway, I am stuck in a very common problem while handling forms. I have tried for hours, searched the web for my problem and none of them have worked. Is it something to do with Netbeans? I don't know.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form:form action="apptest.htm" commandName="userForm" method="POST">
Name:<form:input path="name" />
<br>
Age:<form:input path="age" />
<br>
City:<form:input path="city" />
<br>
<input type="submit" value="Submit">
<br>
</form:form>
</body>
</html>
InsertController.java
package SpringApp.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import SpringApp.DAO.PeopleDAO;
import SpringApp.DAO.People;
import java.util.Map;
import org.springframework.web.bind.annotation.ModelAttribute;
#Controller
#RequestMapping("/apptest.htm")
/**
*
* #author ROHAN
*/
public class InsertController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Map<String, Object> model) {
People userForm = new People();
model.put("userForm", userForm);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
/*public String insertion(ModelMap modelMap) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("Beans.xml");
PeopleDAO dao=(PeopleDAO)ctx.getBean("people");
int status=dao.saveEmployee(new People("Kitty",22,"khardah"));
modelMap.put("msg2","success");
return "test";
}*/
public String processRegistration(#ModelAttribute(value="userForm") People people,
Map<String, Object> model) {
model.put("name",people.getName());
model.put("city",people.getCity());
return "test";
}
}
People.java (Bean class)
package SpringApp.DAO;
public class People {
private int id;
private String name;
private int age;
private String city;
public People()
{
super();
}
public People(String name,int age,String city)
{
this.name=name;
this.age=age;
this.city=city;
}
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "User [name=" + name + ", age=" + age+ ", city=" + city + "]";
}
}
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<context:annotation-config />
<context:component-scan base-package="SpringApp" />
<mvc:annotation-driven />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</beans>
index.jsp is my welcome page as configured in web.xml. Whenever I run the project, I get the following message:
29-Feb-2016 02:46:14.550 SEVERE [http-nio-8035-exec-183] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/SpringApp] threw exception [An exception occurred processing JSP page /index.jsp at line 17
14: </head>
15: <body>
16: <form:form action="apptest.htm" commandName="userForm" method="POST">
17: Name:<form:input path="name" />
18: <br>
19: Age:<form:input path="age" />
20: <br>
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userForm' 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:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at org.apache.jsp.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:228)
at org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:180)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:134)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My project structure is as follows:
Web pages
META-INF
WEB-INF
jsp
test.jsp
dispatcher-servlet.xml
applicationContext.xml
web.xml
index.jsp(outside WEB-INF)
Source Packages
Beans.xml
SpringApp.Controllers
InsertController
SpringApp.DAO
People.java
PeopleDAO.java
test.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
Name: ${userForm.name} <br>
City: ${userForm.city}
</body>
</html>
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute
As you can see from stacktrace index.jsp can't map model attribute to form parameters.
This happans because you have index.jsp in your <welcome-file-list>. So index.jsp is loaded before controller and don't have access to model values.
To solve this problem you have to:
move your index.jsp file to WEB-INF/jsp folder;
change <welcome-file-list> to this:
<welcome-file-list>
<welcome-file></welcome-file>
</welcome-file-list>
or delete this tag at all.
add "/" to #RequestMapping in InsertController class.
So, now your controller will process request, add value to model and pass it to index.jsp.
Below I posted full code.
InsertController
import SpringApp.DAO.People;
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 java.util.Map;
#Controller
#RequestMapping({"/", "/apptest.htm"})
/**
*
* #author ROHAN
*/
public class InsertController {
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Map<String, Object> model) {
People userForm = new People();
model.put("userForm", userForm);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute(value="userForm") People people,
Map<String, Object> model) {
model.put("name",people.getName());
model.put("city",people.getCity());
return "test";
}
}
web.xml
<web-app id="WebApp_ID" 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</display-name>
<description>Spring MVC</description>
<!-- For web context -->
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/application-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--<welcome-file-list>-->
<!--<welcome-file></welcome-file>-->
<!--</welcome-file-list>-->
</web-app>
it looks like your model attribute is not bind with request, make below change in your index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form:form action="apptest.htm" modelAttribute="userForm" method="POST">
Name:<form:input path="name" />
<br>
Age:<form:input path="age" />
<br>
City:<form:input path="city" />
<br>
<input type="submit" value="Submit">
<br>
</form:form>
</body>
</html>
Now be sure that you have a test.jsp having modelAttribute of People bean otherwise it will again cause of error.

Spring Error form not displayed

I created a Spring MVC Project but the errors of form are not displayed .Why?
I try to create a simple form.This is the code of my Project.The project works but in jsp the error are not dispayed..Where did I go wrong?Thanks
Student.java
package coreservlets;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student {
#Size(min=4,max=5,message="Size wrong")
#NotNull
private String name;
#Size(min=4,max=5,message="Size wrong")
#NotNull
private Integer age;
#Size(min=4,max=5,message="Size wrong")
#NotNull
private Integer id;
public String getName(){return name;}//getName
public void setName(String name){this.name=name;}//setName
public Integer getAge(){return age;}//getAge
public void setAge(Integer age){this.age=age;}//setAge
public Integer getId(){return id;}//getId
public void setId(Integer id){this.id=id;}//setId
}//Student
StudentController.java
package coreservlets;
import javax.validation.Valid;
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;
#Controller
public class StudentController {
#RequestMapping(value="/",method=RequestMethod.GET)
public ModelAndView student(){
return new ModelAndView("student", "command", new Student());
}//student
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model){
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}//addStudent
}//StudentController
student.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>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="post" action="/SpringMVCFormExample/addStudent" >
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
<form:errors path="name" />
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age"/></td>
<form:errors path="age" />
</tr>
<tr>
<td><form:label path="id">Id</form:label></td>
<td><form:input path="id"/></td>
<form:errors path="id" />
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
result.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/html/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>Id</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Spring MVC Form</display-name>
<servlet>
<servlet-name>SpringMVCForm</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVCForm</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVCForm-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-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:component-scan base-package="coreservlets" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
Use BindingResult class as parameter in your method.
your method should look like this
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model,BindingResult result)
Spring MVC will validate the model object annotated by the #Valid annotation after binding its properties with inputs from JSP form that uses Spring’s form tags. Any constraint violations will be exposed as errors in the BindingResult object, thus we can check the violation in the controller’s method like this:
if (result.hasErrors()) {
// form validation error
} else {
// form input is ok
}
The following code will return the user to the student form when a validation error occurs. When there is no validation error, the result template will be shown
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#Valid Student student, BindingResult errors, Model model){
if (errors.hasErrors()) {
return "student";
}
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}
You need to make sure that BindingResult errors is positioned exactly after #ModelAttribute #Valid Student student
Check out this and this tutorial for more info.
On another note, you should probably be redirecting the user after a successful POST. See this for more details
If you set the validation at model level you should use BindingResult:
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(#ModelAttribute #Valid Student student,ModelMap model,BindingResult errors){
if (errors.hasErrors()) {
List<FieldError> lerr = errors.getFieldErrors();
for (FieldError err: lerr) {
// manage the errorrs
}
}
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("id",student.getId());
return "result";
}
if you want to handle validation at client level you can jquery.validate.js.

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