session与severlet实现数据库连接事例
时间: 2023-12-17 13:04:46 浏览: 81
以下是一个使用Servlet和Session实现数据库连接的示例:
1. 创建一个名为`DatabaseConnection`的Java类,该类用于连接数据库并执行SQL查询。
```java
public class DatabaseConnection {
private Connection conn;
public DatabaseConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "root";
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public ResultSet executeQuery(String sql) throws SQLException {
Statement stmt = conn.createStatement();
return stmt.executeQuery(sql);
}
}
```
2. 创建一个名为`LoginServlet`的Servlet类,该类用于处理用户登录请求,并从数据库中验证用户。
```java
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
DatabaseConnection conn = new DatabaseConnection();
String sql = "SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'";
ResultSet rs = null;
try {
rs = conn.executeQuery(sql);
if (rs.next()) {
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
3. 创建一个名为`WelcomeServlet`的Servlet类,该类用于处理用户登录后的请求,并从Session中获取用户名。
```java
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
response.getWriter().println("Welcome, " + username + "!");
}
}
```
在这个示例中,`LoginServlet`从数据库验证用户,并将用户名存储在Session中。`WelcomeServlet`从Session中获取用户名,并在响应中返回欢迎消息。通过这种方式,Servlet和Session共同实现了数据库连接的功能。
阅读全文