Pages Navigation Menu

Coding is much easier than you think

Ajax implementation in Struts 2 without jQuery plugin

Posted by in Ajax, Struts-2 | 2 comments

Ajax in Servlet without jQuery
 
AJAX is a technique for creating better, faster, and more interactive web applications. With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest object. With this object, your JavaScript can transfer data with a web server, without reloading the page.
 
This post elaborates on how to implement Ajax in Struts 2 application.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 

Action class

 

package com.simplecode.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.Action;

public class AjaxAction implements Action
{

   private String userName;
   private InputStream inputStream;
	
   public String ajaxMethod()
   {
	System.out.println("ajaxMethod() is called");
	byte[] bArray;
		
	if(!userName.isEmpty())
	{
	bArray = ("Welcome " + userName).getBytes();
	inputStream = new ByteArrayInputStream(bArray);
	}
	else
	{
	bArray = ("User name cant be blank").getBytes();
	inputStream = new ByteArrayInputStream(bArray);
	}
	
	return SUCCESS;
  }

  public String execute()
  {
	return SUCCESS;
  }
	
  public String getUserName()
  {
	return userName;
  }

  public void setUserName(String userName)
  {
	this.userName = userName;
  }

  public InputStream getInputStream()
  {
	return inputStream;
  }
}

 

Recommended reading:

 

Jsp Pages

 

<%@taglib prefix="s" uri="/struts-tags"%>

<html>
<head>
<title>Ajax implementation in Struts 2 </title>

<script type="text/javascript">

//Get XMLHTTP Object
function getXMLHTTPObject()
{
var xmlhttpObject = null;
try
{
 // For Old Microsoft Browsers
 xmlhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
	try
	{
        // For Microsoft IE 6.0+
	xmlhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch (e1)
	{
        // No Browser accepts the XMLHTTP Object then false
	xmlhttpObject = false;
	}
}

if (!xmlhttpObject && typeof XMLHttpRequest != 'undefined')
{
        //For Mozilla, Opera Browsers
	xmlhttpObject = new XMLHttpRequest();
}
        // Mandatory Statement returning the ajax object created
	return xmlhttpObject;
}

	
// Change the value of the outputText field
function setAjaxOutput()
{
document.getElementById('userNameDiv').innerHTML = xmlhttpObject.responseText;
}

function handleServerResponse()
{
	if (xmlhttpObject.readyState == 4)
	{
		if (xmlhttpObject.status == 200)
		{
		setAjaxOutput();
		}
		else
		{
		    alert("Error during AJAX call. Please try again");
		}
	}
}
	
// Implement business logic
function doAjaxCall()
{
   xmlhttpObject = getXMLHTTPObject();
   if (xmlhttpObject != null)
   {
   var URL = "myAjaxAction.action?userName=" + document.getElementById('userName').value;
   xmlhttpObject.open("POST", URL, true);
   xmlhttpObject.onreadystatechange = handleServerResponse;
   xmlhttpObject.send(null);
   }
}
</script>
</head>

<body>
<h3>Ajax implementation in Struts2</h3>
<br/>
<div id="userNameDiv" style="color: red; font-weight: bold"></div>
<br/>
Please Enter your Name :
<s:textfield id="userName" theme="simple" name="userName" onblur="doAjaxCall();"/>
<br />
	
</body>
</html>

 

Also read:

 

Struts.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="default" extends="struts-default" namespace="/">
<action name="ajaxExample" class="com.simplecode.action.AjaxAction">
  <result>/ajax.jsp</result>
</action>
<action name="myAjaxAction" class="com.simplecode.action.AjaxAction" method="ajaxMethod">
  <result type="stream">
     <param name="contentType">text/html</param>
     <param name="inputName">inputStream</param>
  </result>
</action>
</package>
</struts>

 

Demo

 
On running the application
 
ajax in struts 2
 
Now giving the input as Jamil, the following output is obtained
 
ajax in struts 2 output
 
Here the struts 2 action is called onBlur() event automatically , and hence the above response is obtained in the webpage without refreshing the page.
 
download

Read More

AJAX implementation in Servlets using JQuery and JSON

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

 
jsonjqueryajax

In my previous post, I explained about making AJAX calls to a servlet from a JSP page and updating a part of the JSP page with a simple response from the Servlet . In this post I am going to add something more to it by making the servlet return complex Java Objects such as lists, maps, etc with the help of JSON in addition to JQuery and AJAX.
 
Here I’m going to use a JSON library in Servlet to convert this complex Java objects (lists,maps,arrays.etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page. I am going to use google’s gson library for this purpose.
 

Library required

 
Google gson
 

Project Structure

 
Ajax using jquery and json
 

Steps done to set up our Servlet for JSON

 
From the browser perspective: jQuery
 

Jsp Page

 

<html>
<head>
<title>AJAX in Servlet using JQuery and JSON</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>

<script>
	$(document).ready(function() {

		$('.ajax-link').click(function() {
			$('.page-content').hide();
			var category = $(this).attr("data-category");
		       // the URL for the request
			$.get('ajaxAction', {
				// Parameter to be sent to server side
				category : category
			}, function(jsonResponse) {
				$.each(jsonResponse, function(index, value) {
					$("#" + index).html(value);
					if (index % 2 == 0) {
						$("#" + index).addClass("lightblue");
					}
				});
				
				$('.page-content').show();
			});
		});
	});
</script>
</head>
<body>
     <div class="main-content">
	<div>
	     <h3>Click on the links</h3>
	      <ul>
		<li><a href="#" class="ajax-link" data-category="serial">Top 5 Serial</a></li>
		<li><a href="#" class="ajax-link" data-category="movies">Top 5 Movies</a></li>
		<li><a href="#" class="ajax-link" data-category="sports">Top 5 Sports</a></li>
	      </ul>

		<h3>Result will be displayed below via Ajax</h3>
		<div class="page-content">
			<div id="0"></div>
			<div id="1"></div>
			<div id="2"></div>
			<div id="3"></div>
			<div id="4"></div>
		</div>
	</div>
      </div>
</body>
</html>

 
jQuery allows you to fire an ajax request via get or post method and expects a JSON object as a response, as described in my previous post the first and second parameter of these method are the url and a key-value pair and the third argument of get method is a function that defines what is to be done with the response that is got back from the Servlet.
 

Code Explanation

 
In the above code jquery will fire an ajax request when user clicks on a link, for this we have binded the jQuery’s click event with each link using the class supplied on the links; Then we need to extract the categoryfrom link using jQuery’s attribute selector, and then we had binded the ajax request to ajaxActionurl and passed the category as parameter and the server in turn return the required response.
 

Another must read:

 
From the server’s perspective: Servlet

In Servlet, I’m going to use a GSON library to convert Java objects (lists, maps etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page and note that I have returned the response back to jsp based on the value of categoryparameter which i pass to the servlet via jQuery’s get() method.
 

Servlet

 

package com.action;

import java.io.IOException;
import java.util.ArrayList;
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;

public class JsonServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

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

		String category = request.getParameter("category");
		List<String> result = new ArrayList<String>();

		if (category.equalsIgnoreCase("serial")) {
			result.add("Game Of Throme");
			result.add("Prison Break");
			result.add("Breaking Bad");
			result.add("Sherlok Home");
			result.add("Suits");
		} else if (category.equalsIgnoreCase("movies")) {
			result.add("Inception");
			result.add("War Horse");
			result.add("Avatar");
			result.add("Titanic");
			result.add("Life is Beautiful");
		} else if (category.equalsIgnoreCase("sports")) {
			result.add("Basket Ball");
			result.add("Football");
			result.add("Tennis");
			result.add("Rugby");
			result.add("Cricket");
		}

		String json = new Gson().toJson(result);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
}

 

Web.xml

Servlet mapping should be done in web.xml as shown below
 

<web-app ..>
<servlet>
  <servlet-name>AjaxAction</servlet-name>
  <servlet-class>com.action.JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>AjaxAction</servlet-name>
  <url-pattern>/ajaxAction</url-pattern>
</servlet-mapping>
<welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

Demo

 
On clicking ‘Top 5 Serial’ the following response appears
 
Json serial
 
On clicking ‘Top 5 Movies’ the following response appears
 
Json movie
 
download
 

Other Ajax tutorial from our Blog

 

Reference

  • jQuery.get()
  • jQuery.each()
  • Wikipedia : JSON
  •  

    Read More

    Gridview in Servlets using jQuery DataTables plugin

    Posted by in Ajax, J2EE, jQuery, Servlet | 3 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

    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

    AJAX File Upload in Java Web Application using jQuery.AjaxFileUpload plugin

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

     
    ajax style file upload in servlet and jsp
     
    In my previous article on File Upload Example in Servlet & Jsp we learnt how to upload a file into sever via Apache Commons FileUpload plugin, In this article we shall add ajax style feature to our previous example using jQuery.AjaxFileUpload.js plugin.
     

    Modifications

     
    Before getting into the tutorial, I will let you know the small modification which I made in jQuery Form Plugin.
     
    1. By default this plugin allows only images, this is specified in jQuery.AjaxFileUpload.js as below.

    valid_extensions : ['gif','png','jpg','jpeg']
    

    So inorder to upload file with other extensions, I have modified this to

    valid_extensions : ['gif','png','jpg','jpeg','txt','docx','pdf','mkv']
    

    You can include/remove these extensions according to your requirement
     
    2. When file upload fails this plugin sends two parameter in response, they are
    status : Just has the status code, it is set to false when file upload fails
    message : This holds the error message.

    When file upload is successful, no response is sent back to client. So in order to send an upload success message I have modified the code from

    settings.onComplete.apply(element, [response, settings.params]);

    to

    settings.onComplete.apply(element, [ {
    	status : true,
    	message : 'Your file has been uploaded!'
    }, settings.params ]);
    

    Now let’s go ahead implement ajax file upload functionality in java web application
     

    Library

     

    Folder structure

     
    Now Create a dynamic web project in Eclipse with following folder structure
    Ajax file upload
     

    JSP

     

    <!DOCTYPE html>
    <html>
    <head>
    <title>Asynchronous file Upload in Java Web Application</title>
    <script src="jquery-1.8.2.js"></script>
    <script src="jQuery.AjaxFileUpload.js"></script>
    <script lang="Javascript">
    $(document).ready(function() {
      $('input[type="file"]').ajaxfileupload({
      'action' : 'UploadFile',
      'onComplete' : function(response) {
          $('#upload').hide();
          $('#message').show();
    			
          var statusVal = JSON.stringify(response.status);
    
         if(statusVal == "false")
         {
         $("#message").html("<font color='red'>"+JSON.stringify(response.message)+"</font>");
         }
         if(statusVal == "true")
         {
         $("#message").html("<font color='green'>"+JSON.stringify(response.message)+"</font>");
         }
    },
    'onStart' : function() {
    	$('#upload').show();
    	$('#message').hide();
    }
    });
    });
    </script>
    <style type="text/css">
    .centered {
    	width: 100%;
    	margin-left: auto;
    	margin-right: auto;
    	text-align: center;
    }
    </style>
    </head>
    <body>
    <form>
    <div class="centered">
    	<h4>AJAX Style File upload in Java Web Application</h4>
    	<input type="file" name="file" /><br />
    	<div id="upload" style="display: none;">Uploading..</div>
    	<div id="message"></div>
    </div>
    </form>
    </body>
    </html>
    

     
    The required jquery files are referenced in the head section of jsp file. Here whenever a file is selected, the script gets fired and triggers the servlet via action parameter, which holds the servlet url. This servlet in turn handles the file upload logic in the server side.
     
    Another must read:
    jQuery form validation using jQuery Validation plugin

    jQuery Tutorial for Beginners
     

    Servlet

     

    package com.fileupload;
    
    import java.io.File;
    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 org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    public class UploadFile extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String UPLOAD_DIRECTORY = "C:/Files";
    
    	protected void doPost(HttpServletRequest request,
                 HttpServletResponse response) throws ServletException, IOException {
    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    
    	// process only if it is multipart content
    	if (isMultipart) {
    		// Create a factory for disk-based file items
    		FileItemFactory factory = new DiskFileItemFactory();
    
    		// Create a new file upload handler
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		try {
    		// Parse the request
    		List<FileItem> multiparts = upload.parseRequest(request);
    
    		for (FileItem item : multiparts) {
    		if (!item.isFormField()) {
    		String name = new File(item.getName()).getName();
    		item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
    		}
    		}
    		}
    		catch (Exception e)
    		{
    		  e.printStackTrace();
    		}
    	}
    }
    }
    

     

    web.xml

     
    Make sure that the web.xml has following mappings

    <servlet>
    	<servlet-name>UploadFile</servlet-name>
    	<servlet-class>com.fileupload.UploadFile</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>UploadFile</servlet-name>
    	<url-pattern>/UploadFile</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    

     

    Demo

     
    On Running this application
    ajax file upload2
     
    When file upload is successful
    Ajax file upload6
     
    When we try to upload a file whose format is not specified in jQuery.AjaxFileUpload.js file
    Ajax file upload4
     
    I our next article we shall implement ajax file upload functionality with file upload progress bar.
     
    download
     

    Reference

     
    jQuery.AjaxFileUpload.js
     

    Read More
    Page 4 of 41234
    View Mobile Site