Spring SimpleFormController
Join the DZone community and get the full member experience.
Join For Freeto handle forms in spring you need to extend your controller class from simpleformcontroller class. here we will create a user registration form to understand how this works. the simpleformcontroller is deprecated as of spring 3.0 so if you are using spring 3.0 or above use the annotate controllers instead.
package com.vaannila.web; import org.springframework.web.servlet.modelandview; import org.springframework.web.servlet.mvc.simpleformcontroller; import com.vaannila.domain.user; import com.vaannila.service.userservice; @suppresswarnings("deprecation") public class usercontroller extends simpleformcontroller { private userservice userservice; public usercontroller() { setcommandclass(user.class); setcommandname("user"); } public void setuserservice(userservice userservice) { this.userservice = userservice; } @override protected modelandview onsubmit(object command) throws exception { user user = (user) command; userservice.add(user); return new modelandview("usersuccess","user",user); } }
i am using spring 3.0 so you see the suppresswarnings annotation there. here we extend the usercontroller from simpleformcontroller , this makes the controller class capable of handling forms. usually a form will be associated with a particular domain object, in our case it is the user class. in spring this domain object is called command object by default. to refer the command object in the jsp page you need to set the command class using the setcommandclass() method in the constructor. let say the user class has a name property, and to refer this in the jsp page you will use " command.name ". you can also change this name by using the setcommandname() method. here we set the name to user, so to access the user name in the jsp page we use " user.name ".
you need to have a method to handle the form when the form is submitted, here the onsubmit() method is used for this purpose. the onsubmit() method has access to the command object, we first typecast the command object to user (our domain object) and then to register the user we call the add() method of the service class and finally return the modelandview object.
all the forms field values will be submitted as strings to the form controller. spring has several pre registered property editors to convert the string values to common data types. incase you have a custom data type you need to create custom property editors to handle them.
the user domain object has the following attributes.
package com.vaannila.domain; public class user { private string name; private string password; private string gender; private string country; private string aboutyou; private string[] community; private boolean mailinglist; public string getname() { return name; } public void setname(string name) { this.name = name; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public string getgender() { return gender; } public void setgender(string gender) { this.gender = gender; } public string getcountry() { return country; } public void setcountry(string country) { this.country = country; } public string getaboutyou() { return aboutyou; } public void setaboutyou(string aboutyou) { this.aboutyou = aboutyou; } public string[] getcommunity() { return community; } public void setcommunity(string[] community) { this.community = community; } public boolean getmailinglist() { return mailinglist; } public void setmailinglist(boolean mailinglist) { this.mailinglist = mailinglist; } }
our user service interface.
package com.vaannila.service; import com.vaannila.domain.user; public interface userservice { public void add(user user); }
our user service implementation class.
package com.vaannila.service; import com.vaannila.domain.user; public class userserviceimpl implements userservice { @override public void add(user user) { //persist the user object here. system.out.println("user added successfully"); } }
let's now create the user registration form using the spring form tags. to use the form tags you need to first import the spring's form tag library.
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>registration page</title> </head> <body> <form:form method="post" commandname="user"> <table> <tr> <td>user name :</td> <td><form:input path="name" /></td> </tr> <tr> <td>password :</td> <td><form:password path="password" /></td> </tr> <tr> <td>gender :</td> <td> <form:radiobutton path="gender" value="m" label="m" /> <form:radiobutton path="gender" value="f" label="f" /> </td> </tr> <tr> <td>country :</td> <td> <form:select path="country"> <form:option value="0" label="select" /> <form:option value="1" label="india" /> <form:option value="2" label="usa" /> <form:option value="3" label="uk" /> </form:select></td> </tr> <tr> <td>about you :</td> <td><form:textarea path="aboutyou" /></td> </tr> <tr> <td>community :</td> <td> <form:checkbox path="community" value="spring" label="spring" /> <form:checkbox path="community" value="hibernate" abel="hibernate" /> <form:checkbox path="community" value="struts" label="struts" /> </td> </tr> <tr> <td></td> <td> <form:checkbox path="mailinglist" label="would you like to join our mailinglist?" /></td> </tr> <tr> <td colspan="2"><input type="submit"></td> </tr> </table> </form:form> </body> </html>
here the path attribute is used to bind the form fields to the domain object. here we use the http post method to submit the form. inorder to bind the form fields to the domain object successfully the command object should be set to the same name in the jsp page and the controller class. to set the command object name in the jsp page, use the commandname attribute of the form tag.
the web.xml file.
<?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>springexample6</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>*.htm</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>redirect.jsp</welcome-file> </welcome-file-list> </web-app>
next create the spring bean configuration 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:p="http://www.springframework.org/schema/p" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="viewresolver" class="org.springframework.web.servlet.view. internalresourceviewresolver" p:prefix="/web-inf/jsp/" p:suffix=".jsp" /> <bean id="userservice" class="com.vaannila.service.userserviceimpl" /> <bean name="/userregistration.htm" class="com.vaannila.web.usercontroller" p:userservice-ref="userservice" p:formview="userform" p:successview="usersuccess" /> </beans>
as you can see, we use " p " namespace here. the " p " namespace is simple and easy to use. using " p " namespace the properties can be supplied using attributes, rather than elements.
for injecting the simple types we use property name in the " p " namespace and for injecting references we add " -ref " suffix to it. for example we use p:formview for injecting the form view property and p:userservice-ref for injecting the user service.
during the http get request the formview will be rendered. when the form is submitted (during the http post request) the onsubmit() method of the usercontroller class will be called, on successful execution of the method the successview will be rendered. incase of any type conversion errors or validation errors the formview will be automatically displayed the user.
run the example by executing the redirect.jsp file. the redirect.jsp file, redirect the request to " userregistration.htm ".
<%@page contenttype="text/html" pageencoding="utf-8"%> <% response.sendredirect("userregistration.htm"); %>
the following user registration page will be displayed.
fill the form and submit it.
the onsubmit() method of the usercontroller class will be called and the control will be transfered to the view " usersuccess ". we use internalresourceviewresolver here, so the usersuccess.jsp page will be dispalyed. in the usersuccess.jsp page we dispaly all the user details using the jstl tags.
<%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <html> <head> <title>success page</title> </head> <body> user details <hr> user name : ${user.name} <br/> gender : ${user.gender} <br/> country : ${user.country} <br/> about you : ${user.aboutyou} <br/> community : ${user.community[0]} ${user.community[1]} ${user.community[2]}<br/> mailing list: ${user.mailinglist} </body> </html>
the usersuccess.jsp page.
you can download and try the example here.
source :
download
|
war :
download
|
Opinions expressed by DZone contributors are their own.
Comments