Pages Navigation Menu

Coding is much easier than you think

Autocompleter Textbox & dropdown in Struts 2

Autocompleter Textbox & dropdown in Struts 2

To create a Autocompleter component in struts 2, please follow this two steps :
1. Add struts2-dojo-plugin.jar in your class path.
2. Include the “struts-dojo-tags” tag and its header(shown below) in your jsp page

<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<sx:head />

** UPDATE: Struts 2 Complete tutorial now available here.

Action class

package com.simplecode.action;

import java.util.ArrayList;
import com.opensymphony.xwork2.Action;

public class AutoCompleteAction implements Action 
	public ArrayList<String> cricketNations = new ArrayList<String>();
	public String country;

	public String execute() 
		return SUCCESS;

	public void populateCircketNations() 
		cricketNations.add("West Indies");
		cricketNations.add("New Zealand");
		cricketNations.add("South Africa");
		cricketNations.add("Sri Lanka");

	public String displayCountry() 
		return SUCCESS;

	public String getCountry() 
		return country;

	public void setCountry(String country) 
	{ = country;

Do read: Autocomplete in Struts 2 using Jquery and JSON via Ajax

JSP Page

Here <%@taglib uri="/struts-dojo-tags" prefix="sx"%> is a directive used in jsp for including dojo ajax tag files.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@taglib uri="/struts-dojo-tags" prefix="sx"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<sx:head />
<title>Auto complete</title>
<h3>Auto complete Dropdown | Textbox</h3>
<s:form action="displayCountry">
  <sx:autocompleter name="country" list="cricketNations" showDownArrow="false" 
     label="Cricket Nations"/>
<s:submit />


Note: In <sx :autocompleter> tag, showDownArrow property indicates whether to show dropdown or not, on setting to false textbox will appear and when set to true dropdown box will appear.



<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
<package name="default" extends="struts-default" namespace="/">
<action name="autoComplete" class="com.simplecode.action.AutoCompleteAction">
    <result name="success">autoComplete.jsp</result>
<action name="displayCountry" class="com.simplecode.action.AutoCompleteAction"
    <result name="success">WelcomeToCountry.jsp</result>

Do read: AJAX implementation in Struts 2 using JQuery and JSON


On running the above example


Setting showDownArrow = “true”
autocompleter dropdown box
Setting showDownArrow = “false”
autocompleter textbox box

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