MultiActionController

MultiActionController

In general, in Spring WEB MVC applications, we will for each and every form or an URI we will prepare a separate Controller class depending on our requirement. In the above approach, if we want to provide a particular Entity related actions like save, update, search and delete then we have to prepare seperate Controller classes like SaveController, UpdateController, SearchController, DeleteController, etc. it will increase no of controller classes unnecessarily.

In the above context, to reduce no of controller classes, SPring Framework has provided an alternative in the form of “org.springframework.web. servlet.mvc.multiaction.MultiActionController”. The main intention of MultiActionController class is to group related actions into a single controller class. If we want to use MultiAction controller class in Spring WEB MVC applications then we have to declare a user defined class as sub class to “MultiActionController” and we have to define action methods with the same incoming URI names.

public (ModelAndView | Map | String | void) actionName(HttpServletRequest request, HttpServletResponse response); 

E.g

public class StudentController extends MultiActionController{ 
   public ModelAndView save(HttpServletRequest req, HttpServletResponse res)throws Exception { 
      ---- 
   } 
   public ModelAndView search(HttpServletRequest req, HttpServletResponse res)throws Exception {
      ---- 
   } 
   public ModelAndView update(HttpServletRequest req, HttpServletResponse res)throws Exception { 
      ---- 
   } 

   public ModelAndView delete(HttpServletRequest req, HttpServletResponse res)throws Exception { 
      ---- 
   } 
} 

To trap all request to the MultiActionController class and to execute action methods we have to use ‘/’ as “name” attribute value in “bean” configuration in Spring Configuration File.

<bean name="/" class="com.ashok.spring.controller.StudentController"/> 

In the above context, if we submit “http://localhost:1010/app/save” then save() method in StudentController class will be executed, similarily, search(), update(), delete() methods will be executed as per the URI values from clients like search, update, delete.

E.g.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <jsp:forward page="home"/>
</body>
</html>

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>ParameterizableViewController</title>
</head>
<body>
   <br>
   <br>
   <br>
   <div style="text-align: center">
      <a href="addpage">Add Form</a><br>
      <br><a href="searchpage">Search Form</a><br>
      <br><a href="updatepage">Update Form</a><br>
      <br><a href="deletepage">Delete Form</a>
   </div>
</body>
</html>

addForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <br>
   <div style="text-align: center">
      <h3 style="color: blue">Student Add Form</h3>
      <form action="add" method="POST">
         <table>
            <tr>
               <td>Student Id</td>
               <td><input type="text" name="sid" /></td>
            </tr>
            <tr>
               <td>Student Name</td>
               <td><input type="text" name="sname" /></td>
            </tr>
            <tr>
               <td>Student Address</td>
               <td><input type="text" name="saddr" /></td>
            </tr>
            <tr>
               <td><input type="submit" value="ADD" /></td>
            </tr>
         </table>
      </form>
   </div>
</body>
</html>

searchForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <div style="text-align: center">
      <br>
      <h3 style="color: blue">Student Search Form</h3>
      <form action="search" method="POST">
         <table>
            <tr>
               <td>Student Id</td>
               <td><input type="text" name="sid" /></td>
            </tr>
            <tr>
               <td><input type="submit" value="SEARCH" /></td>
            </tr>
         </table>
      </form>
   </div>
</body>
</html>

updateForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <br>
   <div style="text-align: center">
      <h3 style="color: blue">Student Update Form</h3>
      <form action="editform" method="POST">
         <table>
            <tr>
               <td>Student Id</td>
               <td><input type="text" name="sid" /></td>
            </tr>
            <tr>
               <td><input type="submit" value="GetEditForm" /></td>
            </tr>
         </table>
      </form>
   </div>
</body>
</html>

editForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <br>
   <br>
   <br>
   <div style="text-align: center">
      <h3 style="color: blue">Student Edit Form</h3>
      <form method="POST" action="update">
         <table>
            <tr>
               <td>Student Id</td>
               <td>${sto.sid}<input type="hidden" name="sid"
                  value='${sto.sid}' /></td>
            </tr>
            <tr>
               <td>Student Name</td>
               <td><input type='text' name='sname' value='${sto.sname}' /></td>
            </tr>
            <tr>
               <td>Student Address</td>
               <td><input type='text' name='saddr' value='${sto.saddr}' /></td>
            </tr>
            <tr>
               <td><input type="submit" value="UPDATE"></td>
            </tr>
         </table>
      </form>
   </div>
</body>
</html>

deleteForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <br>
   <br>
   <br>
   <div style="text-align: center">
      <h3 style="color: blue" align="center">Student Update Form</h3>
      <form action="delete" method="POST">
         <table>
            <tr>
               <td>Student Id</td>
               <td><input type="text" name="sid" /></td>
            </tr>
            <tr>
               <td><input type="submit" value="DELETE" /></td>
            </tr>
         </table>
      </form>
   </div>
</body>
</html>

student.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <br>
   <br>
   <div style="text-align: center">
      <h3 style="color: blue">Student Details</h3>
      <table border='1'>
         <tr>
            <td>Student Id</td>
            <td>${sto.sid}</td>
         </tr>
         <tr>
            <td>Student Name</td>
            <td>${sto.sname}</td>
         </tr>
         <tr>
            <td>Student Address</td>
            <td>${sto.saddr}</td>
         </tr>
      </table>
      <h3>
         <a href="home">Home Page</a>
      </h3>
   </div>
</body>
</html>

status.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <br>
   <br>
   <h2 style="color: red" align="center">${message}</h2>
   <h3 align="center">
      <a href="home">Home Page</a>
   </h3>
</body>
</html>
package com.ashok.spring.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class HomeController extends AbstractController {
   @Override
   protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
         throws Exception {
      return new ModelAndView("home");
   }
}
package com.ashok.spring.mvc.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.ashok.spring.mvc.dao.StudentDao;
import com.ashok.spring.mvc.dto.StudentDto;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class StudentAction extends MultiActionController {
   StudentDao studentDao;
   String status = "";
   String message = "";

   public void setStudentDao(StudentDao studentDao) {
      this.studentDao = studentDao;
   }

   public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception {
      StudentDto sto = new StudentDto();
      sto.setSid(request.getParameter("sid"));
      sto.setSname(request.getParameter("sname"));
      sto.setSaddr(request.getParameter("saddr"));
      status = studentDao.add(sto);
      if (status.equals("success")) {
         message = "Student Added Successfully";
      } else if (status.equals("failure")) {
         message = "Student Insertion Failure";
      } else if (status.equals("existed")) {
         message = "Student Existed Already";
      }
      return new ModelAndView("status", "message", message);
   }

   public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception {
      String sid = request.getParameter("sid");
      StudentDto sto = studentDao.search(sid);
      ModelAndView mav = null;
      if (sto == null) {
         mav = new ModelAndView("status", "message", "Student Not Existed");
      } else {
         mav = new ModelAndView("student", "sto", sto);
      }
      return mav;
   }

   public ModelAndView editform(HttpServletRequest request, HttpServletResponse response) throws Exception {
      String sid = request.getParameter("sid");
      StudentDto sto = studentDao.search(sid);
      ModelAndView mav = null;
      if (sto == null) {
         mav = new ModelAndView("status", "message", "Student Not Existed");
      } else {
         mav = new ModelAndView("student_edit_form", "sto", sto);
      }
      return mav;
   }

   public ModelAndView update(HttpServletRequest request, HttpServletResponse response) throws Exception {
      StudentDto sto = new StudentDto();
      sto.setSid(request.getParameter("sid"));
      sto.setSname(request.getParameter("sname"));
      sto.setSaddr(request.getParameter("saddr"));
      String status = studentDao.update(sto);
      ModelAndView mav = null;
      if (status.equals("success")) {
         mav = new ModelAndView("status", "message", "Student Updation Success");
      } else {
         mav = new ModelAndView("status", "message", "Student Updation Failure");
      }
      return mav;
   }

   public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
      ModelAndView mav = null;
      String sid = request.getParameter("sid");
      status = studentDao.delete(sid);
      if (status.equals("success")) {
         mav = new ModelAndView("status", "message", "Student Deleted Successfully");
      } else if (status.equals("notexisted")) {
         mav = new ModelAndView("status", "message", "Student Not Existed");
      } else if (status.equals("failure")) {
         mav = new ModelAndView("status", "message", "Student Deletion Failure");
      }
      return mav;
   }
}
package com.ashok.spring.mvc.dao;

import com.ashok.spring.mvc.dto.StudentDto;

/**
 * 
 * @author ashok.mariyala
 *
 */
public interface StudentDao {
   public String add(StudentDto sto); 
   public StudentDto search(String sid); 
   public String update(StudentDto sto); 
   public String delete(String sid);
}
package com.ashok.spring.mvc.dao;

import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

import com.ashok.spring.mvc.dto.StudentDto;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class StudentDaoImpl implements StudentDao {
   private JdbcTemplate jdbcTemplate;
   String status = "";

   public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
      this.jdbcTemplate = jdbcTemplate;
   }

   @Override
   public String add(StudentDto sto) {
      String query1 = "select * from student where SID = '" + sto.getSid() + "'";
      List stdList = jdbcTemplate.query(query1, (resultSet, i) -> {
         StudentDto stdEntity = new StudentDto();
         stdEntity.setSid(resultSet.getString("SID"));
         stdEntity.setSname(resultSet.getString("SNAME"));
         stdEntity.setSaddr(resultSet.getString("SADDR"));
         return stdEntity;
      });
      if (stdList.isEmpty()) {
         String query2 = "insert into student values('" + sto.getSid() + "','" + sto.getSname() + "','"
               + sto.getSaddr() + "')";
         int rowCount = jdbcTemplate.update(query2);
         if (rowCount == 1) {
            status = "success";
         } else {
            status = "failure";
         }
      } else {
         status = "existed";
      }
      return status;
   }

   @Override
   public StudentDto search(String sid) {
      StudentDto sto = null;
      String query = "select * from student where SID = '" + sid + "'";
      List stdList = jdbcTemplate.query(query, (resultSet, i) -> {
         StudentDto stdEntity = new StudentDto();
         stdEntity.setSid(resultSet.getString("SID"));
         stdEntity.setSname(resultSet.getString("SNAME"));
         stdEntity.setSaddr(resultSet.getString("SADDR"));
         return stdEntity;
      });
      if (stdList.isEmpty()) {
         sto = null;
      } else {
         sto = stdList.get(0);
      }
      return sto;
   }

   @Override
   public String update(StudentDto sto) {
      String query = "update student set SNAME = '" + sto.getSname() + "', SADDR = '" + sto.getSaddr()
            + "' where SID = '" + sto.getSid() + "'";
      int rowCount = jdbcTemplate.update(query);
      if (rowCount == 1) {
         status = "success";
      } else {
         status = "failure";
      }
      return status;
   }

   @Override
   public String delete(String sid) {
      String query1 = "select * from student where SID = '" + sid + "'";
      List stdList = jdbcTemplate.query(query1, (resultSet, i) -> {
         StudentDto stdEntity = new StudentDto();
         stdEntity.setSid(resultSet.getString("SID"));
         stdEntity.setSname(resultSet.getString("SNAME"));
         stdEntity.setSaddr(resultSet.getString("SADDR"));
         return stdEntity;
      });
      if (stdList.isEmpty()) {
         status = "notexisted";
      } else {
         String query2 = "delete from student where SID = '" + sid + "'";
         int rowCount = jdbcTemplate.update(query2);
         if (rowCount == 1) {
            status = "success";
         } else {
            status = "failure";
         }
      }
      return status;
   }
}
package com.ashok.spring.mvc.dto;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class StudentDto {
   private String sid;
   private String sname;
   private String saddr;

   public String getSid() {
      return sid;
   }

   public void setSid(String sid) {
      this.sid = sid;
   }

   public String getSname() {
      return sname;
   }

   public void setSname(String sname) {
      this.sname = sname;
   }

   public String getSaddr() {
      return saddr;
   }

   public void setSaddr(String saddr) {
      this.saddr = saddr;
   }
}

ds-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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost/student" />
      <property name="username" value="root" />
      <property name="password" value="ashok" />
   </bean>

   <bean id="jdbcTemplate"   class="org.springframework.jdbc.core.JdbcTemplate">
      <property name="dataSource" ref="dataSource" />
   </bean>
   
   <bean id="studentDao" class="com.ashok.spring.mvc.dao.StudentDaoImpl">
      <property name="jdbcTemplate" ref="jdbcTemplate" />
   </bean>

   <bean name="/home" class="com.ashok.spring.mvc.controller.HomeController" />
   
   <bean name="/addpage" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
      <property name="viewName" value="addform" />
   </bean>
   
   <bean name="/searchpage" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
      <property name="viewName" value="searchform" />
   </bean>
   
   <bean name="/updatepage" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
      <property name="viewName" value="updateform" />
   </bean>
   
   <bean name="/deletepage" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
      <property name="viewName" value="deleteform" />
   </bean>
   
   <bean name="/*"   class="com.ashok.spring.mvc.controller.StudentAction">
      <property name="studentDao" ref="studentDao" />
   </bean>
   
   <bean name="handlerMapping"   class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
   <bean name="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
      <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://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">
   <display-name>MVC</display-name>
   <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>default.html</welcome-file>
      <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
   <servlet>
      <servlet-name>ds</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>ds</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>
MultiActionController
Scroll to top