JSP is just server side view technology. It does not compete with jQuery. You can perfectly use JSP for this. But I understand that you want to run an asynchronous request using ajaxial methods, not a synchronous request. This is also not a problem in JSP.
First, we need to have two dropdown menus in the JSP:
<select id="dropdown1"> <c:forEach items="#{bean.items}" var="item"> <option value="#{item.value}">#{item.label}</option> </c:forEach> </select> <select id="dropdown2"> <option>Please select dropdown1</option> </select>
Then we need to attach some jQuery to the change event so that it populates the second drop-down menu based on the value of the 1st drop-down list. Add the following to <script> in the JSP or an external script that loads through <script src> in the JSP:
$(document).ready(function() { $('#dropdown1').change(function() { var selectedValue = $(this).val(); var servletUrl = 'dropdown2options?value=' + selectedValue; $.getJSON(servletUrl, function(options) { var dropdown2 = $('#dropdown2'); $('>option', dropdown2).remove();
In the servlet for url-pattern of /dropdown2options just return the parameter map as JSON . You can use gson for this.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String selectedValue = request.getParameter("value"); Map<String, String> options = optionDAO.find(selectedValue); String json = new Gson().toJson(options); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); }
That is basically all.
Balusc
source share