使用jsp写一个登录界面,并连接数据库,需要用到mvc架构
时间: 2024-05-07 10:19:15 浏览: 13
好的,下面是一个简单的使用JSP、Servlet和JDBC连接数据库的MVC架构的登录页面代码:
1. Model层 - User类
```java
public class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
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层 - UserDao类
```java
public class UserDao {
public User getUser(String username, String password) {
User user = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
PreparedStatement pstmt = conn.prepareStatement("select * from user where username=? and password=?");
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
user = new User(rs.getString("username"), rs.getString("password"));
}
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
```
3. Controller层 - LoginServlet类
```java
public class LoginServlet extends HttpServlet {
private UserDao userDao = new UserDao();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDao.getUser(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp?error=1");
}
}
}
```
4. View层 - login.jsp
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<% if (request.getParameter("error") != null) { %>
<p style="color: red">Username or password is incorrect!</p>
<% } %>
<form action="login" method="post">
<label>Username:</label><br>
<input type="text" name="username"><br>
<label>Password:</label><br>
<input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
5. View层 - welcome.jsp
```jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome <%=session.getAttribute("user").getUsername()%></h1>
</body>
</html>
```
上面的代码实现了一个简单的登录界面,并连接了MySQL数据库,使用了MVC架构。其中,Model层定义了User类,DAO层定义了UserDao类,Controller层定义了LoginServlet类,View层定义了login.jsp和welcome.jsp两个页面。