详述servlet层如何通过session获取数据库的信息,并且举出实例代码
时间: 2024-02-21 08:01:02 浏览: 25
在Servlet层中,我们可以通过Session对象获取连接数据库所需要的信息,比如数据库的URL、用户名、密码等。以下是一个简单的例子:
假设我们有一个名为LoginServlet的Servlet,用于用户登录。在用户登录成功后,我们需要将用户的信息保存在Session中。同时,我们需要在后续的操作中使用到数据库的连接信息。那么,我们可以在LoginServlet中获取数据库连接信息,并将其保存在Session中。具体代码如下:
```java
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
// 验证用户是否合法,如果合法,则将用户信息保存在Session中
if (isValidUser(username, password)) {
HttpSession session = request.getSession();
session.setAttribute("username", username);
// 获取数据库连接信息,并将其保存在Session中
String dbUrl = "jdbc:mysql://localhost:3306/mydatabase";
String dbUsername = "root";
String dbPassword = "123456";
session.setAttribute("dbUrl", dbUrl);
session.setAttribute("dbUsername", dbUsername);
session.setAttribute("dbPassword", dbPassword);
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
}
// 验证用户是否合法
private boolean isValidUser(String username, String password) {
// 请根据实际情况进行实现
return true;
}
}
```
在上面的代码中,我们获取到了Session对象,并使用setAttribute()方法将数据库连接信息保存在Session中。在后续的操作中,我们可以通过getAttribute()方法来获取Session中保存的连接信息。例如,我们可以编写一个名为ProductServlet的Servlet,用于查询数据库中的产品信息。具体代码如下:
```java
@WebServlet("/product")
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String dbUrl = (String) session.getAttribute("dbUrl");
String dbUsername = (String) session.getAttribute("dbUsername");
String dbPassword = (String) session.getAttribute("dbPassword");
// 获取数据库连接
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 查询数据库中的产品信息
List<Product> productList = new ArrayList<Product>();
try {
Statement stmt = conn.createStatement();
String sql = "select * from product";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Product product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getDouble("price"));
productList.add(product);
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 将产品信息保存在request中,并跳转到显示产品信息的页面
request.setAttribute("productList", productList);
request.getRequestDispatcher("product.jsp").forward(request, response);
}
}
```
在上面的代码中,我们首先获取了Session对象,并使用getAttribute()方法获取了数据库连接信息。然后,我们根据连接信息获取数据库连接。最后,我们查询了数据库中的产品信息,并将其保存在request中,然后跳转到显示产品信息的页面。