Skip to main content

How to use Autocomplete feature with Spring


Autocomplete is a feature in javascript which shows the suggestions as soon as a user types character in the page.

For this I have used JQuery Autocomplete feature in my program to show the suggestions.

The following things are required to make this program.

1) I have used Freemarker Template for my prsentation part
2) Autocomplete is now integrated in the jQuery UI plugins as well so, no need to add any extra js plugins. So all you need to use a latest jQuery plugin and JQueryUI plugin

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

You can also download these JS and use instead.

3) Spring MVC for my Controller, Service and Repository logic
4) I have used JCR(Java Content Repository) in my program, you can use JDBC or ORMs such as Hibernate, IBatis etc.


First we need to create a ftl in the client side for a text field.

<label for="Tags">Tags</label>
 <input type="text" name="tags" id="courseFeatureTags" class="form-control input-md utf8decode" value="${courseFeatureTags!""}" placeholder="Seprated by,"  />

<script src ="${request.contextPath}/resources/js/jscriptOperations.js"></script>

Include a js file in your FTL and write the following jscript to call the method getSuggestedTags which will eventually sends the asynchronous request to server to fetch the tags.

jscriptOperations.js

$(function(){
   $('input#courseFeatureTags').keydown(function(){
       getSuggestedTags($(this).attr("id"));
   }); 
});

function getSuggestedTags(id) {
var keyword = $('#'+id).val();
if( keyword != undefined && keyword != "" && keyword.length > 1) {
$.ajax({
url : contextPath+"/course/getSuggestedTagList",
data : { keyWord : keyword},
cache : true,
async  : false,
success : function(responseData) {
//console.log(responseData);
var avlTagArr = responseData.slice(0,10);  // show only 10 suggested list
$("#"+id).autocomplete({ source: avlTagArr, minLength : 3, delay : 200 });
// the following filter extends the autocomplete feature and shows the suggestions starting with the character you typed in 
$.ui.autocomplete.filter = function (array, term) {
var matcher = new RegExp("^" +  $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
}
});
}

}

Now write a Controller class which takes the request from our client and sends it across to the Service class.

CourseController.java

// imports here
@Controller
@RequestMapping("/course")
public class CourseController {
    @Resource
    private CourseService courseService;

    @RequestMapping(value = "getSuggestedTagList")
    @ResponseBody
    public List<String> getSuggestedTagList(@RequestParam(value = "keyWord") String keyWord)       throws LoginException,
    NoSuchWorkspaceException, RepositoryException, NamingException {
       List<String> listOfSuggestedTags = null;
       if (StringUtils.isNotEmpty(keyWord)) {
         listOfSuggestedTags = courseService.getTagLists(keyWord.toLowerCase());
       }
       log.info("The list of Tags are " + listOfSuggestedTags);
       return listOfSuggestedTags;
    }
}

The CourseService class which will eventually passed to the repository class.

CourseService.java

// imports here
@Service
public class CourseService extends AbstractService {
@Resource
private CourseRepository courseRepository;

public List<String> getTagLists(String searchTags) throws LoginException, NoSuchWorkspaceException, RepositoryException, NamingException {
Session session = getSession();
courseRepository.setSession(session);
List<String> tagsList = courseRepository.getAllTags(searchTags, session);
releaseSession(session);
return tagsList;
}
}

Lastly the repository class which will fetch the tags from the Database as list.

CourseRepository.java

// imports go here

@org.springframework.stereotype.Repository
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CourseRepository extends BaseRepository<Course> {

public List<String> getAllTags(String str, Session session) throws RepositoryException {
List<String> tags = new ArrayList<>();
List<String> getAllTagList = new ArrayList<String>();
Query q = null;
QueryManager qm;
qm = session.getWorkspace().getQueryManager();
q = qm.createQuery("//*[jcr:like(fn:lower-case(@tags),'%" + str + "%')]", javax.jcr.query.Query.XPATH);
QueryResult result = q.execute();
NodeIterator nodes = result.getNodes();
while (nodes.hasNext()) {
Node nd = (Node) nodes.next();
javax.jcr.Value[] values = null;
try {
values = nd.getProperty("tags").getValues();
} catch (PathNotFoundException e) {
log.error(e.getMessage());
}
catch(ValueFormatException e2) {
log.error(e2.getMessage());
}
if (null != values) {
for (int i = 0; i < values.length; i++) {
String tag = values[i].getString();
if (tag != null && tag.toLowerCase().contains(str.toLowerCase())) {
tags.add(tag);
}
}
}
}
HashSet<String> listToSet = new HashSet<String>(tags);
getAllTagList = new ArrayList<String>(listToSet);
return getAllTagList;
}
}

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment

Popular posts from this blog

Struts2 and Hibernate Example using Annotation

Hi Guys, Today we are going to create an example using Struts2 and Hibernate using Annotation. For the database, we are going to use MySQL. This example will register a record for a user in the mysql database, which later will be used to login to the application. First of all we need to create our database table in MySQL. Log into your mysql database and type the following command to create a database in the mysql prompt. create database mydb; Use the above created database to create table. use mydb; Now we need to create a database table named "users". create table users( uid int primary key auto_increment, uname char(15), password char(20), email char(20), phone long, city char(15)); Now to create this application, we are going to use eclipse. Open your eclipse and create a dynamic web project. Put the following jars related to Struts2 and Hibernate in the WEB-INF/lib folder Now create the following packages in the src folder for the ...

Java program to create staircase

Observe that its base and height are both equal to  , and the image is drawn using  #  symbols and spaces.  The last line is not preceded by any spaces. Write a program that prints a staircase of size  . Input Format A single integer,  , denoting the size of the staircase. Output Format Print a staircase of size   using  #  symbols and spaces. Note : The last line must have   spaces in it. package com.rohan.test; import java.util.Scanner; public class StaircaseTest {     public static void main(String[] args) {         Scanner in = new Scanner(System.in);         int n = in.nextInt();                  for(int i = 0; i< n; i++) {         for(int k = 0; k < n; k++) {         if(k < n-i-1)         System.out.p...

Java program to print the maximum hourglass value of the matrix

Context   Given a    2D Array ,  : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in   to be a subset of values with indices falling in this pattern in  's graphical representation: a b c d e f g There are   hourglasses in  , and an  hourglass sum  is the sum of an hourglass' values. Task   Calculate the hourglass sum for every hourglass in  , then print the  maximum  hourglass sum. Note:  If you have already solved the Java domain's  Java 2D Array  challenge, you may wish to skip this challenge. Input Format There are   lines of input, where each line contains   space-separated integers describing  2D Array   ; every value in   will be in the inclusive range of   to  . Constraints Output Format Print the largest (maximum) hourglass sum f...