在Java中實現網頁登錄,可以使用Java Web技術,如Servlet、JSP、HTML、CSS、JavaScript等。
以下是一種簡單的實現方式:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登錄頁面</title>
</head>
<body>
<form action="login" method="post">
<label for="username">用戶名:</label>
<input type="text" id="username" name="username">
<label for="password">密碼:</label>
<input type="password" id="password" name="password">
<input type="submit" value="登錄">
</form>
</body>
</html>
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;
@WebServlet("/login")
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) && "123456".equals(password)) {
// 登錄成功,跳轉到歡迎頁面
response.sendRedirect("welcome.jsp");
} else {
// 登錄失敗,跳轉到錯誤頁面
response.sendRedirect("error.jsp");
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>歡迎頁面</title>
</head>
<body>
<h1>登錄成功!歡迎您,admin!</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>錯誤頁面</title>
</head>
<body>
<h1>登錄失敗!用戶名或密碼錯誤!</h1>
</body>
</html>
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>trimSpaces</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>compilerSourceVM</param-name>
<param-value>1.8</param-value>
</init-param>
<init-param>
<param-name>compilerTargetVM</param-name>
<param-value>1.8</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
以上是一種簡單的實現方式,當用戶在登錄頁面輸入用戶名和密碼后,點擊登錄按鈕,請求會提交到LoginServlet,LoginServlet會根據用戶輸入的用戶名和密碼進行驗證,如果驗證成功,跳轉到歡迎頁面,否則跳轉到錯誤頁面。