Javaweb链接mysql进行登录验证jsp代码
时间: 2023-06-04 07:06:25 浏览: 66
好的,我可以回答这个问题。在Javaweb中,连接MySQL进行登录验证的jsp代码可以类似下面这样:
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select * from users where username=? and password=?";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "123456");
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
if (rs.next()) {
// 登录成功,跳转到主页
response.sendRedirect("index.jsp");
} else {
// 登录失败,跳转回登录页
response.sendRedirect("login.jsp");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
%>
当用户在登录页面输入账号和密码后,这段代码会将其传入对应的参数中,然后使用MySQL中的用户名和密码查询语句进行验证。如果查询结果中有对应的记录,表示登录成功,会跳转到主页;否则,跳转回登录页面重新输入。