怎么用Java写一个有登录页面进去后跳转到个人记账本页面的代码
时间: 2024-03-06 09:48:16 浏览: 22
好的,以下是一个简单的Java Web应用程序示例,该程序包含登录页面和个人记账本页面。当用户登录成功后,会跳转到个人记账本页面。
首先,我们需要创建一个名为`LoginServlet`的Java Servlet类,用于处理用户登录请求。该类的代码如下:
```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;
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")) {
// 验证成功,将用户信息保存到Session中
request.getSession().setAttribute("username", username);
// 跳转到个人记账本页面
response.sendRedirect(request.getContextPath() + "/account.jsp");
} else {
// 验证失败,返回登录页面
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
}
}
```
在该类中,我们首先从`HttpServletRequest`对象中获取用户提交的用户名和密码,然后对其进行验证。如果验证成功,我们将用户信息保存到`Session`中,并使用`HttpServletResponse`对象的`sendRedirect`方法将用户重定向到个人记账本页面;如果验证失败,则将用户重定向到登录页面。
接下来,我们需要创建一个名为`login.jsp`的JSP页面,用于显示登录表单。该页面的代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/login">
<label for="username">用户名:</label>
<input type="text" id="username" name="username"><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
在该页面中,我们使用`<form>`元素定义一个登录表单,其中`action`属性指定了表单提交的目标URL,即`LoginServlet`类的URL;`method`属性指定了表单提交的HTTP方法,即`POST`方法。表单中包含两个输入框,分别用于输入用户名和密码,以及一个提交按钮。
最后,我们需要创建一个名为`account.jsp`的JSP页面,用于显示个人记账本页面。该页面的代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>个人记账本</title>
</head>
<body>
<h1>欢迎您,${sessionScope.username}!</h1>
<p>这里是您的个人记账本页面。</p>
</body>
</html>
```
在该页面中,我们使用`${sessionScope.username}`表达式获取保存在`Session`中的用户名,并显示在页面中。
以上就是一个简单的Java Web应用程序示例,包含登录页面和个人记账本页面。请注意,该示例仅供参考,实际实现中还需要考虑安全性等方面的问题。