So I am creating a sample rent a car application using jsp and servlet. The user is shown a drop down list of all the cars make. When the user selects an option from the make, it will then show thee user the specific models based on the make. I am getting all the make and model values from mysql database. I am able to show all the make and model value together but I am not sure how to show the model option based on the make option. After researching online, I found that you have to use javascript but I don't see an example where javascript gets the data from the database. Here is my code so far:
JSP
Rent A Car
Please select your type of vehicle
<form name="rentForm" action="RentACar" method="post">
Car Make: <select name="carMake">
<%
ArrayList<String> getMake = (ArrayList) request.getAttribute("make");
for(int i = 0; i < getMake.size(); i++)
{
out.println("<option value=\"" + getMake.get(i) + "\">" + getMake.get(i) + "</option>");
}
%>
</select>
Car Model: <select name="carModel">
<%
ArrayList<String> getModel = (ArrayList) request.getAttribute("model");
for(int i = 0; i < getMake.size(); i++)
{
out.println("<option value=\"" + getModel.get(i) + "\">" + getModel.get(i) + "</option>");
}
%>
</select>
</form>
</body>
</html>
Servlet
public class RentACar extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ArrayList<String> vehicleMake = RentService.getMake();
request.setAttribute("make", vehicleMake);
ArrayList<String> vehicleModel = RentService.getModel(model);
request.setAttribute("model", vehicleModel);
RequestDispatcher dispatcher = request.getRequestDispatcher("rent-car.jsp");
dispatcher.forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String model = request.getParameter("carMake");
}
}
Database Service
public class RentService
{
public static ArrayList<String> getMake()
{
ArrayList<String> vehicleList = new ArrayList<>();
String make = "";
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT make FROM Vehicles";
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
make = rs.getString("make");
vehicleList.add(make);
}
}
catch (Exception e)
{
System.out.println(e);
}
return vehicleList;
}
public static ArrayList<String> getModel(String carMake)
{
ArrayList<String> modelList = new ArrayList<>();
String model = "";
try
{
Connection conn = DBConnection.getConnection();
String query = "SELECT model FROM Vehicles WHERE make=? ";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, carMake);
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
model = rs.getString("model");
modelList.add(model);
}
}
catch (Exception e)
{
System.out.println(e);
}
return modelList;
}
}