java mysql登录系统_JavaEE:JSP+Servlet结合Mysql,实现用户登录系统相关代码
时间: 2024-02-11 20:04:42 浏览: 125
好的,以下是使用JSP+Servlet结合MySQL实现用户登录系统的相关代码,仅供参考:
1. JavaBean类
```
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
```
2. DAO类
```
public class UserDao {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
public UserDao() {
conn = DBUtil.getConnection();
}
public boolean isExist(User user) {
boolean flag = false;
try {
String sql = "select * from userinfo where username=? and password=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
rs = pstmt.executeQuery();
if (rs.next()) {
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(rs, pstmt, conn);
}
return flag;
}
}
```
3. Servlet类
```
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");
User user = new User();
user.setUsername(username);
user.setPassword(password);
UserDao userDao = new UserDao();
if (userDao.isExist(user)) {
response.sendRedirect("/success.jsp");
} else {
response.sendRedirect("/fail.jsp");
}
}
}
```
4. JSP页面
```
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
以上代码是使用JSP+Servlet结合MySQL实现用户登录系统的简单示例,仅供参考。具体实现还需要根据自己的需求进行调整。
阅读全文