Wednesday, 14 December 2016

Dependent DropDown Select Box in Servlet & JSP


index.jsp

<html>
<head>
<title>AJAX in Servlet using JQuery and JSON</title>
<script src="js/jquery-1.11.1.js" type="text/javascript"></script>

<script>
$(document).ready(function() {

$('#sports').change(function(event) {
var sports = $("select#sports").val();
$.get('JsonServlet', {
sportsName : sports
}, function(jsonResponse) {

var select = $('#player');
select.find('option').remove();
   $.each(jsonResponse, function(index, value) {
 $('<option>').val(value).text(value).appendTo(select);
      });
});
});
});

</script>
</head>
<body>
<h3>AJAX in Servlet using JQuery and JSON</h3>
Select Favorite Sports:
<select id="sports">
<option>Select Sports</option>
<option value="Football">Football</option>
<option value="Cricket">Cricket</option>
</select>
<br /> <br />
Select Favorite Player:
<select id="player">
<option>Select Player</option>
</select>
</body>
</html>


JsonServlet.java

package com.action;

import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;

public class JsonServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

String sportsName = request.getParameter("sportsName");
List<String> list = new ArrayList<String>();
String json = null;

if (sportsName.equals("Football")) {
list.add("Lionel Messi");
list.add("Cristiano Ronaldo");
}
                else if (sportsName.equals("Cricket")) {
list.add("MSD");
list.add("Virat");
list.add("Sachin");
list.add("Kapil");
} else if (sportsName.equals("Select Sports")) {
list.add("Select Player");
}

json = new Gson().toJson(list);
response.setContentType("application/json");
response.getWriter().write(json);
}
}


Output:




No comments:

Post a Comment