In this article we will explain how to use struts2 autocompleter tag. This tag is used for getting a dropdown list with options which has at least a partial match with the text we enter in the text box. If the user clicks on the dropdown button then all options will be showing in the dropdown list..
Lets see how can we create a sample application which gives the list of planet names in the dropdown list as below.
As and when the user give input in the text field , the planet names matching with the text entered will be displaying the drop down.
Make sure that you have struts2-dojo-plugin-2.1.8.jar file in your lib folder.
Add the following code into your struts.xml file.
<!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”>
<action name=”AjaxDemo”>
<result name=”success”>/ajaxDemo.jsp</result>
</action>
</package>
</struts>
Create a list in the action class and populate them with planet names as shown in the “AutoCompleteAction” class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package j2eereference; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import com.opensymphony.xwork2.ActionSupport; public class AutoCompleteAction extends ActionSupport { private List planetList; private String planets = "Mercury ,Venus ,Earth ,Mars ,Jupiter ,Saturn,Uranus,Neptune,Pluto"; public String execute() { planetList = new ArrayList(); StringTokenizer st = new StringTokenizer(planets, ","); while (st.hasMoreTokens()) { planetList.add(st.nextToken().trim()); } return SUCCESS; } public List getPlanetList() { return planetList; } } |
Now let’s create ajaxDemo.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="sx" uri="/struts-dojo-tags"%> <html> <head> <title>Welcome</title> <s:head theme="ajax" /> </head> <body> <s:label name="stateName" value="Select Planet Name:" /> <s:autocompleter list="planetList" name="planet"/> </action> </body> </html> |
In the above JSP you can notice that
1) We have included the tag library <%@ taglib prefix=”sx” uri=”/struts-dojo-tags”%>
2) <s:head theme=”ajax” /> – This is for getting the Ajax theme in our JSP page, like the background color while scrolling throgh the options etc.
3) <s:autocompleter list=”planetList” name=”planet”/>
This is for getting autocompleter list
Leave a Reply