所以我正在创建一个使用jsp和servlet租用汽车应用程序的示例。向用户显示所有汽车制造的下拉列表。当用户从make中选择一个选项时,它将根据make向用户显示特定的模型。我从mysql数据库获取所有的make和model值。我能够一起显示所有品牌和型号值,但我不知道如何根据make选项显示模型选项。在线研究后,我发现你必须使用javascript,但我没有看到javascript从数据库中获取数据的例子。 到目前为止,这是我的代码:
JSP
请选择您的车辆类型
<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");
}
}
数据库服务
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;
}
}