给出上诉实例代码
时间: 2023-12-19 07:05:51 浏览: 84
非常抱歉,上述实例代码是错误的,我理解错了你的问题。下面是一个简单的JavaEE登录界面的实例代码,仅供参考:
login.jsp 页面:
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form action="loginServlet" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
```
LoginServlet.java Servlet:
```
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "admin".equals(password)) {
// 登录成功,保存用户信息到Session中
HttpSession session = request.getSession();
session.setAttribute("username", username);
// 跳转到主页或其他页面
response.sendRedirect("home.jsp");
} else {
// 登录失败,跳转回登录页面并给出错误提示
response.sendRedirect("login.jsp?error=1");
}
}
}
```
home.jsp 主页:
```
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<h1>Welcome <%= session.getAttribute("username") %></h1>
<a href="logoutServlet">Logout</a>
</body>
</html>
```
LogoutServlet.java Servlet:
```
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/logoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate(); // 销毁Session
response.sendRedirect("login.jsp");
}
}
```
上述代码实现了一个简单的JavaEE登录界面,包括登录页面、登录处理Servlet、主页和退出登录Servlet。其中登录处理Servlet负责验证用户输入的用户名和密码,如果验证通过则保存用户信息到Session中并跳转到主页,否则返回登录页面并给出错误提示。主页展示用户信息并提供退出登录功能。
阅读全文