How to read values from query string and set values in multiple select dropdown in JSP?

Viewed 55

I am trying to get values from query string coming from http servlet request in JSP. Like this,

http://localhost:8080/admin/createlisting?maincategory=1&category=1,4,5,7

Now, I want to get category value from this query string. category=1,4,5,7 is basically category ID and according to this category ID, I want to set value in multiselect dropdown.

That is, whenever page opens multiselect dropdown values should be displayed as per category ID. This is my createlisting.jsp page and I extracted category value from query string like below:

<%
  String category[] = null;
  if (null != request.getParameterValues("category")) {
    category = request.getParameterValues("category");
  }
  for(int i = 0; i < category.length; i++){
    System.out.println("Category ID elements : "+category[i]);
  }
%>

<div class="col-md-6">
    <div class="form-group">
        <label for="">Select Category</label>
            <select class="form-control js-example-tokenizer" multiple="multiple" id="category" required style='display: none;'></select>
    </div>
</div>

screenshot of dropdown

1 Answers

Consider this JSP.

<%
    String[] category = request.getParameterValues("category");
    if (category != null) {
        for(int i = 0; i < category.length; i++){
            out.print("array element " + i + ": " + category[i] + " ");
        }
    } else {out.print("category was null");}
%>

If you call it with the following query string

?category=1,4,5,7 

then the output will be

array element 0: 1,4,5,7

If you call it with the following query string

?category=1&category=4&category=5&category=7

then the output will be array element 0: 1 array element 1: 4 array element 2: 5 array element 3: 7

Related