s數據庫:html
正確登陸:java
錯誤登陸:sql
servlet類數據庫
package servlet_chack; 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; import java.sql.*; @WebServlet("/UserCheck") public class UserCheck extends HttpServlet { private static final long serialVersionUID = 1L; public UserCheck() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String strUserName = null; String strPassword = null; strUserName = request.getParameter("name"); strPassword = request.getParameter("password"); if (check(strUserName, strPassword)) { response.getWriter().write("用戶名:" + strUserName); response.getWriter().write("</br>"); response.getWriter().write("密碼:" + strPassword); } else { response.getWriter().write("用戶名或密碼錯誤!"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public static boolean check(String usr, String psd) { final String driver = "org.mariadb.jdbc.Driver"; final String url = "jdbc:mariadb://192.168.1.231:3306/hello"; final String user = "root"; final String pswd = "admin"; Connection conn; try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(url, user, pswd); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("select * from users where usr=\"" + usr + "\" and psd=\"" + psd + "\";"); conn.close(); return rs.next() ? true : false; } catch (Exception e) { e.printStackTrace(); } return false; } }
登陸頁面:ide
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用戶名檢查</title> </head> <body> <h1>用戶登陸</h1> <form action="/servlet_chack/UserCheck" method="post"> <p> 用戶名:<input type="text" name="name" /> </p> <p> 密碼:<input type="password" name="password" /> </p> <input type="submit" value="登陸" /> </form> </body> </html>
小結:參考了網上的代碼,在原來的servlet類中新建了check()方法,在doGet()中進行了傳參和判斷。post