Nearby lessons

20 of 35

Spring - Command Class

📌 What You Will Learn
  • Understand Spring - Command Class
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Command Class step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Command Class

o spring-expression-4.3.9.RELEASE.jar o spring-jdbc-4.3.9.RELEASE.jar o spring-tx-4.3.9.RELEASE.jar o spring-web-4.3.9.RELEASE.jar o spring-webmvc-4.3.9.RELEASE.jar

Command Class

Command Class is a normal Java Bean class, it can be instantiate by Spring WEB MVC framework inorder to store form data which is submitted by the respective Client along with request.

The main intention to store form data in Command Class objects is

  • To make available form data to Business Logic to use.
  • To transfer form data from Controller Layer to View Layer like DTO[Fata Transfer Object]
  • To perform Server side Data Validatins before using data in Business logic.

To use Command classes in Spring WEB MVC applications, we have to use the following conventions.

  • Command class must be a normal JAVA Bean class.
  • Command class must be a public, non-abstract and non-final class.
  • Command class must have the properties whose names must be same as the form

properties name.

  • In Command class, we must provide a seperate setXXX() method and getXXX() method for

each and every property.

  • In Command classesm we have to declare all properties as private and methods as

public.

  • If we want to provide constructor in Command class then we can provide constructor,

but, it must be public and 0-argument constructor.

  • It is suggestible to implement java.io.Serializable interface
Example02
JCode Cell
1 
2public class Student implements Serializable{
3private String sid;
4private String sname;
5private String saddr;
6setXXX() and getXXX()
7}
8

Command Class

Note: In Spring WEB MVC applications, Framework will create a seperate Command object for each and every request which is generated from form.

If we want to use Command classes in Spring WEB MVC Applications then we have to use Command Controller Classes.

Spring has provided the following Command Controller classes to use Command classes.

  • BaseCommandController
  • AbstractCommandController
  • AbstractFormController
  • SimpleFormController
  • AbstractWizardFormController

BaseCommandController

It is an abstract class provided by SpringFramework as "org.springframework.web.servlet.mvc.BaseCommandController".

It is a base class for all Command Controller classes which are wishing to populate request parameters data in Command class objects.

Note: It is a deprecated abstract class , it was not existed in Spring4.x version.

AbstractCommandController — index.jsp

It is an abstract class provided by Spring Framework as "org.springframework.web.servlet.mvc.AbstractCommandController" with the following methods.

 protected abstract ModelAndViewhandle(HttpServletRequest request, HttpServletResponse response, java.lang.Object command, BindException errors)

 protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)

This controller class will populate form data in Command class objects automatically by creating Command class object for each and every request.

In general, we will use Controller class when we have form submission from client and when we dont want to perform Data Validations at Server side.

If we want to use this CommandController class then we have to declare an user defined class and it must be extended from "AbstractCommandController" abstract class and we must override handle(--) method. Note: In User defined Controller class , we have to provide 0-arg constructor, where we have to set command class by using the following method.

public void setCommandClass(Class class) or

set the following properties in Controller class configuration in Spring configuration file.

  • commandName: any name
  • commandClass: Fully qualified name of the Command class.

EX:

<bean name="/login" class="com.durgasoft.controller.LoginController"> <property name="commandName" value="user"/> <property name="commandClass" value="com.durgasoft.command.User"/>
</bean>

Note: AbstractCommandController class is deprecated and it was removed from Spring4.x version, so that, to execute the below application we have to use either Spring2.5 versin or atleast Spring3.x version.

EX:

Example05
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="loginpage"/>
12</body>
13</html>
14

AbstractCommandController — loginform.jsp

Example06
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color: red">Durga Software Solutions</h2>
12<h3 style="color: blue">User Login Page</h3>
13<form method="POST" action="login">
14<table>
15<tr>
16<td>User Name</td>
17<td><input type="text" name="uname"/></td>
18</tr>
19<tr>
20<td>Password</td>
21<td><input type="password" name="upwd"/></td>
22</tr>
23<tr>
24<td><input type="submit" value="Login"/></td>
25</tr>
26</table>
27</form>
28</body>
29</html>
30

AbstractCommandController — status.jsp

Example07
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color: red">Durga Software Solutions</h2>
12<h3 style="color: green">User Logic Status </h3>
13<h2 style="color: blue">${message}</h2>
14<h3>
15<a href="loginpage">Login Form</a>
16</h3>
17</body>
18</html>
19

AbstractCommandController — LoginController.java

Example08
JCode Cell
1 
2package com.durgasoft.controller;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.validation.BindException;
8import org.springframework.web.servlet.ModelAndView;
9import org.springframework.web.servlet.mvc.AbstractCommandController;
10 
11 
12import com.durgasoft.command.User;
13 
14public class LoginController extends AbstractCommandController{
15@Override
16protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object command, BindException exception)
17 throws Exception {
18User user = (User)command;
19String uname = user.getUname();
20String upwd = user.getUpwd();
21ModelAndView mav = null;
22if(uname.equals("durga") && upwd.equals("durga")) {
23 mav = new ModelAndView("status", "message", "User Login Success");
24}else {
25 mav = new ModelAndView("status", "message", "User Login Failure");
26}
27return mav;
28}
29}
30

AbstractCommandController — User.java

Example09
JCode Cell
1 
2package com.durgasoft.command;
3 
4import java.io.Serializable;
5 
6public class User implements Serializable{
7private String uname;
8private String upwd;
9 
10public String getUname() {
11return uname;
12}
13public void setUname(String uname) {
14this.uname = uname;
15}
16public String getUpwd() {
17return upwd;
18}
19public void setUpwd(String upwd) {
20this.upwd = upwd;
21}
22}
23

AbstractCommandController — ds-servlet.xml

Example10
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13 
14<bean name="/loginpage" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
15<property name="viewName" value="loginform"/>
16</bean>
17<bean name="/login" class="com.durgasoft.controller.LoginController">
18<property name="commandName" value="user"/>
19<property name="commandClass" value="com.durgasoft.command.User"/>
20</bean>
21 
22<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
23 
24<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
25<property name="prefix" value="/WEB-INF/"/>
26<property name="suffix" value=".jsp"/>
27</bean>
28</beans>
29

AbstractCommandController — web.xml

Example11
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<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_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>app7</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>/</url-pattern>
21</servlet-mapping>
22</web-app>
23

AbstractFormController — index.jsp

It is an abstract class provided by Spring Framework as "org.springframework.web.servlet.mvc.AbstractFormController" with the following methods.

 protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object command,BindException exception) throws Exception {

 protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException exception)throws Exception {

 Where processFormSubmission() method will handle the request , It will include the application logic which we want to execute after submmitting form, It will be executed when we submit POST rquest from the user form.  Where we have to override showForm() method to prepare view name and it will be

executed when we submitted GET request from client.

This controller class will populate form data in Command class objects automatically eithet by creating Command class object for each and every request or it will reuse the command class object from session scope if we set "sessionForm" property value true.

In general, we will use Controller class when we have form submission from client and when we dont want to perform Data Validations at Server side.

If we want to use this CommandController class then we have to declare an user defined class and it must be extended from "AbstractCommandController" abstract class and we must override processFormSubmission(--) method and showForm() method.

Note: In User defined Controller class , we have to provide 0-arg constructor, where we have to set command class by using the following method.

public void setCommandClass(Class class) or

We have to set the following properties in Controller bean configurations in spring configuration file.

  • sessionForm --> true
  • commandName --> any name
  • commandClass --> Fully qualified name of the command class.

Note: AbstractFormController class is deprecated in Spring3.x version, to use this Controller class we have to use either Spring2.5 version atleast Spring3.x version.

Example:

Example12
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="reg"/>
12</body>
13</html>
14

AbstractFormController — registrationform.jsp

Example13
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color: red" align="center">Durga Software Solutions</h2>
12<h3 style="color: blue" align="center">User Registration Page </h3>
13<form method="POST" action="reg">
14<center>
15<table>
16<tr>
17<td>Student Id</td>
18<td><input type="text" name="sid"/></td>
19</tr>
20<tr>
21<td>Student Name</td>
22<td><input type="text" name="sname"/></td>
23</tr>
24<tr>
25<td>Student Email</td>
26<td><input type="text" name="semail"/></td>
27</tr>
28<tr>
29<td>Student Mobile</td>
30<td><input type="text" name="smobile"/></td>
31</tr>
32<tr>
33<td><input type="submit" value="Registration"/></td>
34</tr>
35</table>
36</center>
37</form>
38</body>
39</html>
40

AbstractFormController — registrationdetails.jsp

Example14
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5<html>
6<head>
7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color: red;" align="center">Durga Software Solutions</h2>
12<h3 style="color: blue;" align="center">Student Registration Details</h3>
13<center>
14<table border='1'>
15<tr>
16<td>Student Id</td>
17<td>${student.sid}</td>
18</tr>
19<tr>
20<td>Student Name</td>
21<td>${student.sname}</td>
22</tr>
23<tr>
24<td>Student Email Id</td>
25<td>${student.semail}</td>
26</tr>
27<tr>
28<td>Student Mobile No</td>
29<td>${student.smobile}</td>
30</tr>
31</table>
32</center>
33</body>
34</html>
35

AbstractFormController — Student.java

Example15
JCode Cell
1 
2package com.durgasoft.command;
3 
4public class Student {
5private String sid;
6private String sname;
7private String semail;
8private String smobile;
9 
10public String getSid() {
11return sid;
12}
13public void setSid(String sid) {
14this.sid = sid;
15}
16public String getSname() {
17return sname;
18}
19public void setSname(String sname) {
20this.sname = sname;
21}
22public String getSemail() {
23return semail;
24}
25public void setSemail(String semail) {
26this.semail = semail;
27}
28public String getSmobile() {
29return smobile;
30}
31public void setSmobile(String smobile) {
32this.smobile = smobile;
33}
34}
35

AbstractFormController — StudentController.java

Example16
JCode Cell
1 
2package com.durgasoft.controller;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.springframework.validation.BindException;
8import org.springframework.web.servlet.ModelAndView;
9import org.springframework.web.servlet.mvc.AbstractFormController;
10 
11 
12import com.durgasoft.command.Student;
13 
14public class StudentController extends AbstractFormController {
15 
16@Override
17protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object command,
18 BindException exception) throws Exception {
19Student student = (Student)command;
20ModelAndView mav = new ModelAndView("registrationdetails", "student", student);
21return mav;
22}
23 
24@Override
25protected ModelAndView showForm(HttpServletRequest arg0, HttpServletResponse arg1, BindException arg2)
26 throws Exception {
27 
28return new ModelAndView("registrationform");
29}
30}
31

AbstractFormController — ds-servlet.xml

Example17
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<bean name="/reg" class="com.durgasoft.controller.StudentController">
14<property name="sessionForm" value="true"/>
15<property name="commandName" value="student"/>
16<property name="commandClass" value="com.durgasoft.command.Student"/>
17</bean>
18<bean name="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
19<bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
20
📝 Key Takeaways
  • Key ideas of Spring - Command Class explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end