javaweb 小代码
时间: 2023-08-09 18:04:52 浏览: 129
以下是一个简单的 JavaWeb 代码示例,实现了一个简单的登录页面:
index.html:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h2>Login Page</h2>
<form action="login" method="post">
<label>Username:</label>
<input type="text" name="username"><br>
<label>Password:</label>
<input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
LoginServlet.java:
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("admin") && password.equals("123456")) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("error.html");
}
}
}
```
welcome.jsp:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome Page</title>
</head>
<body>
<h2>Welcome, admin!</h2>
</body>
</html>
```
error.html:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Error Page</title>
</head>
<body>
<h2>Invalid username or password!</h2>
<a href="index.html">Back to login page</a>
</body>
</html>
```
在此示例中,当用户提交表单时,LoginServlet.java 会接收到请求并检查用户名和密码是否匹配。如果匹配,则重定向到 welcome.jsp 页面,否则重定向到 error.html 页面。这是一个非常简单的示例,但可以帮助您了解如何在 JavaWeb 中编写代码。
阅读全文