目前我正在构建一个汽车租赁应用程序,并且我一直致力于使这个数组列表能够存储所有对象属性并将其推送到数组。我有一个 java bean `package com.rental.models;
public class Car {
private String Id;
private String Year;
private String Make;
private String Model;
private String Color;
private String Available;
public Car() {
super();
}
public String getYear() {
return Year;
}
public void setYear(String year) {
Year = year;
}
public String getMake() {
return Make;
}
public void setMake(String make) {
Make = make;
}
public String getModel() {
return Model;
}
public void setModel(String model) {
Model = model;
}
public String getColor() {
return Color;
}
public void setColor(String color) {
Color = color;
}
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getAvailable() {
return Available;
}
public void setAvailable(String available) {
Available = available;
}
}
和 bean 结果列表,`package com.rental.models;
import java.util.List;
public class CarData {
private List<Car> cars;
public CarData() {
super();
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
}
最后,这是我所坚持的代码。
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
List<Car> cars;
ResultSet rs =null;
Connection conn = null;
Statement st= null;
try {
Context ctx = new InitialContext();
Context env = ( Context )ctx.lookup( "java:comp/env" );
DataSource ds = ( DataSource )env.lookup( "jdbc/carRentalSystem");
conn = ds.getConnection();
st= conn.createStatement();
rs= st.executeQuery("SELECT * FROM carrdetails" );
if(rs.next()) {
Car car = new Car();
car.setId("id");
car.setYear("Year");
car.setMake("Make");
car.setModel("model");
car.setColor("Color");
car.setAvailable("Availability");
cars.add(car);
return cars;
}
} catch(Exception e) {
System.out.println(e);
}
finally {
try{ if(st != null ) st.close(); } catch(java.sql.SQLException e){}
try{ if(conn != null ) conn.close(); } catch(java.sql.SQLException e){}
try{ if(rs != null) rs.close(); } catch(java.sql.SQLException e){}
}
最佳答案
我犯了一个错误,就是将此实例推送到我正在使用的 JSP 中。但它正在工作。
关于java - 使用Java在mySQL中查询当前数据库表,构建对象列表并将它们显示在页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46525285/