Pages Navigation Menu

Coding is much easier than you think

Autocomplete in Struts 2 using Jquery

I have already written a detailed post on Autocompleter Textbox & dropdown in Struts 2 using struts2-dojo-plugin.jar. In this post, I am going to describe how to implement Ajax based autocomplete in Struts 2 web application using jQuery plugin. 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.
struts 2 autocompleter_2
Here when user types a character in text box, jQuery will fire an ajax request using autocomplete plugin to Struts 2 action class, which in turn call the dao class which connects to the database and returns the required data back as an array list, this list should be returned in json format to the success function of ajax call. So to handle this you need struts2-json-plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute (which has getter and setter) into a JSON object. This guide will teach you on how to implementation AJAX in Struts 2 using JQuery and JSON


Now create a dynamic web project in eclipse and add the above jars in classpath of the project and the project structure should look like shown below.

Project Structure

struts 2 autocompleter

Jsp page

We are done with the setup. Now create a new jsp file under WebContent folder to display the data fetched from database into autocomplete textbox. Now to implement this page with Autocompleter feature and make sure that you referred the jQuery core and jQueryUI libraries.

<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>Autocomplete in Struts 2 using Jquery and JSON</title>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="autocompleter.js"></script>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="style.css">

	<div class="header">
		<h3>Autocomplete in Struts 2 using Jquery and JSON</h3>
	<br />
	<br />
	<div class="search-container">
		<div class="ui-widget">
			<s:textfield id="search" name="search" />


Js file

Here we get data from database via ajax and apply autocompleter

$(document).ready(function() {
	$(function() {
		source : function(request, response) {
				url : "searchAction",
				type : "POST",
				data : {
					term : request.term
				dataType : "json",
				success : function(jsonResponse) {

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.
Recommended reading :

  • AJAX implementation in Struts 2 using JQuery and JSON

    Business class

    Next step is to create a class that would fetch 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 ( {
    				data = rs.getString("FRAMEWORK");
    		} catch (Exception e) {
    		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() {
    	if (connection != null)
    		return connection;
    	else {
    		// database URL
    		String dbUrl = "jdbc:oracle:thin:@localhost:1521:XE";
    		// set the url, username and password for the database
    		connection = DriverManager.getConnection(dbUrl, "system", "admin");
    		} catch (Exception e) {
    		return connection;


    Action class

    Now Create the action class to handle Ajax call; in action class you need to create instance variables and its respective getter and setter methods since all the variables which have a setter can be set to the values as which are passed as parameters by jQuery and all the variables that have a getter method can be retrieved in the client javascript code.

    package com.action;
    import java.util.ArrayList;
    import com.dao.DataDao;
    import com.opensymphony.xwork2.Action;
    public class AutoCompleteAction implements Action {
    	// Received via Ajax request
    	private String term;
    	// Returned as responce
    	private ArrayList<String> list;
    	public String execute() {
    		try {
    			System.out.println("Parameter from ajax request : - " + term);
    			DataDao dataDao = new DataDao();
    			list = dataDao.getFrameWork(term);
    		} catch (Exception e) {
    		return SUCCESS;
    	public ArrayList<String> getList() {
    		return list;
    	public void setList(ArrayList<String> list) {
    		this.list = list;
    	public String getTerm() {
    		return term;
    	public void setTerm(String term) {
    		this.term = term;

    As mentioned in the code, the action class will call the business service class which in turn creates the necessary connection and returns the data back as an array list.
    Also read :

  • Gridview in Struts2 using jQuery DataTable
  • CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax


    In struts.xml, create a package that extend json-default and specify the result type of your action class inside this package to be json. This package component is present in struts2-json-plugin-2.x.x.jar

    Please read the article on AJAX implementation in Struts 2 using JQuery and JSON to understand about “json-default” package better.

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
      	<package name="default" extends="json-default">
    		<action name="searchAction" class="com.action.AutoCompleteAction">
    			<result type="json">
                     	   <param name="excludeNullProperties">true</param>
                	           <param name="encoding">UTF-8</param>
     	                  <param name="noCache">true</param>



    Make sure you have done mapping in web.xml file as given below,




    struts 2 autocompleter_2
    If you have any other suggestion on above topic, do let me know via comments.

    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. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

    • Pradeep Gowda

      In Action class instead of list assume that you have one object how to populate a textbox

    • Manopriyan Mano Mano

      Hai i am getting communication failuer can you please solve me

      • Pritom Ghosh

        is your database is “O.K.” to go as Dao may not be getting any value as the database was not… Hope that was a solve for the problem :)

    • ivan


      • Mohaideen Jamil

        Most welcome :)

    • N2

      hi i am not able to get value on jsp page though the ui is shown when it matches the text with database but the list in not populated.

    • Fation Hadri

      Many Thanks to you from me!You helped me a lot!I sucessfully integrate autocomplete!

      • Mohaideen Jamil

        Most welcome :)

    • Palani Samy.N

      Hi…Your war file working with my database file in mysql . my project integrate your codes but can’t call autocomplter.js file in my project….. please give solutions….