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;
}
}
This comment has been removed by a blog administrator.
ReplyDelete