Asked  7 Months ago    Answers:  5   Viewed   71 times

Suppose I am having three dropdownlist controls named dd1, dd2 and dd3. The value of each dropdownlist comes from database. dd3's value depends upon value of dd2 and dd2's value depends on value of dd1. Can anyone tell me how do I call servlet for this problem?

 Answers

70

There are basically three ways to achieve this:

  1. Submit form to a servlet during the onchange event of the 1st dropdown (you can use Javascript for this), let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database as a Map<String, String>, let it store them in the request scope. Finally let JSP/JSTL display the values in the 2nd dropdown. You can use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach tag for this. You can prepopulate the 1st list in the doGet() method of the Servlet associated with the JSP page.

     <select name="dd1" onchange="submit()">
         <c:forEach items="${dd1options}" var="option">
             <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
         </c:forEach>
     </select>
     <select name="dd2" onchange="submit()">
         <c:if test="${empty dd2options}">
             <option>Please select parent</option>
         </c:if>
         <c:forEach items="${dd2options}" var="option">
             <option value="${option.key}" ${param.dd2 == option.key ? 'selected' : ''}>${option.value}</option>
         </c:forEach>
     </select>
     <select name="dd3">
         <c:if test="${empty dd3options}">
             <option>Please select parent</option>
         </c:if>
         <c:forEach items="${dd3options}" var="option">
             <option value="${option.key}" ${param.dd3 == option.key ? 'selected' : ''}>${option.value}</option>
         </c:forEach>
     </select>
    

    Once caveat is however that this will submit the entire form and cause a "flash of content" which may be bad for User Experience. You'll also need to retain the other fields in the same form based on the request parameters. You'll also need to determine in the servlet whether the request is to update a dropdown (child dropdown value is null) or to submit the actual form.

  2. Print all possible values of the 2nd and 3rd dropdown out as a Javascript object and make use of a Javascript function to fill the 2nd dropdown based on the selected item of the 1st dropdown during the onchange event of the 1st dropdown. No form submit and no server cycle is needed here.

     <script>
         var dd2options = ${dd2optionsAsJSObject};
         var dd3options = ${dd3optionsAsJSObject};
         function dd1change(dd1) {
             // Fill dd2 options based on selected dd1 value.
             var selected = dd1.options[dd1.selectedIndex].value;
             ...
         }
         function dd2change(dd2) {
             // Fill dd3 options based on selected dd2 value.
             var selected = dd2.options[dd2.selectedIndex].value;
             ...
         }
     </script>
    
     <select name="dd1" onchange="dd1change(this)">
         <c:forEach items="${dd1options}" var="option">
             <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
         </c:forEach>
     </select>
     <select name="dd2" onchange="dd2change(this)">
         <option>Please select parent</option>
     </select>
     <select name="dd3">
         <option>Please select parent</option>
     </select>
    

    One caveat is however that this may become unnecessarily lengthy and expensive when you have a lot of items. Imagine that you have 3 steps of each 100 possible items, that would mean 100 * 100 * 100 = 1,000,000 items in JS objects. The HTML page would grow over 1MB in length.

  3. Make use of XMLHttpRequest in Javascript to fire an asynchronous request to a servlet during the onchange event of the 1st dropdown, let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database, return it back as XML or JSON string. Finally let Javascript display the values in the 2nd dropdown through the HTML DOM tree (the Ajax way, as suggested before). The best way for this would be using jQuery.

     <%@ page pageEncoding="UTF-8" %>
     <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
     <!DOCTYPE html>
     <html lang="en">
         <head>
             <title>SO question 2263996</title>
             <script src="http://code.jquery.com/jquery-latest.min.js"></script>
             <script>
                 $(document).ready(function() {
                     $('#dd1').change(function() { fillOptions('dd2', this); });
                     $('#dd2').change(function() { fillOptions('dd3', this); });
                 });
                 function fillOptions(ddId, callingElement) {
                     var dd = $('#' + ddId);
                     $.getJSON('json/options?dd=' + ddId + '&val=' + $(callingElement).val(), function(opts) {
                         $('>option', dd).remove(); // Clean old options first.
                         if (opts) {
                             $.each(opts, function(key, value) {
                                 dd.append($('<option/>').val(key).text(value));
                             });
                         } else {
                             dd.append($('<option/>').text("Please select parent"));
                         }
                     });
                 }
             </script>
         </head>
         <body>
             <form>
                 <select id="dd1" name="dd1">
                     <c:forEach items="${dd1}" var="option">
                         <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
                     </c:forEach>
                 </select>
                 <select id="dd2" name="dd2">
                     <option>Please select parent</option>
                 </select>
                 <select id="dd3" name="dd3">
                     <option>Please select parent</option>
                 </select>
             </form>
         </body>
     </html>
    

    ..where the Servlet behind /json/options can look like this:

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         String dd = request.getParameter("dd"); // ID of child DD to fill options for.
         String val = request.getParameter("val"); // Value of parent DD to find associated child DD options for.
         Map<String, String> options = optionDAO.find(dd, val);
         String json = new Gson().toJson(options);
         response.setContentType("application/json");
         response.setCharacterEncoding("UTF-8");
         response.getWriter().write(json);
     }
    

    Here, Gson is Google Gson which eases converting fullworthy Java objects to JSON and vice versa. See also How to use Servlets and Ajax?

Tuesday, June 1, 2021
 
EurekA
answered 7 Months ago
51

Assuming that you've the model and DB part already finished (as per the comments on the question), just create a servlet class and implement the doGet() method accordingly. It's relatively simple, just retrieve the list of passengers from the DB, store it in request scope and forward to the JSP which should present it. The below example assumes that you're using EJB/JPA as service/DB layer, but whatever service/DB layer you use, you should ultimately end up getting a List<Passenger> from it anyway.

@WebServlet("/passengers")
public class Passengers extends HttpServlet {

    @EJB
    private PassengerService service;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Passenger> passengers = service.list();
        request.setAttribute("passengers", passengers);
        request.getRequestDispatcher("/WEB-INF/passengers.jsp").forward(request, response);
    }

}

Create a JSP file /WEB-INF/passengers.jsp which uses JSTL <c:forEach> to iterate over it, printing a new HTML <option> everytime:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="passenger">
    <c:forEach items="${passengers}" var="passenger">
        <option value="${passenger.id}"><c:out value="${passenger.name}" /></option>
    </c:forEach>
</select>

(this example assumes the Passenger entity to have id and name properties)

That should basically be it. Just open the page by invoking the servlet's URL like so http://example.com/contextpath/passengers.

See also:

  • doGet and doPost in Servlets
  • Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
  • Populating cascading dropdown lists in JSP/Servlet
Tuesday, June 1, 2021
 
saad
answered 7 Months ago
62

To begin with, inside a jQuery event handler function this refers to the element that triggered the event, so you can replace the additional calls to $("select#CountryID") with $(this). Though where possible you should access element properties directly, rather than using the jQuery functions, so you could simply do this.value rather than $(this).val() or $("select#CountryID").val().

Then, inside your AJAX calls success function, you need to create a series of <option> elements. That can be done using the base jQuery() function (or $() for short). That would look something like this:

$.ajax({
    success: function(states) {
        // states is your JSON array
        var $select = $('#StateID');
        $.each(states, function(i, state) {
            $('<option>', {
                value: state.stateId
            }).html(state.StateName).appendTo($select);
        });
    }
});

Here's a jsFiddle demo.

Relevant jQuery docs:

  • jQuery.each()
  • jQuery()
Saturday, July 3, 2021
 
redrom
answered 5 Months ago
77

The trouble is that you're not initializing the row. It's easily fixed:

cols = 5;
rows = 10;

front = new Array(cols)// .fill(new Array(rows));

// Loop through Initial array to randomly place cells
for(var x = 0; x < cols; x++){
  front[x] = [];  // ***** Added this line *****
  for(var y = 0; y < rows; y++){
    front[x][y] = Math.floor(Math.random()*5);
  }
}
console.table(front) ; // browser console only, not StackOverflow's

Update

This is a cleaner version, somewhat similar to the one from Code Maniac, but simplified a bit:

const randomTable = (rows, cols) => Array.from(
  {length: rows}, 
  () => Array.from({length: cols}, () => Math.floor(Math.random() * 5))
)

console.table(randomTable(10, 5)) // browser console only, not StackOverflow's
Saturday, August 21, 2021
 
Steve
answered 4 Months ago
11

Given the amended html mark-up:

<form action="#" method="post">
    <select id="searchType">
        <option value="sessions">Sessions</option>
        <option value="files">Files</option>
        <option value="clients">Clients</option>
    </select>

    <select id="sessions">
        <option value="conf">Config ID</option>
        <option value="length">Length</option>
        <option value="date">Date</option>
    </select>

    <select id="files">
        <option value="id">File ID</option>
        <option value="length">Length</option>
        <option value="sent">Sent</option>
        <option value="sessionId">Session ID</option>
    </select>

    <select id="clients">
        <option value="name">Client Name</option>
        <option value="organization">Organization</option>
        <option value="specialty">Specialty</option>
        <option value="sessionId">Session ID</option>
    </select>

    <fieldset id="textAreaSearchBox">
        <legend>Search:</legend>
        <textarea></textarea>
    </fieldset>
</form>

(Note the changed ids, wrapping the form elements in a form, the addition of a fieldset, legend and textarea in the mark-up), the following JavaScript seems to work:

var select1 = document.getElementById('searchType');
var selects = document.getElementsByTagName('select');

select1.onchange = function() {
    var select2 = this.value.toLowerCase();
    for (i = 0; i < selects.length; i++) {
        if (selects[i].id != this.id) {
            selects[i].style.display = 'none';
        }
    }
    document.getElementById(select2).style.display = 'block';
    document.getElementById('textAreaSearchBox').style.display = 'block';
};

JS Fiddle demo.

Friday, August 27, 2021
 
nika
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share