s数据库:
正确登录:
错误登录:
servlet类
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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; } }
登录页面:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<!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()中进行了传参和判断。