java创建用户连接数据库,用数据库密码和账号登录,登录成功后进入showAllProducts页面,写出dao,service,se
时间: 2024-03-09 16:46:21 浏览: 60
java 连接数据库实现用户登录功能
rvlet的代码。
首先是DAO层的代码,用于访问数据库:
```java
public class ProductDAO {
private final String url = "jdbc:mysql://localhost/mydatabase";
private final String username = "myusername";
private final String password = "mypassword";
public List<Product> getAllProducts() {
List<Product> products = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(url, username, password)) {
String sql = "SELECT * FROM products";
try (Statement stmt = conn.createStatement()) {
try (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"));
products.add(product);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return products;
}
}
```
接着是Service层的代码,用于处理业务逻辑:
```java
public class ProductService {
private ProductDAO productDAO = new ProductDAO();
public List<Product> getAllProducts() {
return productDAO.getAllProducts();
}
}
```
最后是Servlet层的代码,用于接收请求和返回响应:
```java
@WebServlet("/showAllProducts")
public class ShowAllProductsServlet extends HttpServlet {
private ProductService productService = new ProductService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Product> products = productService.getAllProducts();
req.setAttribute("products", products);
req.getRequestDispatcher("/WEB-INF/jsp/showAllProducts.jsp").forward(req, resp);
}
}
```
在这个例子中,Servlet接收GET请求,调用Service层的方法获取所有的产品,然后将其存储在请求属性中,并将请求转发到JSP页面以显示所有产品的列表。
阅读全文