JOBS4TIMES jobs4timesLogo

Spring Web Module

Agenda :
  1. Introduction :
  • Spring Web module is uses MVC2 architecture.
  • The advantage of spring, it is clean separation of model, view, controller and DAO components.
Procedure to develop Web based applications by using Spring
  1. create web-based application by using IDE.
  2. add spring capabilities and make sure that spring bean configuration file is placed in 'WEB-INF' folder.
  3. add ContextLoaderListener in web.xml
    <web-app>
    <listener>
     <listener-class>
      org.springframework.web.context.ContextLoaderListener
     </listener-class>
    </listener>
    </web-app>
    
  4. Provide the information of spring bean configuration file in web.xml by using context parameter.
    <web-app>
    <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    </web-app>
    
  5. add DispatcherServlet in web.xml
    <web-app>
    <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>
    </web-app>
    
  6. Create another spring bean configuration file, the name of the file must be spring-servlet.xml
  7. Create a folder whose folder name is pages (this folder is used to hold the jsp's of a project)
  8. configure InternalResourceViewResolver into spring bean configuration file
    <bean id="jspView" 
     class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/pages/"/>
     <property name="suffix" value=".jsp"/>
    </bean>
    
    spring-servlet.xml
The following steps are carried out when we deployed spring based application
  1. Server reads the contents from web.xml
  2. Server creates ServletContext object
  3. Server raises an event and check for appropriate event handler in web.xml (Listener)
  4. Now the server create object to ContextLoaderListener and execute contextInitialized() method.
  5. contextInitialized() method get the Servlet Context object and get the spring bean configuration file name.
  6. The Listener uses XmlWebApplicationContext to create the spring container object.
  7. In the web-based application we use WebApplicationContext interface to create the spring container object.
  8. We use a class XmlWebApplicationContext to create the spring container.
    container
  9. The following is the internal code of ContextLoaderListener
    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.XmlWebApplicationContext;
    
    
    public class ContextLoaderListener implements ServletContextListener {
    
    public void contextInitialized(ServletContextEvent sce) {
     ServletContext application=sce.getServletContext();
     String fileName=application.getInitParameter("contextConfigLocation");
     WebApplicationContext container=new XmlWebApplicationContext(fileName);
    }
    
    public void contextDestroyed(ServletContextEvent sce) {
     //close the spring container object
    }
    
    }//class
    
    Note : We call the spring container created by the Listener class as parent spring container object.
What will happened the client send the request whose url-pattern ends with *.htm
  1. Server creates DispatcherServlet object
  2. server called 2nd init() method
  3. It will find the name of the servlet configured in web.xml file
  4. Dynamically it will find the spring bean configuration file and create child spring container object.
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;


public class DispatcherServlet extends HttpServlet {

public void init(){
 ServletConfig config=getServletConfig();
 String name=config.getServletName();
 String fileName=name+"-servlet.xml";
 WebApplicationContext context=new XmlWebApplicationContext(fileName);
}

}//class

In spring, if we want to carryout any work we must develop controller classes.

The following is the UML diagram of Controller interface

Controller
ModelAndView handleRequest(HttpServletRequest,HttpServletResponse)

  • Container is a java program, which provide the implementation of Controller interface directly or indirectly.
  • Develop a controller configure into spring bean configuration file display it and test it.
  • All the Controller classes must be configured in child spring bean (spring-servlet.xml)
  • The DAO classes and business service classes must be configured in parent spring container.
Develop a Controller class :
package com.mvc;

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 FirstController implements Controller {

public ModelAndView handleRequest(HttpServletRequest request,
			   HttpServletResponse response)throws Exception {
System.out.println("we are in handleRequest()");
ModelAndView mav=null;
return mav;
}

}//class
Configure Controller in spring bean configuration file
<bean name="/fc.htm" class="com.mvc.FirstController"/>

spring-servlet.xml

The following steps are carried out when the client send the request to server, whose url-pattern ends with .htm
  1. Server creates request and response object,if required server create DispatcherServlet object and call init() method
  2. This method creates spring container object call to spring bean whose scope is singleton, DispatcherServlet service() calls handleRequest() it returns ModelAndView object.
  3. The service() responds ModelAndView contains null value, DispatcherServlet service() method stop the execution of request, (i.e., because ModelAndView is holding null value)

    controlflow

In spring view object hold the name of view component, in spring we can use different views. (Ex : JSP or PDF or ExcelSheet are act as View)

spring model is an object it contains data, model objects are used by view component to display the output.

When ever a ModelAndView object is hand over into DispatcherServlet it call InternalResourceViewResolver , this bean forms the JSP name by getting Prefix & Suffix.

It is the responsibility of DispatcherServlet to dispatch the request to the Jsp.
We can develop controller class based on AbstractController :
The Advantages of using AbstractController when compared with Controller interface
  1. We can make sure that the controller work only for specific methods(GET or POST)
  2. We can control the cache by specified expire date and time
  3. Based on the availability of the session object we can execute the controller.
FirstController.java
package com.mvc;

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 FirstController extends AbstractController {

public ModelAndView handleRequestInternal(HttpServletRequest request,
		    HttpServletResponse response)throws Exception {
System.out.println("we are in handleRequestInternal()");
ModelAndView mav=new ModelAndView("one");
return mav;
}

}//class

The following is internal code of AbstractController

package com.mvc;

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

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

public abstract class AbstractController implements Controller{

public ModelAndView handleRequest(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	
	handleRequestInternal(request,response);
	//...............
 return null;
}

public abstract ModelAndView handleRequestInternal(HttpServletRequest
		           request, HttpServletResponse response);

}//class
  • When the client send the request to above FirstController server will call handleRequest() method.
  • As it is not available in FirstController server checks in AbstractController.
  • AbstractController will call handleRequestInternal().
controller has to work only POST request :
To achieve above requirement, we are use a method setSupportedMethods(-) in constructor as shown below.
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 SecondController extends AbstractController{
	
public SecondController(){
 String[] methods=new String[]{"POST"};
 this.setSupportedMethods(methods);
}

public ModelAndView handleRequestInternal(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		//................
 return null;
}

}//class
It is not recommended to use setSupportedMethods() to achieving by using spring bean configuration file as shown below
<bean name="/sc.htm" class="com.mvc.SecondController">
 <property name="supportedMethods">
  <value>POST</value>
 </property>
</bean>	
spring-servlet.xml
  • All modern browsers try to catch the website data , the dis-advantage of this approach is if any modification is done in server , the browser will not send the request , it's not recommended to catch the data.
  • In servlets, we are remove the browser cache by using cache Control Header to achieve the same in spring , we use a method setCacheSeconds(-).
public class SecondController extends AbstractController{
	
public SecondController(){
 this.setCacheSeconds(10);//disable cache memory 
}

public ModelAndView handleRequestInternal(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		//................
 return null;
}

}//class

When we specified setCacheSeconds(-) browser catch the data from 2 mins, if we don't want to allow browser to catch the data we specified the value zero.

If we want to execute the controller if the session object is available then we have to specify requireSession property.
<bean name="/sc.htm" class="com.mvc.SecondController">
 <property name="requireSession">
  <value>true</value>
 </property>
</bean>
spring-servlet.xml

Reports :

  • In every project we required reports, with out reports we will never implement the project reports gives the information about the health of the project.
  • Generally the management uses reports to understand the business.
  • Generally the reports are placed in side the PDF document or EXCEL.
There are so many Reporting Tools are available in the market some of them are...
  1. Jasper
  2. I-Reports
  3. I-Text
  4. FOP
  5. BO Reports //non-java
Spring guys simplifies development of reports spring guys are given so many packages.
PDF :

The following an example to generate PDF report based on i-Text

package com.mvc;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF{
	
public static void main(String[] args) throws FileNotFoundException, 
                                                 DocumentException{
 Document doc=new Document();
 PdfWriter.getInstance(doc, new FileOutputStream("report.pdf"));
 doc.open();
 
 PdfPTable table=new PdfPTable(3);
 table.addCell("first");
 table.addCell("second");
 table.addCell("third");
 
 doc.add(table);
 doc.close();
 System.out.println("success");
}

}//class
standalone iText.jar
add jar file to IDE
iText in Action book download
iText in Action in PDF
The meaning of using jasper reports is create the object to a class and call the methods.
ExcelSheet :
  • By using spring we want to develop ExcelSheet by using reports.
  • To develop Excel report we can use a predefined class AbstractExcelView.
  • This class internally uses POI API (apache) to generate Excel report.
  • POI is an OpenSource API release on apache
    (add POI.jar file)
The following is an example of generating an Excel Sheet based on ExcelView
package com.mvc;

import java.util.Map;

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

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

public class ExcelView extends AbstractExcelView{

@Override
protected void buildExcelDocument(Map mm, 
                  HSSFWorkbook book,
                  HttpServletRequest request, 
                  HttpServletResponse response)
			                   throws Exception {
 
HSSFSheet sheet=book.createSheet("dummySheet");
HSSFRow row=sheet.createRow(0);

HSSFCell cell=row.createCell(0);
 cell.setCellValue("Eno");
 
 cell=row.createCell(1);
 cell.setCellValue("Name");
 
 cell.setCellValue(2);
 cell.setCellValue("Salary"); 
}

}//class


BACK