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 ...

Single LindedList in C. Program to create, insert, delete, traverse in Single Linked List.

For creating the LinkedList program I have used Linux(ubuntu 12.04) machine. When I was in my college days, I would use the Tourbo C compiler which was easy to use in Windows Type the following command to install the build-essential which create our environment and C  compiler to build and run C programs. This will be enough for our purpose to create C programs. $ sudo apt−get install build−essential SinglyLinkedList.c ----------------------- #include <stdio.h> #include <stdlib.h> /* Linded List is having an element and a pointer which points to the same type of structure. I have type defined a NODE type and given alias as "node". */ typedef struct NODE { int info; struct NODE *next; }node; /* I have created a boolean type which returns 0, 1 and 2 which returns false, true and done respectively. This is basically for return type to be used in the program to return boolean values. */ typedef enum {false, true, done}boolean; /* Now crea...

N-Queens Problem

N-Queens Problem N- queen problem states that if no of queens are placed on a chessboard, then no two queens can attack each other. The following program states the same: package com.backtracking.test; public class QueenProblem { private int[][] chessTable; private int numOfQueens; public QueenProblem(int numOfQueens) { this.chessTable = new int[numOfQueens][numOfQueens]; this.numOfQueens = numOfQueens; } public void solve() { if (setQueens(0)) { printQueens(); } else { System.out.println("There is no solution.."); } } private boolean setQueens(int colIndex) { if (colIndex == numOfQueens) { return true; } for (int rowIndex = 0; rowIndex < numOfQueens; ++rowIndex) { if (isPlaceValid(rowIndex, colIndex)) { chessTable[rowIndex][colIndex] = 1; // Queeen is placed if (setQueens(colIndex + 1)) { return true; } // BACKTRACKING chessTable[rowIndex][colI...