JSP(JavaServer Pages)是一种用于创建动态Web内容的技术,它允许开发者将Java代码嵌入到HTML页面中,从而实现服务器端的动态处理。下面是一个简单的JSP登录界面的示例代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录界面</title>
<style>
body {
font-family: Arial, sans-serif;
}
.login-container {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
}
.form-group input[type="text"],
.form-group input[type="password"] {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.btn-login {
width: 100%;
padding: 10px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
.btn-login:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<div class="login-container">
<h2>用户登录</h2>
<form action="loginProcess.jsp" method="post">
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
</div>
<button type="submit" class="btn-login">登录</button>
</form>
</div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
定义了页面的语言、内容类型和字符编码。<head>
和<body>
部分。action
属性指向处理登录请求的JSP页面(例如loginProcess.jsp
)。<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录处理</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
// 假设数据库连接信息
String url = "jdbc:mysql://localhost:3306/mydatabase";
String dbUsername = "root";
String dbPassword = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
out.println("登录成功!");
} else {
out.println("用户名或密码错误!");
}
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
out.println("数据库连接失败:" + e.getMessage());
}
%>
</body>
</html>
通过以上代码,你可以创建一个基本的JSP登录界面,并处理用户的登录请求。如果遇到具体问题,可以根据错误信息进一步调试和优化。
领取专属 10元无门槛券
手把手带您无忧上云