login.jsp
<%@ page import="java.util.Random" %> <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>登录</title> </head> <body> <form action="dologin.jsp" method="post"> <p>账号:<label> <input type="text" name="username"> </label></p> <p>密码:<label> <input type="password" name="password"> </label></p> <p>验证码:<label> <input type="number" name="verify"> </label> <label> <% Random rdm = new Random(); int code1 = rdm.nextInt(100); int code2 = rdm.nextInt(100); %> <input type="number" name="code1" value="<%=code1%>" hidden> <input type="number" name="code2" value="<%=code2%>" hidden> <%=code1%>+<%=code2%>(输入该算式的值) </label></p> <input type="submit" value="登录"> </form> </body> </html>
dologin.jsp
<%@ page import="java.sql.DriverManager" %> <%@ page import="java.sql.Connection" %> <%@ page import="java.sql.PreparedStatement" %> <%@ page import="java.sql.ResultSet" %> <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <html> <head> <title>登录结果</title> </head> <body> <% String loginInfo = ""; String sign = ""; try { String code1 = request.getParameter("code1"); String code2 = request.getParameter("code2"); String verify = request.getParameter("verify"); int code1Int = Integer.parseInt(code1); int code2Int = Integer.parseInt(code2); int verifyInt = Integer.parseInt(verify); if (code1Int + code2Int != verifyInt) loginInfo = "登录失败,验证码不正确"; else { String username = request.getParameter("username"); String password = request.getParameter("password"); Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "cc461352"); PreparedStatement st = conn.prepareStatement("select upwd from usertable where uname = ?"); st.setString(1, username); ResultSet set = st.executeQuery(); if (!set.next()) loginInfo = "用户不存在"; else { String pwd = set.getString(1); if (!password.equals(pwd)) loginInfo = "登录失败,密码错误"; else { loginInfo = "登录成功"; sign = "hidden"; } } } } catch (Exception e) { e.printStackTrace(); loginInfo = "登录失败,参数错误"; } %> <p><%=loginInfo%></p> <form action="index.jsp" method="get"> <input type="submit" value="返回登录" <%=sign%>> </form> </body> </html>