Pages Navigation Menu

Coding is much easier than you think

Autocomplete in java web application using Jquery and JSON

 
This article will describe how to implement jQuery Autocomplete in java web application. jQuery Autcomplete is part of the jQuery UI library which allows converting a normal textbox into an autocompleter textbox by providing a data source for the autocompleter values.
 
Autocompleter in java
 
Here when user types a character in text box ,jQuery will fire an ajax request using autocomplete plugin to the controller, this controller(Servlet) in turn call the dao class which connects to the database and returns the required data back as an array list. After getting the data we convert this list to json format and return it back to the success function of our ajax call.
 

Library

 
gson-2.2.2.jar
ojdbc14.jar
servlet-api.jar
jquery-1.10.2.js
jquery-ui.js
jquery-ui.css
 

Project Structure


 
Autocompleter in java project structure
 

Jsp page

Now create a jsp page with Autocompleter feature and make sure that you referred the jQuery core and jQueryUI libraries.
 

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Autocomplete in java web application using Jquery and JSON</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="autocompleter.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<!-- User defied css -->
<link rel="stylesheet" href="style.css">

</head>
<body>
<div class="header">
	<h3>Autocomplete in java web application using Jquery and JSON</h3>
</div>
<br />
<br />
<div class="search-container">
	<div class="ui-widget">
		<input type="text" id="search" name="search" class="search" />
	</div>
</div>
</body>
</html>

 

Js file

 
Here we get data from database via ajax and apply autocompleter
 

$(document).ready(function() {
	$(function() {
		$("#search").autocomplete({	
		source : function(request, response) {
		$.ajax({
			url : "SearchController",
			type : "GET",
			data : {
				term : request.term
			},
			dataType : "json",
			success : function(data) {
				response(data);
			}
		});
	}
});
});
});

 
When a user types a character in text box ,jQuery will fire an ajax request to the controller, in this case controller is SearchController as mentioned in the above js file.
 

Controller

 
Creating The Controller To Handle Ajax Calls

package com.servlet;

import java.io.IOException;
import java.util.ArrayList;

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

import com.dao.DataDao;
import com.google.gson.Gson;

public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

		response.setContentType("application/json");
		try {
			String term = request.getParameter("term");
			System.out.println("Data from ajax call " + term);

			DataDao dataDao = new DataDao();
			ArrayList<String> list = dataDao.getFrameWork(term);

			String searchList = new Gson().toJson(list);
			response.getWriter().write(searchList);
		} catch (Exception e) {
                        System.err.println(e.getMessage());
		}
	}
}

 
This servlet will call the business class which in turn creates the necessary connection and returns the data back as an array list to the controller. After getting the data we convert it to json format and return it back to the success function of our ajax call.
 

Business class

Creating Methods To Get Data From Database
 

package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class DataDao {
	private Connection connection;

	public DataDao() throws Exception {
		connection = DBUtility.getConnection();
	}

	public ArrayList<String> getFrameWork(String frameWork) {
	ArrayList<String> list = new ArrayList<String>();
	PreparedStatement ps = null;
	String data;
	try {
	ps = connection.prepareStatement("SELECT * FROM JAVA_FRAMEWORK  WHERE FRAMEWORK  LIKE ?");
		ps.setString(1, frameWork + "%");
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			data = rs.getString("FRAMEWORK");
			list.add(data);
		}
	} catch (Exception e) {
		System.out.println(e.getMessage());
	}
	return list;
}
}

 

Data Access object

 
Connecting To Database Using JDBC

package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtility {
	private static Connection connection = null;

	public static Connection getConnection() throws Exception {
		if (connection != null)
			return connection;
		else {
			// Store the database URL in a string
			String serverName = "127.0.0.1";
			String portNumber = "1521";
			String sid = "XE";
			String dbUrl = "jdbc:oracle:thin:@" + serverName + ":" + portNumber
					+ ":" + sid;
			Class.forName("oracle.jdbc.driver.OracleDriver");

			// set the url, username and password for the databse
			connection = DriverManager.getConnection(dbUrl, "system", "admin");
			return connection;
		}
	}
}

 

web.xml

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

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

 

Demo

 
Autocompleter in java
 

dwd2
Download It – jQueryAutocompleter.war

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2.

Leave a Reply Note To post source code in comment, use [code] [/code] tag

%d bloggers like this: