Recently i worked on integrating Select2 plug-in with auto-complete feature of few form fields. Though the documentation is exhaustive, it will be a bit daunting for the first-time user to get it up and running immediately. Therefore i thought of posting a working example of using this plugin for getting remote data.
In below example, we will retrieve remote data from a Java Servlet. This example can be later easily extended by modifying the Servlet to retrieve data from a Data Base.
Step-1:
In below example, we will retrieve remote data from a Java Servlet. This example can be later easily extended by modifying the Servlet to retrieve data from a Data Base.
Step-1:
- Create a dynamic web project named test-app in Eclipse.
- Create a Servlet named DisplayServlet. This servlet is used to present a simple html form containing an input text field.
- To this input text field, we will add the Select2 plug-in. Yes, we can add Select2 plug-in to an 'input text field'. The plug-in will automatically convert it to 'select'.
- Download the select2 plugin from github and include the select2.js and select2.css in corresponding directories (js and css under eclipse project's WebContent directory)
- Include the required jquery plug-in also in js directory under eclipse project's WebContent directory.
- As you can see below, there's another java script with name custom_myselect.js. This is the javascript we will write in which we will call the constructor of select2 for our input text field and point it to another Java Servlet to retrieve remote data. Create this javascript also in the 'js' directory under WebContent. (contents of which are given in Step-2)
package testPackage; import java.io.*; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; /** * A Simple Servlet that has an input text field to which we will * add 'Select2' plug-in for retrieving remote data from another Servlet. * @author phani */ @WebServlet("/DisplayServlet") public class DisplayServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println ("<html>\n" + "<head>\n"+ "<link href=\"css/select2.css\" type=\"text/css\" rel=\"stylesheet\"/>\n"+ "<script type=\"text/javascript\" src=\"js/jquery-1.9.1.js\"></script>\n"+ "<script type=\"text/javascript\" src=\"js/select2.js\"></script>\n"+ "<script type=\"text/javascript\" src=\"js/custom_myselect.js\"></script>\n"+ "</head>\n" + "<body>\n" + "<form id=\"query_form\" name=\"query_form\" method=\"post\" action=\"/test-app/DisplayServlet\">\n" + "<fieldset>"+ "<legend>Search Criteria</legend>"+ "<input type=\"text\" name=\"Student\" value=\"\" id=\"Student\" size=\"30\" title=\"Student name\">\n"+ "</fieldset>"+ "</form>"+ "</body>"+ "</html>"); } }Step-2:
- Integrate select2 for the input text field. We will be doing this in the custom_myselect.js script.
- We will use only the bare minimum options of the select2 plug-in and later add more options.
- As you can see below, select2 is added for input text field (#Student). Few parameters of the constructor are explained in comments.
- Notice the 'ajax' parameter that is used to perform remote requests. The requests are made to the url (i.e another servlet which we will define in Step-3).
- 'json' dataType is used for requests as the target url will be in the same domain. Select2 supports json, jsonp and xml.
- 'data' function is used to generate the query parameters for the ajax request. These parameters are passed to the url (Servlet defined in Step-3 in our example). Important parameter to be noted is 'term'. This name is fixed by the plug-in and is used to pass 'search term' typed by the user. In example below, i have hard-coded another auxiliary parameter (aux_variable) also in the request. Similarly we can retrieve some other values from the html page/form and pass them as parameters.
- 'results' function is used to build the query results from the ajax response.
$(document).ready(function () { $('#Student').select2({ // Initial value that is selected if no other selection is made. placeholder: 'Enter Student ', // multiple selection enabled. multiple: true, ajax: { //How long the user has to pause their typing before sending the next request quietMillis: 150, // The url of the json service url: '/test-app/StudentServlet', dataType: 'json', // term contains the search item data: function (term, page) { return { aux_variable : 'Testing', term: term }; }, results: function (data) { return { results: data }; } } }); });Step-3:
- In this step we will create another servlet (StudentServlet) that will handle the ajax requests coming from select2 plug-in and provides a response back.
- Response back from this Servlet is used to populate the select2 on the html form.
- Response should be 'json' format - Array of JSON objects like below:
[{"text":"Abhijeet"},{"text":"Abhishek"},{"text":"Anurag"},{"text":"Anuj"},{"text":"Gaurav"},{"text":"Subodh"},{"text":"Phani"}]
- gson is a java library is used to convert JSON to java objects and vice-versa.
- Download this jar file and include in your eclipse project's WEB-INF/lib directory. We use it to create the JSON response in the above format required for select2 plug-in to function.
- In the below example, we are just returning same list of students always. In a real-life scenario, the search term (available in the ajax request parameter 'term') and any other parameters sent in the request are used in the Servlet to send the valid response. For example: we can use the incoming value to do a DB search and return those records that start with 'term'.
- Build this project and deploy the war file on your tomcat web server.
package testPackage; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @WebServlet("/StudentServlet") public class StudentServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userInput = request.getParameter("term"); System.out.println(userInput); // We can get auxiliary parameters sent from select2 like below: // request.getParameter("aux_variable"); String json = ""; List<String> studentList = getStudentList(); List<HashMap<String, String>> listOfMapForJSONConv = new ArrayList<HashMap<String,String>>(); for(String s : studentList) { HashMap<String, String> map = new HashMap<String, String>(); map.put("text", s); listOfMapForJSONConv.add(map); } Gson gson = new GsonBuilder().create(); json = gson.toJson(listOfMapForJSONConv); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(json); } private List<String> getStudentList() { List<String> studentList = new ArrayList<String>(); studentList.add("Abhijeet"); studentList.add("Abhishek"); studentList.add("Anurag"); studentList.add("Anuj"); studentList.add("Gaurav"); studentList.add("Subodh"); studentList.add("Phani"); return studentList; } }Step-4:
- Once the war file is deployed successfully, verify the DisplayServlet first. This can be seen by typing "http://localhost:8080/test-app/DisplayServlet" in your browser window. (Assuming you deployed the war file on your 'localhost' and default port of your tomcat web server is 8080).
- You can 'view source' of the web page and make sure all the javascripts and css files are included. If not, then something wrong with your eclipse project setup.
- Now the 'DisplayServlet' should show something like below in the html page:
- And once you click in the input text field, select2 will send the ajax request and displays the results back like below:
- Now this is just bare-bones example and in a separate post i will update some gotchas and important parameters that can be used to modify this select2 plugin.
Please feel free to get back if you notice any errors or any feedback.
No comments:
Post a Comment