servlet编写网页登录界面
时间: 2023-10-23 13:08:45 浏览: 39
要编写一个基本的网页登录界面,需要以下步骤:
1. 创建一个 HTML 页面,添加一个表单元素,用于用户输入登录信息。
```html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="loginServlet" 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>
```
2. 创建一个 Servlet,用于接收表单数据并验证用户信息。
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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");
// 假设用户名为 "admin",密码为 "admin123"
if (username.equals("admin") && password.equals("admin123")) {
// 如果验证通过,跳转到欢迎页面
response.sendRedirect("welcome.jsp");
} else {
// 如果验证不通过,返回登录页面并显示错误消息
request.setAttribute("errorMessage", "Invalid username or password");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/login.jsp");
dispatcher.forward(request, response);
}
}
}
```
3. 在 web.xml 文件中添加 Servlet 映射。
```xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
```
4. 创建一个欢迎页面 welcome.jsp,用于显示登录成功的消息。
```html
<!DOCTYPE html>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<h2>Welcome</h2>
<p>You have successfully logged in!</p>
</body>
</html>
```
5. 运行应用程序,并在浏览器中访问登录页面。输入用户名和密码后点击登录按钮,如果验证通过,将跳转到欢迎页面。否则将返回登录页面并显示错误消息。