Struts 2 jQuery Autocomplete

Struts 2 jQuery Autocomplete

In this tutorial you will see how to generate select option list based on value enter into input field using jQuery autocomplete. Please follow step below:

Steps:

  • Create maven project name: StrutsAutoCompleteExample.
  • Final project structure will be as below:

Struts 2 jQuery Autocomplete

  • pom.xml:
<dependencies>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.16.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>2.3.16.3</version>
        </dependency>       
        <!-- JASON Plug-in -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>2.3.16.3</version>
        </dependency>
    </dependencies>
  • AutoCompleteAction.java:
package com.javahonk.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("json-default")
public class AutoCompleteAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private List<String> jasonList = new ArrayList<String>();   
    private String term;

    @Override
    @Action(value = "/autoCompleteAction", 
        results = { @Result(name = "success", type = "json") })
    public String execute() throws Exception {
        jasonList.addAll(DataForAutoComplete.getName(term));
        return ActionSupport.SUCCESS;
    }   

    public List<String> getJasonList() {
        return jasonList;
    }

    public void setJasonList(List<String> jasonList) {
        this.jasonList = jasonList;
    }

    public String getTerm() {
        return term;
    }

    public void setTerm(String term) {
        this.term = term;
    }
        
}

  • DataForAutoComplete.java:
package com.javahonk.action;

import java.util.ArrayList;
import java.util.List;

public class DataForAutoComplete {
    static StringBuilder dataCache;
    static String[] data;
    static {

        dataCache = new StringBuilder();
        dataCache
                .append("Java Honk,Java Honk Test,Java Honk Test "
                        + "Successful,Java Honk Spring MVC,"
                        + "Java Honk autocomplete,Java Honk "
                        + "Spring MVC autocomplete List");

        data = dataCache.toString().split(",");
    }

    public static List<String> getName(String name) {

        List<String> returnMatchName = new ArrayList<String>();
        String[] data = dataCache.toString().split(",");
        for (String string : data) {
            if (string.toUpperCase().indexOf(name.toUpperCase()) != -1) {
                returnMatchName.add(string);
            }
        }

        return returnMatchName;
    }
}

  • WelcomeAction.java:
package com.javahonk.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;

@Results({
        @Result(name = "error", location = "/index.jsp"),
        @Result(name = "input", location = "/index.jsp")})
public class WelcomeAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    
    @Override
    @Action(value = "/welcomeAction")   
    public String execute() throws Exception {
        return ActionSupport.INPUT;
    }   
    
}

  • ApplicationResources_en.properties:
label.welcome = Struts 2 jQuery Autocomplete
  • index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Struts 2 jQuery Autocomplete</title>
<link rel="stylesheet"
    href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" />
<script type="text/javascript"
    src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $(function() {
            $("#autocomplete").autocomplete({
                source : function(request, response) {
                    $.ajax({
                        url : "autoCompleteAction",
                        type : "POST",
                        data : {
                            term : request.term
                        },
                        dataType : "json",
                        success : function(serverJsonResponse) {
                            response(serverJsonResponse.jasonList);
                        }
                    });
                }
            });
        });
    });
</script>
<s:head />
</head>

<body>
    <h2 style="color: green">
        <s:text name="label.welcome" />
    </h2>
    <s:form action="welcomeAction" namespace="/" method="post"
        name="strutsForm">
        <s:textfield id="autocomplete" size="30" maxlength="50" label="Enter Name" />
    </s:form>
</body>
</html>

  • web.xml:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>struts.devMode</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>struts.custom.i18n.resources</param-name>
            <param-value>ApplicationResources</param-value>
        </init-param>               
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
</web-app>

  • Please configure tomcat server in eclipse using this tutorial. To Run: Right click projejct –> Run As –> Run on Server. You will see below page:

Struts 2 jQuery Autocomplete

 

  • Enter value in the field to get select list autocomplete option as below:

Struts 2 jQuery Autocomplete

For more information please see this tutorial.

download Download Project: StrutsAutoCompleteExample

Leave a Reply

Your email address will not be published. Required fields are marked *