Saturday, 14 March 2015

Spring Web


1.     WEB MODULE

--> Spring web based module uses the MVC2 architecture. We can simply develop the web based application by using spring framework.
--> In case of web based applications creating objects are treating as rising the events
--> In servlet Sun Micro System provided three events.
·         When the session object is created
·         When the request object is created.
·         When the servlet object is created.
Procedure to create web based application in spring:
1.       Create web based application
2.       Add spring capabilities to project
3.       Place applicationContext.xml file in the /WEB-INF folder
4.       Create another configuration file with the name "spring-servlet.xml"
5.       Configure context parameter(contextConfiguration)
6.       Configure listeners as part of "web.xml"
7.       Create a folder with name "Pages"
8.       Add the "InternalResourceViewResolver" to the spring bean configuration file
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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">

      <context-param>
            <param-name>contextConfiguration</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
      </context-param>
      <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <servlet>
            <servlet-name>spring</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>*.htm</url-pattern>
      </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
spring-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"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
      <bean name="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/Pages"></property>
            <property name="suffix" value=".jsp"></property>     
      </bean>
</beans>
What happens when we deploy  spring based application?
1.       When we deploy application in server read contents from web.xml  file
2.       After that server create the servlet context object.
3.       When server created the servlet context object server looks for appropriate listener classes
4.       As part of web.xml we configured ContextLoaderListener. So server execute the ContextLoaderListener class contextInitilized(ServletContextEvent  event)
5.       As part of this method spring people provided the code to get the "contextConfiguration" parameter value and read the content of parent container.
6.       ContextLoaderListener create the spring container object based on "XMLWebApplicationContext".
7.       Whenever server create the parent spring container it create the object for the DispatcherServlet. because of <load-on-startup>
8.       Now server execute the second init() of dispatcher servlet
9.       second init() method find the child spring bean name and create the child spring container object
--> In spring we have two container object those are parent and child containers
--> In the both containers we can configure the beans
--> In spring if we want to carry any work we need to create the controller classes.
MyController.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class MyController implements Controller {

      public ModelAndView handleRequest(HttpServletRequest request,
                  HttpServletResponse response) throws Exception {
            System.out.println("Welcome to Spring");
            return null;
      }

}
spring-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"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
      <bean name="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/Pages"></property>
            <property name="suffix" value=".jsp"></property>     
      </bean>
      <bean name="/mc.htm" class="com.ibm.MyController"/>
</beans>
What happened when we send request to the above servlet?
·         When we send to the above servlet server create the request and response objects
·         server hand over the request to the dispatcher servlet's service(). This method get the value of url sent by the client and checks weather any spring bean fie is configured or not if not available it gives the 404 error.
·         Spring  bean is available dispatcher servlet create the object to controller class and handover request to the handleRequest() method.
·         This method return the ModelAndView object. Now Dispatcher servlet handover the ModelAndView  object  to InternalResourceViewResolver class
·         As it find "null" it stop the execution of request.
--> In spring we have a class ModelAndView. This can hold two objects
1.       Model
2.       View
·      View object can hold the view(jsp) this is used for forwarding the request to the appropriate jsp
·      model object consist of data, These are used by view components to display client data
Create spring controller class which forwarding the request to jsp by using model and view object?
1)  Create the controller class and in handleRequest() provide the display name for the model and view object
public class DisplayJSPController implements Controller{

       public ModelAndView handleRequest(HttpServletRequest request,        HttpServletResponse response) {
              ModelAndView mav = new ModelAndView();
              mav.setViewName("display");
              return mav;
       }
}
2)      Configure the controller class in the spring-servlet.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
       <bean name="jspViewResolver"        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/Pages/"></property>
              <property name="suffix" value=".jsp"></property>
       </bean>
       <bean name="/jspController.htm"          class="com.ibm.spring .controller.DisplayJSPController"></bean>
</beans>
3)      Configure the jsp page which is mentioned in the controller class(display.jsp)
Welcome to spring web application------------------->display.jsp
Controller class which is used for storing objects ?
public class DisplayNameController implements Controller{

       public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
       {
              ModelAndView mav = new ModelAndView();
              mav.addObject("name", "Chandra");
              mav.setViewName("displayName");
              return mav;
       }
}
---------------
<%@ page isELIgnored="false" %>
${name}, welcome to Spring

Abstract controller

·         Instead of developing controller class based on the controller interface spring guys has provided one class "org.springframework.web.servlet.mvc.AbstractCOntroller"
·         We always try to develop the controller class based on the AbstractController class. The advantage of this class is they have added extra methods for handling the browser cache and supported methods.
public class ConsoleDisplayController extends AbstractController {

       public ConsoleDisplayController() {
              String[] s = new String[2];
              s[0] = "POST";
              s[1] = "GET";
              this.setSupportedMethods(s);
              this.setCacheSeconds(10);
              //it will work if session is present
              //if this.setRequireSession(true); and session is not exist it throws exception like
              //org.springframework.web.HttpSessionRequiredException: Pre-existing session required but none found
              this.setRequireSession(false);
              this.setUseExpiresHeader(true);
       }

       protected ModelAndView handleRequestInternal(HttpServletRequest request,
                     HttpServletResponse response) throws Exception {
              System.out.println("Welcome to Speing Abstract controller class");
              return null;
       }

}
In the above class we are supporting post and get methods, browser cache is 10 seconds.
What happen when we send request to above servlet?
1.       server creates the request and response objects and handover the request to the Dispatcher servlet.
2.       Now the dispatcher servlet get the url and find any beans are configured with the name if configured dispatcher servlet handover the request to the controller class handleRequest().
3.       Now server check for handle request for our class but that method is not available on the servlet so server looks this method in the super class so server execute the super class handleRequest().
4.       This method again calls the handleReuestInternal() so here it calls this mehtod in our class and execute it.
The above yellow colour configuration we can do in configuration file also. The configuration is. <?xml version="1.0" encoding="UTF-8"?>
<beans
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
       <bean name="jspViewResolver"        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/Pages/"></property>
              <property name="suffix" value=".jsp"></property>
       </bean>

       <bean name="/supportedMehtodsController.htm"           class="com.ibm.spring.abstractcontroller.SupportedMethodsInConfigurationFil        eAbstractController">
              <property name="supportedMethods" value="POST,GET" />
              <property name="cacheSeconds" value="10" />
       </bean>
</beans>

View

·        We can add multiple objects to the ModelAndView object, in this case we can use array list and can add then to the mav object
·        If we want to add multiple types  of objects to the Model and View object we will go for Map and in that map we can store data.
·        By using spring web module we can create our own view classes
If we want to develop our own view classes we need to provide the implementation of View interface. This interface is having two methods.
public class OurView implements View {

       public String getContentType() {
              return "text/html";
       }

       @SuppressWarnings("rawtypes")
       public void render(Map map, HttpServletRequest request,
                     HttpServletResponse response) throws Exception {
              PrintWriter out = response.getWriter();
              out.print("Welocme to view Class");
       }

}

Reports

·         Every project we need to develop some reports based on client requirements, generally we create reports based on the pdf and excel. In spring They have created some view class for generating reports
1.       AbstractPdfView
2.       AbstractExcelView
3.       AbstractXmlView
·         If we want to create pdf by using spring we can use AbstractPdfView class this class depends on "itext.jar" file
·         Example if we want to display all employee details in pdf
public class PDFGeneratorView extends AbstractPdfView
{

    @SuppressWarnings("rawtypes")
    protected void buildPdfDocument(Map map, Document doc, PdfWriter pw, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
       Paragraph p = new Paragraph();
       p.add("This is PDF file");
       Table t = new Table(4);
       t.setWidth(100f);
       t.setBackgroundColor(Color.GREEN);

       t.addCell(Employee.EMP_NO);
       t.addCell(Employee.EMP_NAME);
       t.addCell(Employee.SALARY);
       t.addCell(Employee.DELETED_IND);
       if (map.containsKey(Constants.EMPLOYEE_LIST))
       {
           List<Employee> empList = (List<Employee>) map.get(Constants.EMPLOYEE_LIST);
           for (Employee emp : empList)
           {
              t.addCell(emp.getEmpNo().toString());
              t.addCell(emp.getEmpName().toString());
              t.addCell(emp.getEmpSalary().toString());
              t.addCell(new Boolean(emp.isDeleted()).toString());
           }
          
       }
       doc.add(p);
       doc.add(t);
    }
}

In spring based application every time we are creating container object but some time we need to destroy it. So this need to create container based on the "AbstractApplicationContext". In this we hare registerShutDownHook() method, this method removes the container onject.

Spring bean life cycle

Spring bean life cycle means when spring container created beans are created and establishes the dependencies between the objects. By default spring beans were created when container is created once container is destroys those are removed. If we want to customize this option, for example we have spring bean with three properties eno, name and salary in this any one value is null no need to create bean object . In this case we will go for
public class InitDestroyBean
{
    public void init()
    {
       System.out.println("init method");
    }

    public void destroy()
    {
       System.out.println("Destroy method");
    }
}
<bean name="initDestroyBean"
       class="com.ibm.spring.beans.InitDestroyBean"          
       init-method="init"
       destroy-method="destroy"/>

Following are the steps which were carried out in the spring bean configuration file:
1.       Container read the configurations from the configuration file
2.       Container create the object to the bean class
3.       Container establish the dependencies b/w the object. If init method is configured it calls the init method
4.       If destroy method is configured it calls the destroy method
5.       Server removes the container from the server
·         Instead of configuring the init and destroy in configuration we have two classes which were provided by spring. Those classes are  InitializingBean, DisposableBean    by using these methods
public class InitDestroy implements InitializingBean, DisposableBean
{

    public void destroy() throws Exception
    {
       System.out.println("Destroy");
    }

    public void afterPropertiesSet() throws Exception
    {
       System.out.println("Init");
    }

}

I18N applications

1.       First we need to create properties file
2.       Configure these files in spring configuration file
3.       Create jsp file which can access the properties
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

       <bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
              <property name="basename" value="messages"/>
       </bean>
</beans>

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<spring:message code="age" />
·         If we want to configure multiple file we can use
                <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

       <bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
              <property name="basename" value="messages1,messages2"/>
       </bean>
</beans>>

Form based applications

1.AbstractCommandController:

·         Step 1: identify the form name fields
·         Step 2: create the command bean class
public class ProductCommandBean implements Serializable
{
    private static final long serialVersionUID = 4266309082169530357L;
   
    private Integer productId;
    private String productName;
    private Double price;
    public Integer getProductId()
    {
        return productId;
    }
    public void setProductId(Integer productId)
    {
        this.productId = productId;
    }
    public String getProductName()
    {
        return productName;
    }
    public void setProductName(String productName)
    {
        this.productName = productName;
    }
    public Double getPrice()
    {
        return price;
    }
    public void setPrice(Double price)
    {
        this.price = price;
    }
}

·         Step3: create command controller class by using AbstractCommandController
public class ProductAbstractCommandController extends AbstractCommandController
{
    public ProductAbstractCommandController()
    {
       this.setCommandClass(ProductCommandBean.class);
       this.setCommandName("product");
    }
   
    protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object object, BindException be)
    {
       ProductCommandBean bean = (ProductCommandBean)object;
       ModelAndView mav = new ModelAndView();
       mav.setViewName("product");
       mav.addObject("prod", bean);
       return mav;
    }
}

·         Step4 : create product.jsp file
<%@ page isELIgnored="false" %>
${prod.productId}
${prod.productName}
${prod.price}
·         Create html file which could display the form
<html>

<body bgcolor="orange">
       <form action="./productAbstractController.htm">
       <table>
              <tr>
                     <td>ProductId</td>
                     <td><input type="text" name="productId"/></td>
              </tr>
              <tr>
                     <td>ProductName</td>
                     <td><input type="text" name="productName"/></td>
              </tr>
              <tr>
                     <td>ProductPrice</td>
                     <td><input type="text" name="price"/></td>
              </tr>
              <tr>
                     <td></td>
                     <td><input type="submit" value="Save"/></td>
              </tr>
       </table>
       </form>
</body>
</html>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
·         Spring container creates object to the controller class. The internal code of AbstractCommandController create object to command bean class. It has  captured data from form and store data in the command bean object by using setter methods. This process is called "data binding process"
·         When data binding process is happened spring internal code creates the BindingException. If any exception is raised while binding process those data stored in the BindingException
public class ProductAbstractCommandController extends AbstractCommandController
{
    public ProductAbstractCommandController()
    {
       this.setCommandClass(ProductCommandBean.class);
       this.setCommandName("product");
    }
   
    protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object object, BindException be)
    {
       ProductCommandBean bean = (ProductCommandBean)object;
       ModelAndView mav = new ModelAndView();
       mav.setViewName("product");
       mav.addObject("prod", bean);
       return mav;
    }
}
The following page will display the details
<%@ page isELIgnored="false" %>
${prod.productId}
${prod.productName}
${prod.price}
·         We will never use this approach in spring to display records in view components. BindException is an object which is created at the time of data binding process. By using BindException  object we can find the number of errors as well as we get errors also
public class ProductAbstractCommandController extends AbstractCommandController
{
    public ProductAbstractCommandController()
    {
       this.setCommandClass(ProductCommandBean.class);
       this.setCommandName("product");
    }
   
    protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object object, BindException be)
    {
       ProductCommandBean bean = (ProductCommandBean)object;
       ModelAndView mav = new ModelAndView();
       mav.setViewName("product");
       mav.addObject("prod", bean);
       System.out.println(be.getErrorCount());
       System.out.println(be.getAllErrors());
       return mav;
    }
}
·         BindException contains the model object. If we want to get the model object we use the "getModel()"
public class ProductAbstractCommandController extends AbstractCommandController
{
    public ProductAbstractCommandController()
    {
       this.setCommandClass(ProductCommandBean.class);
       this.setCommandName("product");
    }
   
    protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object object, BindException be)
    {
       ProductCommandBean bean = (ProductCommandBean)object;
       ModelAndView mav = new ModelAndView();
       mav.setViewName("product");
       mav.addObject("prod", bean);
       int count = be.getErrorCount();
       List l = be.getAllErrors();
       Map m = be.getModel();
       return mav;
    }
}
·        This map object contains two objects those are 1. CommandBean object 2. BindingResultObject










Dealing errors in spring:
public class DisplayMessagesAbstractCommandController extends AbstractCommandController
{
    public DisplayMessagesAbstractCommandController()
    {
       this.setCommandClass(StudentCommandBean.class);
       this.setCommandName("student");
    }
   
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object obj, BindException be)
    {
       //Here if pass two parameters that is not working
       be.rejectValue("studentId", "id.required", "Student Id is required.");
       be.rejectValue("studentName", "name", "Student Name is required");
       ModelAndView mav = new ModelAndView();
       mav.addAllObjects(be.getModel());
       mav.setViewName("displayErrors");
       return mav;
    }
}
·         Here we are raising our own errors by using a method rejectValues(). For this method we are passing 3 arguments those are field name, error code and description
·         Error code need to configure in the properties file
·         To display errors we use the spring:bind tag
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>

<spring:bind path="student.studentId">
       ${status.errorMessage}
       ${status}
       ${staus.value}
</spring:bind>
·         To display multiple messages we use
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>

<spring:bind path="student.studentId">
       <c:forEach var="error" items="${status.errorMessage}">
              <c:out value="${error}"></c:out>
       </c:forEach>
</spring:bind>


<spring:bind path="student.studentName">
       <c:forEach var="error" items="${status.errorMessage }">
              <c:out value="${error}"></c:out>
       </c:forEach>
</spring:bind>


<spring:bind path="student.address">
       <c:forEach var="error" items="${status.errorMessage }">
              <c:out value="${error}"></c:out>
       </c:forEach>
</spring:bind>

Validators

public class StudentVallidator implements Validator
{

    public boolean supports(@SuppressWarnings("rawtypes") Class cmd)
    {
       return StudentCommandBean.class.isAssignableFrom(cmd);
    }

    public void validate(Object obj, Errors error)
    {
       StudentCommandBean bean = (StudentCommandBean) obj;
       if (bean.getStudentId() == null)
       {
           error.rejectValue("studentId", "id.required","id is required");
       }
    }

}
public class StudentvalidatorAbstractCommandController extends AbstractCommandController
{
    public StudentvalidatorAbstractCommandController()
    {
       this.setCommandClass(StudentCommandBean.class);
       this.setCommandName("student");
       this.setValidator(new StudentVallidator());
    }
   
    public ModelAndView handle(HttpServletRequest request, HttpServletResponse    response, Object obj , BindException be)
    {
       ModelAndView mav= new ModelAndView();
       mav.addAllObjects(be.getModel());
       mav.setViewName("displayErrors");
       return mav;
    }
}





2.SimpleFormController:

·         We always try to use the SimpleFormController to develop the form base application
·         SimpleFormController is depends on the two forms
1.       From View
2.       Success View
·         A resource which display form is called from view
·         A resource which display success information is called success view
Procedure
·         Identify the form name and filed names and validations
·         Develop command bean class
public class ProductCommandBean implements Serializable
{
    private static final long serialVersionUID = 4266309082169530357L;

    public static final String PRODUCT_ID = "productId";
    public static final String PRODUCT_NAME = "productName";
    public static final String PRICE = "price";

    private Integer productId;
    private String productName;
    private Double price;
//setter and getter methods
}
·         Develop from view class
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<spring:bind path="pcb.productId">
       <c:forEach var="error" items="${status.errorMessage}">
              <c:out value="${error}"></c:out>
              <br/>
       </c:forEach>
</spring:bind>


<spring:bind path="pcb.productName">
       <c:forEach var="error" items="${status.errorMessage }">
              <c:out value="${error}"></c:out>
              <br/>
       </c:forEach>
</spring:bind>


<spring:bind path="pcb.price">
       <c:forEach var="error" items="${status.errorMessage }">
              <c:out value="${error}"></c:out>
              <br/>
       </c:forEach>
</spring:bind>
<form action="./productSFC.htm" method="post" >
       <table>
              <tr>
                     <td>ProductId</td>
                     <td><input type="text" name="productId" /></td>
              </tr>
              <tr>
                     <td>ProductName</td>
                     <td><input type="text" name="productName" /></td>
              </tr>
              <tr>
                     <td>ProductPrice</td>
                     <td><input type="text" name="price" /></td>
              </tr>
              <tr>
                     <td></td>
                     <td><input type="submit" value="Save" /></td>
              </tr>
       </table>
</form>
·         Develop success view form
The following details are stored
ProductId     :      ${pcb.productId}<br/>
ProductName   :      ${pcb.productName}<br/>
price         :      ${pcb.price}<br/>
·         Develop controller class
public class ProductSFC extends SimpleFormController
{
    public ProductSFC()
    {
       this.setCommandClass(ProductCommandBean.class);
       this.setCommandName("pcb");
       this.setValidator(new ProductValidator());
       this.setSuccessView("productSuccessView");
       this.setFormView("productFormView");
    }
   
    public void doSubmit(Object obj) throws Exception
    {
       ProductCommandBean bean = (ProductCommandBean)obj;
       System.out.println(bean.getProductId());
       System.out.println(bean.getProductName());
       System.out.println(bean.getPrice());
       super.doSubmitAction(obj);
    }
}
·         Develop validator class
public class ProductValidator implements Validator
{
    public boolean supports(@SuppressWarnings("rawtypes") Class cmd)
    {
       return ProductCommandBean.class.isAssignableFrom(cmd);
    }
   
    public void validate(Object object, Errors error)
    {
       ProductCommandBean bean = (ProductCommandBean)object;
       if (bean.getProductId()==null || bean.getProductId() == 0)
       {
           error.rejectValue(ProductCommandBean.PRODUCT_ID,"productId.required");
       }
       if (StringUtils.isEmpty(bean.getProductName()))
       {
           error.rejectValue(ProductCommandBean.PRODUCT_NAME,                              "productName.required");
       }
       if (bean.getPrice() == null || bean.getPrice() == 0)
       {
           error.rejectValue(ProductCommandBean.PRICE, "price.required");
       }
    }
}
·         Configure errors in the properties file
productId.required=Product id is required.
productName.required=Product name is required.
price.required=Price is required.
id.required=id is required.
·         Configure property file in the 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

       <bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
              <property name="basename" value="messages"/>
       </bean>
</beans>
·         Configure controller class in spring-servet 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
      
       <bean name="jspViewResolver"        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/Pages/"></property>
              <property name="suffix" value=".jsp"></property>
       </bean>
      
       <!-- SimpleFormCOntroller -->
       <bean name="/productSFC.htm"      class="com.ibm.spring.forms.simpleformcontroller.ProductSFC" />
       <!--http://localhost:8089/SpringWeb2.0/productSFC.htm -->    
</beans>

·         The following steps occurs when we call the simple form controller
1.       Spring controller checks the request type sent by client
2.       Request type is "get" server send the request to from view
3.       Request type is "post" it performs the data binding process
4.       Now it will call the validate() method on the validator class and perform the validations
5.       Now internal code checks for errors on the BindingException
6.       If errors available forward request to the from view class
7.       No errors found server calls the doSubmit() on controller.
8.       After completion of process it call the success view page
·         In web based application we can get the child container object. Once we got it we can perform the jdbc transaction for saving updating and deleting
public class ProductSFC extends SimpleFormController
{
    public ProductSFC()
    {
       this.setCommandClass(ProductCommandBean.class);
       this.setCommandName("pcb");
       this.setValidator(new ProductValidator());
       this.setSuccessView("productSuccessView");
       this.setFormView("productFormView");
    }
   
    public void doSubmit(Object obj) throws Exception
    {
       ProductCommandBean bean = (ProductCommandBean)obj;
       ApplicationContext continer = getApplicationContext();
       HibernateTemplate template =      (HibernateTemplate)continer.getBean("hibernateTemplate");
       super.doSubmitAction(obj);
    }
}
·         It is recommended to use jdbc code in controller, just create code in dao layer
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
·         In spring we no need to set all properties in controller class like form view, success view
       <bean name="/springTagsProductSFC.htm"        class="com.ibm.spring.forms.simpleformcontroller.springtags.
       SpringTagsProductSFC">
              <property name="commandClass"     value="com.ibm.domain.ProductCommandBean"/>
              <property name="commandName" value="pcb"/>
              <property name="validator" ref="pv"/>
              <property name="successView" value="productSuccessView"/>
              <property name="formView" value="SpringTagsProductForm"/>
       </bean>
       <!-- http://localhost:8089/SpringWeb2.0/springTagsProductSFC.htm -->
·         We can develop form by using spring tags
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://www.springframework.org/tags"  prefix="spring"%>
<form:form action="./springTagsProductSFC.htm" commandName="pcb">
<form:errors path="productId"/><br/>
<form:errors path="productName"/><br/>
<form:errors path="price"/><br/>
<spring:message code="productId"/><form:input path="productId"/><br/>
<spring:message code="productName"/><form:input path="productName"/><br/>
<spring:message code="price"/><form:input path="price"/><br/>
<input type="submit" value="Store"/>
</form:form>

3. AbstractWizardFormController:


·         In Spring if we want to deal with these type of forms we can use AbstractWizardFormCOntroller. This form consist of pages. Pages index start with "0". This from uses the target to display next page.
If we want to develop multiple form applications we must specify two properties page and target in the form of hidden variables.

No comments:

Post a Comment