Pages Navigation Menu

Coding is much easier than you think

Gridview in Servlets using jQuery DataTables plugin

Posted by in Ajax, J2EE, jQuery, Servlet | 8 comments

 
In this article we shall learn the basic coding that required to create JQuery DataTable using JSON passed by servlet. DataTable is a jQuery plugin which adds a lot of functionality to plain HTML tables, such as filtering, paging sorting, changing page length, server side processing etc.
 
Gridview-in-Java-web-application-using-jQuery-DataTable-plugin
 

Library required

 

Installation

 
Above download will provide two JQuery plugin jquery.js and jquery.dataTables.js

<script src="js/jquery.js"></script>
<script src="js/jquery.dataTables.js"></script>

 
Default stylesheet which shipped with latest DataTable download package

<link href="css/demo_table_jui.css" rel="stylesheet" />
<link href="css/jquery-ui.css" rel="stylesheet" />
<link href="css/demo_page.css" rel="stylesheet" />

 

Project Structure

Create a dynamic web project with following folder structure and place the above files as shown.
 
Folder-structure-Gridview-Java-DataTable
 

Model class

 

package com.model;

public class RevenueReport {

	public RevenueReport(String company, String country, int year, int revenue) {
		this.company = company;
		this.country = country;
		this.year = year;
		this.revenue = revenue;
	}

	private String company;
	private String country;
	private int year;
	private int revenue;

	public String getCountry() {
		return country;
	}

	public int getRevenue() {
		return revenue;
	}

	public String getCompany() {
		return company;
	}

	public int getYear() {
		return year;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public void setRevenue(int revenue) {
		this.revenue = revenue;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public void setYear(int year) {
		this.year = year;
	}
}

 

Recommended reading:

 

Business class

 
This Business Service class which provides static data using model class.
 

package com.service;

import java.util.LinkedList;
import java.util.List;

import com.model.RevenueReport;

public class BusinessService {

public static List<RevenueReport> getCompanyList() {

	List<RevenueReport> listOfCompany = new LinkedList<RevenueReport>();

	listOfCompany.add(new RevenueReport("Bosch", "Germany",2012, 40000));
	listOfCompany.add(new RevenueReport("XYZ", "India",2014, 10000));
	listOfCompany.add(new RevenueReport("Robotics", "United Kingdom",2011, 35000));
	listOfCompany.add(new RevenueReport("Merch", "USA",2010, 20000));
	listOfCompany.add(new RevenueReport("Foxtron", "Indonesia",2009, 15000));
	listOfCompany.add(new RevenueReport("Benz", "Germany",2013, 50000));
	listOfCompany.add(new RevenueReport("Audi", "United Kingdom",2012, 60000));
	listOfCompany.add(new RevenueReport("Hyat", "France",2011, 30000));
	listOfCompany.add(new RevenueReport("HCL", "India",2007, 23000));
	listOfCompany.add(new RevenueReport("CTS", "USA",2010, 42000));
	listOfCompany.add(new RevenueReport("Accenture", "France",2008, 15000));
	listOfCompany.add(new RevenueReport("Air India", "India",2005, 10000));
	listOfCompany.add(new RevenueReport("Kingfisher", "India",2011, 8000));
	listOfCompany.add(new RevenueReport("Vodaphone", "Netharland",2006, 45000));
	
	return listOfCompany;
}
}

 

Jsp

 

<!DOCTYPE html>
<html>
<head>
<title>Gridview in Servlet using jQuery DataTable plugin</title>

<link href="css/demo_table_jui.css" rel="stylesheet" />
<link href="css/jquery-ui.css" rel="stylesheet" />
<link href="css/demo_page.css" rel="stylesheet" />

<script src="js/jquery.js"></script>
<script src="js/jquery.dataTables.js"></script>
<script>
// Ajax call to Servlet to display data via DataTables
$(document).ready(function() {
	$(".jqueryDataTable").dataTable({
		"sPaginationType" : "full_numbers",
		"bProcessing" : false,
		"bServerSide" : false,
		"sAjaxSource" : "displayData",
		"bJQueryUI" : true,
		"aoColumns" : [
            { "mData": "company" },
            { "mData": "country" },
            { "mData": "year" },
            { "mData": "revenue" }
        ]
    } );
} );
</script>
</head>

<body id="dt_example">
<div id="container">
<h1>Ajax based Gridview using jQuery DataTable plugin</h1>
<div id="demo_jui">
	<table class="display jqueryDataTable">
	<thead>
	<tr>
		<th>Company</th>
		<th>Country</th>
		<th>Year</th>
		<th>Revenue</th>
	</tr>
	</thead>
	<tbody>
	</tbody>
	</table>
</div>
</div>
</body>
</html>

 

DataTable Parameters class

 
In reply to each request for information that DataTables makes to the server, it expects to get a well formed JSON object with some parameters.So Create a DataTable Parameters class with all those required parameters
 

package com.dataTable;

import java.util.List;

import com.model.RevenueReport;

public class DataTableParameters {
	// Data table plugin parameter
	int iTotalRecords;
	int iTotalDisplayRecords;
	String sEcho;
	String sColumns;
	List<RevenueReport> aaData;

	public int getiTotalRecords() {
		return iTotalRecords;
	}

	public void setiTotalRecords(int iTotalRecords) {
		this.iTotalRecords = iTotalRecords;
	}

	public int getiTotalDisplayRecords() {
		return iTotalDisplayRecords;
	}

	public void setiTotalDisplayRecords(int iTotalDisplayRecords) {
		this.iTotalDisplayRecords = iTotalDisplayRecords;
	}

	public String getsEcho() {
		return sEcho;
	}

	public void setsEcho(String sEcho) {
		this.sEcho = sEcho;
	}

	public String getsColumns() {
		return sColumns;
	}

	public void setsColumns(String sColumns) {
		this.sColumns = sColumns;
	}

	public List<RevenueReport> getAaData() {
		return aaData;
	}

	public void setAaData(List<RevenueReport> aaData) {
		this.aaData = aaData;
	}
}

 

Servlet implementation

 

package com.servlet;

import java.io.IOException;
import java.util.List;

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

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.dataTable.DataTableParameters;
import com.model.RevenueReport;
import com.service.BusinessService;

public class DataTableServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		// Call business service class to get list of company
		List<RevenueReport> listOfCompany = BusinessService.getCompanyList();

		DataTableParameters dataTableParam = new DataTableParameters();
		// Set the list fetched in aaData
		dataTableParam.setAaData(listOfCompany);

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		// Convert Java Object to Json
		String json = gson.toJson(dataTableParam);

		response.getWriter().print(json);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

 

web.xml

Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,
 

<web-app>
<servlet>
	<display-name>displayData</display-name>
	<servlet-name>displayData</servlet-name>
	<servlet-class>com.servlet.DataTableServlet</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>displayData</servlet-name>
	<url-pattern>/displayData</url-pattern>
</servlet-mapping>
<welcome-file-list>
	<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

download
 

Reference

 
jQuery DataTables in Java Web Applications
 

Read More

Introduction to Java web application & Servlets

Posted by in J2EE, JSP, Servlet

 
In this article let’s us learn about how the communication happens in a web world.
client-server-architecture
 

Client: In case of web application, web browser acts as client through which a user sends a request to server.
 
Server: A server is a combination of a hardware machines and a number of software’s running on that machine. The duty of server is to serve resources that are being requested by the client.

 
Note:
Servers itself are capable of serving static resources only.
 

HTTP Protocol

Inorder to communicate between client and server we need some set of rules so called http (Hyper text transfer protocol). In web there are a number of protocols other than http that does the communication work done, but almost in 99% of applications the requests being made are http requests.

Http: Http can be assumed as a common interface of interaction that both client and server understand.

 
Note
HTTP is a stateless protocol i.e. HTTP supports only one request per connection. This means that with HTTP the clients connects to the server to send one request and then disconnects. This mechanism allows more users to connect to a given server over a period of time.
 

Request/Response cycle

 
Web flow starts when a request is made by user via browser (client), this request is made as http request so that server can understand it. The server receives the request, finds the resources and return response to the client in form of HTTP. When a server answers a request the server usually sends some type of content to the client. The server often sends responds to the browser with a set of instructions written in HTML (HyperText Markup Language). All browsers know how to display HTML page to the user.
 

Http Request: Http requests basically have three major components.
1 – HTTP method, there are 7 methods defined in java servlets but most of the time you will see either a get or post method.
2 – The requested page URL, the page to access like www.fb.com.
3 – Parameters, parameters (as userName, password… etc.) are being send as part of request on which the response is being generated.
 
Http Response: Http requests basically have three major components.
1 – A status code, this code tells the browser whether the request is successful or not.
2 – Content type, it tells the browser about the type of content that response web page contains in it (text, picture, html…etc).
3 – The content is the information that is served as response that the user was requested.
 
So far we are familiar with the request-response cycle and client-server model over the web.
 

So here, where the Servlet does come into the picture?

 
Let’s assume a user requests a page having some text information written on some topic. This page content is never going to change and the same page is sent back to every user request.

But if a user requests to access his facebook account, this time server needs to create a page of that user’s information based on username and password provided by the user. Here the username and password are called parameters and the response is being generated dynamically based on user’s request parameter are called dynamic pages.
 
As I said before that the server can serve only static pages as response, so in case if we need to serve dynamic pages then server must have something that provides dynamic contents to serve and this can be done via servlets. Servlets are nothing but helper applications that helps the server to response back dynamic pages.
 
We shall learn about how these servlets helps server in serving dynamic contents in our upcoming tutorials. In our next article we shall learn about Servlet Architecture.
 

Read More

AJAX in Servlet & jsp using JQuery – Java web application

Posted by in J2EE, Java, jQuery | 5 comments

 
jQuery-Ajax-Servlet-Jsp
 
Implementing Ajax features in a Java web application will be so easy if you are using JQuery library; Since this library provides built-in methods that can be used to enable Ajax. In this post, I am going to demonstrate the JQuery’s Ajax capability using on blur event in java web application.
 

Folder Structure

 
jquery-ajax-basic
 
As highlighted in the image download the jQuery library and place in js folder of eclipse work-space, and refer this jQuery files in the head section in the jsp, this jQuery file is responsible for the AJAX call made to the servlet and for updating the response back in the JSP.
 

Jsp Page

 

<html>
<head>
<title>AJAX in java web application using jQuery</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<form>
  <fieldset>
    <legend>AJAX implementation in JSP and Servlet using JQuery</legend>
    <br /> Enter your Name: <input type="text" id="userName" />
 </fieldset>

 <fieldset>
   <legend>Response from jQuery Ajax Request on Blur event</legend>
   <div id="ajaxResponse"></div>
 </fieldset>
</form>
</body>
</html>

 

JS File

 
File: ajax.js
In this file we will fire ajax via jquery get method to call java servlet

$(document).ready(function() {
	$('#userName').blur(function(event) {
		var name = $('#userName').val();
		$.get('JqueryServlet', {
			userName : name
		}, function(responseText) {
			$('#ajaxResponse').text(responseText);
		});
	});
});

 
Here when the user types a name in the “userName textbox” and click anywhere outside the textbox, then its blur event gets triggered and the ‘get’ function executes the Ajax GET request on the Servlet. Here the first argument of get method is the URL, second argument is a key-value pair that passes the parameter from JSP to Servlet and the third argument is a function that defines what is to be done with the response that is got back from the Servlet.
 
Note :
This get method is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

 

Recommended reading:

  • Ajax implementation without jQuery library
  • jQuery Tutorial for Beginners
  •  

    Servlet

     
    Now let’s go on and write the servlet which handles this Ajax call

    package com.servlet;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class JqueryServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request,
    	HttpServletResponse response) throws ServletException, IOException {
    
    	String userName = request.getParameter("userName");
    	if (userName.equals("")) {
    		userName = "User name cannot be empty";
    	} else {
    		userName = "Hello " + userName;
    	}
    	response.setContentType("text/plain");
    	response.getWriter().write(userName);
    }
    }
    

    I hope the code above is self explanatory.
     

    Another must read:

     

    Web.xml

     
    Make sure you have done servlet mapping in web.xml as shown below

    <web-app>
      <display-name>JqueryAjaxServlet</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <servlet-name>JqueryServlet</servlet-name>
        <servlet-class>com.servlet.JqueryServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>JqueryServlet</servlet-name>
        <url-pattern>/JqueryServlet/*</url-pattern>
      </servlet-mapping>
    </web-app>
    

     

    Demo

     
    AJAX-implementation-in-JSP-and-Servlet-using-JQuery
     
    On running the application the above webpage is generated, in which enter a value in the textbox and click anywhere outside the textbox, then you will see a welcome message saying “Hello (userName)”.

    Note: In our next article I have explained on how to return complex Java objects such as list, map, etc. as response to a ajax call.
     
    download
     

    Reference

     

    Read More

    What is SQL Injection?

    Posted by in J2EE, Java, JDBC, Security, SQL Injection

     
    Sql Injection
     
    SQL injection is a code injection technique, used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker) – Wikipedia
     
    SQL injection errors occur when:

    1. Data enters a program from an untrusted source.
    2. The data is used to dynamically construct a SQL query.

     
    Now, let us see some of the practical Scenario of SQL injection. For example consider an application which has a login page, it is possible that the application uses a dynamic SQL Statement as below.
     

    SELECT * FROM Employee WHERE Employee_Name =  'strEmployeeName' AND Password = 'strPassword';
    

     
    This statement is expected to return at least a single row with the employee details from the Employee table as the result set when there is a row with the employee name and password entered in the SQL statement.
     
    If the attacker would enter Gokul as the strEmployeeName (in the textbox for employee name) and Krish as strPassword (in the textbox for password), the above SQL statement would become:
     

    SELECT * FROM Employee WHERE Employee_Name = 'Gokul' AND Password = 'Krish';
    

     
    If an attacker enters the string ‘Gokul€’ OR ‘a’=’a’™ for strEmployeeName, and ‘Krish’ OR ‘a’=’a’ for strPassword then the query becomes the following:
     

    SELECT * FROM Employee WHERE Employee_Name = 'Gokul'  OR 'a'='a'
    AND Password = 'Krish' OR 'a'='a';
    

     

    Since ‘a’=’a’ condition is always true, the result set would consist of all the rows in the Employee table. The application could allow the attacker to log in as the first employee in the Employee table.
     
    If the attacker would enter ‘Gokul'; DROP table Employee;€ as strEmployeeName and anything as strPassword, the SQL statement would become like the one below.
     

    SELECT * FROM Employee WHERE Employee_Name = 'Gokul';
    DROP table Employee; AND Password = 'Krish'
    

     
    This statement could cause the table Employee to be permanently deleted from the database.
     

    Solution

     
    So inorder to avoid SQL inject errors it is better to use prepare statement instead of normal statement.
     

    Read More

    Pie Chart using YUI3 jquery chart plugin in Java web application

    Posted by in Ajax, J2EE, Java, Servlet | 1 comment

     
    In this article we will learn to create a pie chart in Servlet with YUI3 jquery chart plugin and this demo is as follows
     
    pie chart jquery
     
    YUI3 provides a “charts” module for creating a wide variety of good looking charts, this module can be called using use() method. These charts requires input data to be in JSON format. For more Information on YUI3 chart, read on its official document – http://yuilibrary.com/yui/docs/charts/
     
    Recommended reading
    Create Auto-Refreshing Pie Chart/Bar Chart in Servlet dynamically using JFreeChart
     
    In this example, I am going to retrieve values from a csv file insted of database and display its data in from of pie chart, for this, I am going to use OpenCSV library which simplifies the work of parsing CSV files. Here the Data table will load the data by making an Ajax call.
     
    Note:
    • Refer the article on how to Read / Write CSV file in Java using Opencsv library/ .
     
    Download the csv file from which the data is to be read from here and place it under src folder. This csv files contains 2 columns – Source and Percentage.
     
    Final folder structure is as shown below
     
    YUI3 CHart integration in java web application
     

    Model class

     
    Create a model class that gets and sets the data from the columns of the csv file.
     

    package com.model;
    
    public class AirPollution {
    
    	private String Source;
    	private int Percentage;
    
    	public AirPollution() {
    	}
    
    	public AirPollution(String source, int percentage) {
    		Source = source;
    		Percentage = percentage;
    	}
    
    	public String getSource() {
    		return Source;
    	}
    
    	public int getPercentage() {
    		return Percentage;
    	}
    
    	public void setSource(String source) {
    		Source = source;
    	}
    
    	public void setPercentage(int percentage) {
    		Percentage = percentage;
    	}
    }
    

     

    Business class

     
    Create a Business Service class that would fetch data from the csv file using model class.
     

    BusinessService

     

    
    package com.service;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.LinkedList;
    import java.util.List;
    
    import au.com.bytecode.opencsv.CSVReader;
    
    import com.model.AirPollution;
    
    public class BusinessService {
    
    public static List<AirPollution> getAirPollutionSource() {
    
    	List<AirPollution> airPollutionList = new LinkedList<AirPollution>();
    	String fileName = "AirPollution.csv";
    
    	InputStream is = Thread.currentThread().getContextClassLoader()
    			.getResourceAsStream(fileName);
    	BufferedReader br = new BufferedReader(new InputStreamReader(is));
    
    	try {
    		CSVReader reader = new CSVReader(br,',','\"',1);
    		String[] row = null;
    		while ((row = reader.readNext()) != null)
    		{
    		airPollutionList.add(new AirPollution(row[0], Integer.parseInt(row[1])));
    		}
    		reader.close();
    	} catch (IOException e) {
    		System.err.println(e.getMessage());
    	}
    	return airPollutionList;
    }
    }
    

     
    Also read
    Struts2-Jfreechart integration
     

    Jsp page

    Now create the jsp file to display the data fetched from csv file in form of pie chart.
     

    <!DOCTYPE html>
    <html>
    <head>
    <title>Pie Chart using YUI3 Charts in Java web application</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
    <script>
    YUI().use(
    'charts',
    'charts-legend',
    'io',
    function m(Y) {
    	var data, urifordata = "./PieChartDemo",
    	marklinechart = Y.one("#pieChartId"), configuration = {
    		method : 'POST',
    		headers : {
    			'Content-Type' : 'application/json',
    		},
    
    		on : {
    			success : function(transactionid, response,	arguments)
    			{
    			data = JSON.parse(response.responseText),
    				pieChart = new Y.Chart(
    					{
    					type : "pie",
    					stacked : true,
    					dataProvider : data,
    					categoryKey : 'Source',
    					legend : {
    						position : "right",
    						width : 100,
    						height : 100,
    					},
    					render : marklinechart,
    				});
    			},
    
    	failure : function(transactionid, response,	arguments) {
    				alert("Error In Data Loading.");
    			}
    		}
    	};
    	Y.io(urifordata, configuration);
    });
    </script>
    <style>
    #pieChartId {
    	height: 400px;
    	margin: 10px;
    	max-width: 500px;
    	width: 90%;
    }
    </style>
    </head>
    <body>
    <div class="wrapper">
    <div class="container">
    	<div class="header">
    		<h3>Pie Chart Demo using YUI3 Charts in Java web application</h3>
    	</div>
    	<br />
    	<div id="pieChartId"></div>
    </div>
    </div>
    
    </body>
    </html>
    

     

    Controller

     

    package com.controller;
    
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.model.AirPollution;
    import com.service.BusinessService;
    
    public class PieChartDemo extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	protected void doGet(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		response.setContentType("application/json");
    		// Call business service class to get list of Air Pollution Source
    		List<AirPollution> airPollutionList = BusinessService.getAirPollutionSource();
    
    		Gson gson = new GsonBuilder().setPrettyPrinting().create();
    		// Convert Java Object to Json
    		String json = gson.toJson(airPollutionList);
    		
    		response.getWriter().print(json);
    	}
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    

     

    Web.xml

     
    Make sure you have done servlet mapping properly in web.xml file as shown below

      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <display-name>PieChartDemo</display-name>
        <servlet-name>PieChartDemo</servlet-name>
        <servlet-class>com.controller.PieChartDemo</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>PieChartDemo</servlet-name>
        <url-pattern>/PieChartDemo</url-pattern>
      </servlet-mapping>
    </web-app>
    

     
    download
     

    Reference

     
    YUI library Official website
     

    Read More

    Servlets – Life Cycle

    Posted by in J2EE, Servlet

    In this article we will learn about lifecycle of a servlet and about servlet lifecycle methods doGet() & doPost() and their implementation.
     
    During its lifecycle, servlet went through three main methods and all these methods are called by web container, they are as follows.
    1. Call the servlets init() method.
    2. Call the servlets service() method.
    3. Call the servlets destroy() method.
     
    Servlet Life cycle
     

    init() :

    init() method of a servlet is called only once in its lifecycle, when a very first request comes to servlet it makes servlet state from does not exists to initialized state and during all other requests servlet remains already initialized. The container calls the init() method before the servlet can serve any client request. This method can be overridden in our servlet classes to write some initialization code in it. Initialization means something like initializing your data source or other things that we want ready before servlet starts serving the request.
     
    Why constructor is not used for servlet initialization ?
    In java, constructors are used for initialization stuff, so in case of servlet why do we use an init() method and not a constructor?
    The init() method have access to two special objects called servletContext and servletConfig and we needs to use these two many times during our application. A constructor does not have access to servletConfig and servletContext that’s why we use init() instead of constructor to initialize a servlet.
     
    We shall learn about servletContext and servletConfig in upcoming article
     

    service() :

    The service() method is the main method to where working of servlet is defined, The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, then it calls the init method as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. This method determines which http method should be called based on client request. There are 7 http methods but doGet() and doPost() are most frequently used methods with in each service request.
     
    If user request is a get request than doGet() method of servlet is called and if the request is a post than doPost() method is called and all the business logic goes into either a doGet() or a doPost() method of servlet.
     

    destroy() :

    This method is called by the container when the servlet is no longer required.
     

    Read More
    Page 3 of 41234