When you come across a requirement of auto-complete feature like google search,

ex:- when you search for the particular employee name you need to fetch all employee names which will match or start with the particular character or word. The below code will help you to achieve that requirement.

jsp code :-

//created the resource URL to hit the serveResource method.

 

// Input field where you need to enter the characters of employee name for example

 

// script code to perform auto complete feature.

Note :-
we can get the values in different ways of matching scenarios depending upon the value given to the ” resultFilters ”
charMatch: gives the results that contain all of the individual characters in the query, in any order (not necessarily consecutive).
phraseMatch: gives the results that contain the complete query as a phrase.
startsWith: gives the results that start with the complete query as a phrase.
subWordMatch: gives the results in which all the words of the query match either whole words or parts of words in the result. Non-word characters like whitespace and certain punctuation are ignored.
wordMatch: gives the results that contain all the individual words in the query, in any order (not necessarily consecutive).
ex:-
resultFilters: [‘charMatch’, ‘wordMatch’]

java code :- This code should be write in the Action class of your portlet.

import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

import java.io.PrintWriter;

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse
resourceResponse) throws IOException, PortletException {
_log.info(“Starting of Serve Resource Method”);
getResults(resourceRequest,resourceResponse);
_log.info(“Exit of Serve Resource Method”);
}

public void getResults(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
PrintWriter out;
JSONArray usersJSONArray = JSONFactoryUtil.createJSONArray();
JSONObject userJSON=null;
String mystring = StringPool.BLANK;
try {
List list=MLocalServiceUtil.getM(0,MLocalServiceUtil.getMCount());
for(M mobj:list){
mystring= “result values”; userJSON=JSONFactoryUtil.createJSONObject();
userJSON.put(“result”,mystring);
usersJSONArray.put(userJSON);
}
out = resourceResponse.getWriter();
out.println(usersJSONArray.toString());
}
catch (SystemException e) {
}
catch (IOException e) {
}
}

Leave a Reply