您没有将某些内容传递给servlet.你只需让servlet访问一些东西.
您应该摆脱main()方法并将数据库交互代码移动到DAO类中.我还给模型类(带有时区和位置)一个以大写字母开头的更敏感的名称.总而言之,您应该更新代码,使其看起来如下所示:
模型类,区域(只要它有意义,任意你想要的名称),它应该只代表一个实体:
public class Area {
private String location;
private String timezone;
public String getLocation() { return location; }
public String getTimezone() { return timezone; }
public void setLocation(String location) { this.location = location; }
public void setTimezone(String timezone) { this.timezone = timezone; }
}
基本连接管理器类,数据库,这里只加载驱动程序一次,并为连接提供一个getter:
public class Database {
private String url;
private String username;
private String password;
public Database(String driver, String url, String username, String password) {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Driver class is missing in classpath", e);
}
this.url = url;
this.username = username;
this.password = password;
}
public Connection getConnection() {
return DriverManager.getConnection(url, username, password);
}
}
DAO类,AreaDAO,这里放置所有数据库交互方法:
public class AreaDAO {
private Database database;
public AreaDAO(Database database) {
this.database = database;
}
public List list() throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List areas = new ArrayList();
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT location, timezone FROM userclient");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Area area = new Area();
area.setLocation(resultSet.getString("location"));
area.setTimezone(resultSet.getString("timezone"));
areas.add(area);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return areas;
}
}
最后,在servlet中初始化DAO一次并获取HTTP方法中的列表:
public class AreaServlet extends HttpServlet {
private AreaDAO areaDAO;
public void init() throws ServletException {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/dbname";
String username = "user";
String password = "pass";
Database database = new Database(driver, url, username, password);
this.areaDAO = new AreaDAO(database);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List areas = areaDAO.list();
request.setAttribute("areas", areas);
request.getRequestDispatcher("/WEB-INF/areas.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot retrieve areas", e);
}
}
}
将此servlet映射到web.xml中的/ areas区域的url-pattern上,以便您可以在http://example.com/contextname/areas之前调用它
/WEB-INF/areas.jsp看起来像这样,假设您要显示表中的区域:
${area.location} | ${area.timezone} |
也可以看看: