jsp+mysql写出一个登录判断
时间: 2024-01-14 11:02:23 浏览: 19
以下是一个基本的 JSP 和 MySQL 登录判断示例:
```jsp
<%@page import="java.sql.*"%>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String pass = "password";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pass);
stmt = conn.createStatement();
String sql = "SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'";
rs = stmt.executeQuery(sql);
if (rs.next()) {
// 登录成功,跳转到首页或其他需要登录验证的页面
response.sendRedirect("index.jsp");
} else {
// 登录失败,跳转回登录页面或给出错误提示信息
out.println("<script>alert('用户名或密码错误!');window.location.href='login.jsp';</script>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
%>
```
该示例中,首先获取用户输入的用户名和密码,然后使用 JDBC 连接到 MySQL 数据库,查询是否存在该用户,如果存在则登录成功,跳转到首页或其他需要登录验证的页面,否则登录失败,跳转回登录页面或给出错误提示信息。需要注意的是,为了避免 SQL 注入攻击,应该使用 PreparedStatement 或其他方式来代替直接拼接 SQL 语句中的参数。