Recent Posts

Tuesday, 13 August 2019

Spring MVC Part 5

Controller Classes
     The main intention of Controller classes is to manage business logic or to include code in order access the business logic existed with Business components. To prepare Controller classes, Spring framework has provided a set of predefined classes in "org.springframework.web.servlet.mvc" package an which are implemented by Controller interface.
AbstractController
     This Controller Class will be used to prepare Controller classes where no form data submission in request, but it will display dynamic content through the web pages. AbstractController class is able to have the following method to have Business logic or the code to access business components.
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception
In general, we will use this Controller class in the following situations.
☀ When we click on "view profile" link in Facebook account, generating profile data
☀ When we click on "Get all Jobs" link JOB Portals
Note: In all the cases, no form submission is going on, but, dynamic content will be included in response.
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="wish"/> 
</body> 
</html> 
wish.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>Spring MVC</title> 
   </head> 
   <body> 
      <h1>Hello..!!, ${message}.</h1> 
   </body> 
</html> 
WishController.java 

package com.ashok.spring.mvc.controller; 

import java.time.LocalTime; 
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 WishController extends AbstractController { 
   @Override 
   protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) 
         throws Exception { 
      LocalTime time = LocalTime.now(); 
      int hour = time.getHour(); 
      String wishMessage = ""; 
      if (hour < 12) { 
         wishMessage = "Good Morning"; 
      } else if (hour < 17) { 
         wishMessage = "Good After noon"; 
      } else { 
         wishMessage = "Good Evening"; 
      } 
      return new ModelAndView("wish", "message", wishMessage); 
   } 
}
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 name="/wish" class="com.ashok.spring.mvc.controller.WishController"/> 
   <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>

     There are three types of AbstractControler classes.
1. ParameterizableViewController
2. MultiActionController
3. BaseCommandController

1. ParameterizableViewController
☀ Spring framework has provided this controller class in the form of "org.springframework. web.servlet.mvc.ParameterizableViewController".
☀ The main intention of this controller class is to display web pages without processing request.
☀ In ParameterizableViewController classes, it is not required to define any user defined controller class, rather, it must be configured in Spring configuration file directly and it will take "viewName" property with the logical name of the view name in order to open JSP page.
☀ In general, we will use the mechanism when we want to get some web pages just by clicking on hyperlinks.
E.g.
     If we click on "ContactUs" and "AboutUs" links in webpages then we are able to get ContactUs web page and AboutUs web page.
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> 
    <h1 align="center"> 
        <a href="contactUs">ContactUs</a>  
        <a href="aboutUs">AboutUs</a> 
    </h1> 
</body> 
</html> 
aboutUs.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> 
    <h2 style="color: red" align="center">Waytoeasylearn gives easy tutorials.</h2> 
    <br> 
    <br> 
    <br> 
    <h3> 
        <a href="home">Home Page</a> 
    </h3> 
</body> 
</html> 
contactUs.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> 
    <h2 style="color: red" align="center"> 
        Waytoeasylearn<br> 
        Website : www.waytoeasylearn.com<br> 
        Mobile : +91 9000027370<br> 
    </h2> 
    <br> 
    <br>  
    <h3> 
        <a href="home">Home Page</a> 
    </h3> 
</body> 
</html> 
HomeController.java
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; 

public class HomeController extends AbstractController { 
   @Override 
   protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) 
         throws Exception { 
      return new ModelAndView("home"); 
   } 
} 
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 name="/home" class="com.ashok.spring.mvc.controller.HomeController" /> 
    <bean name="/contactUs" class="org.springframework.web.servlet.mvc.ParameterizableViewController"> 
        <property name="viewName" value="contactUs" /> 
    </bean> 
    <bean name="/aboutUs" class="org.springframework.web.servlet.mvc.ParameterizableViewController"> 
        <property name="viewName" value="aboutUs" /> 
    </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
     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>

3. Command Controllers
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
1. To make available form data to Business Logic to use.
2. To transfer form data from Controller Layer to View Layer like DTO[Fata Transfer Object]
3. 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.
1. Command class must be a normal JAVA Bean class.
2. Command class must be a public, non-abstract and non-final class.
3. Command class must have the properties whose names must be same as the form properties name.
4. In Command class, we must provide a seperate setXXX() method and getXXX() method for each and every property.
5. In Command classesm we have to declare all properties as private and methods as public.
6. If we want to provide constructor in Command class then we can provide constructor, but, it must be public and 0-argument constructor.
7. It is suggestible to implement java.io.Serializable interface.
E.g.
public class Employee implements Serializable {
   private String empName;
   private String empId;
   private String empAddress;
   private double salary;

   public String getEmpName() {
      return empName;
   }

   public void setEmpName(String empName) {
      this.empName = empName;
   }

   public String getEmpId() {
      return empId;
   }

   public void setEmpId(String empId) {
      this.empId = empId;
   }

   public String getEmpAddress() {
      return empAddress;
   }

   public void setEmpAddress(String empAddress) {
      this.empAddress = empAddress;
   }

   public double getSalary() {
      return salary;
   }

   public void setSalary(double salary) {
      this.salary = salary;
   }
}
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.
1. BaseCommandController
2. AbstractCommandController
3. AbstractFormController
4. SimpleFormController
5. AbstractWizardFormController

1. 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.

2. AbstractCommandController:
It is an abstract class provided by Spring Framework as "org.springframework.web.servlet.mvc.AbstractCommandController" with the following methods.
protected abstract ModelAndView handle(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.
1. commandName: any name
2. commandClass: Fully qualified name of the Command class.
E.g.
<bean name="/login" class="com.ashok.spring.mvc.controller.LoginController">
   <property name="commandName" value="user"/>
   <property name="commandClass" value="com.ashok.spring.mvc.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.

3. AbstractFormController
     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.
1. sessionForm --> true
2. commandName --> any name
3. 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.

4. SimpleFormController
     This controller class is able to support the Command classes inorder to store form data in Command class objects when we submit user forms. It was introduced in Spring2.5 version as "org.springframework.web.servlet.mvc.SimpleFormController" and it was deprecated in SPring3.x version and it was removed in spring4.x version.
     It is best option for Data Validations in Spring WEB MVC Framework, it will render the same page automatically when validation errors are identified and it will forward to successView page when no Validation messages are identified.
     If we want to use this controller class then we have to declare an user defined class and it must be extended from SimpleFormController class and we must implement either of the following methods.
protected ModelAndView onSubmit(Object command) throws Exception
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindingExceptin exception) throws Exception
onSubmit(--) method will take the application logic which we want to execute by submitting form from client.
     If we want to use this Controller class, we must provide the the following properties in Controller class configuration.
1. formView: it will take form name to get User form.
2. commandName: it will take logical name to the command class.
3. commandClass: It will take fully qualified name of the command class.
4. sessionForm: to keep Command Object in session scope inorder to reuse command object.
     In case of SimpleFormController, if we want to provide data to the GUI components like checkboxes, radio buttons, Select boxes,..... in user forms from Controller class then we have to override the following method from SimpleFormController class.
public Map referencedData(HttpServletRequest request)throws Exception

5. AbstractWizardFormController:
     In general, In web applications , it is required to display more than one page in order to complete a given task. In web applications, providing sequence of pages in a single task is called as "Wizard".
     In general, in Web applications, we will use multiple pages to enter user details like general details, qualification details, communication details,....in User registration process, to achieve this we have to use "Wizard".
     To support for the Wizards in web applications, Spring Web MVC has provided a predefined controller in the form of "org.springframework.web.servlet.mvc.AbstractWizardFormController".
AbstractWizardFormController allows us to carry the same command object through an entire flow of Web pages in Wizard.
     If we want to use AbstractWizardController class in Spring web MVC applications then we have to use the following steps.
1. Prepare multiple web pages with the buttons where names of the buttons must be
a) _finish: Finish the wizard form.
b) _cancel: Cancel the wizard form.
c) _targetx: Move to the target page, where x is the zero-based page index.

2. Prepare Controller class by extending AbstractWizardFormController class and override the following methods.
a) protected ModelAndView processFinish(HttpServletRequest request, HttpServletResponse response, Object command, BindException exception) throws Exception
b) protected ModelAndView processCancel(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception
Where
processFinish() method will handle Wizard Finish action.
processCancel() method will handle izard cancel Task.

3. Configure contoller class configuration in Spring configuration file with "pages" property , where "pages" property must be of "list" type, it must include all the pages names in a sequence inorder to open the pages when we click on Next buttons in Wizard.
E.g
<bean name="/reg" class="com.ashok.spring.mvc.controller.UserController">
<property name="pages">
<list>
<value>form1</value>
<vale>form2</value>
<value>form3</value>
</list>
</property>
</beans>

Next Tutorial : Spring MVC Tag Library 

Previous Tutorial : Spring MVC Part 4 

1 comment:



  1. تنظيف منازل بالدمام شركة تنظيف
    تنظيف منازل بالاحساء شركة تنظيف منازل بالاحساء
    تنظيف منازل بمكة شركة تنظيف منازل بمكة
    تنظيف منازل بجدة شركة تنظيف منازل بجدة
    تنظيف منازل بالمدينة المنورة شركة تنظيف المنازل بالمدينة المنورة

    ReplyDelete