1.创建表login:
creat tables login{uname varchar(20),upwd varchar(20)}
并在表中添加帐号和密码:
insert into join(uname,upwd) values('zs','abc');
2.在eclipse中创建MyWebProject工程,并添加index.jsp和check.jsp
3.将mysql java 8.0.14 jar复制到WEB-INF/lib中
4.在index.jsp中输入代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body><form action="check.jsp" method="post"> 用户名:<input type="text" name="uname"/><br/> 密码:<input type="password" name="upwd"/><br/> <input type="submit" value="登录"/><br/> </form> </body> </html>
5.在check.jsp中输入代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% String URL = "jdbc:mysql://localhost:3306/myemployees?serverTimezone=UTC"; String USERNAME = "root"; String PWD = "123456"; Connection connection = null; Statement stmt=null; ResultSet rs=null; //返回值表示增删改第几条数据 try { //a.导入驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //b.与数据库进行连接 connection=DriverManager.getConnection(URL,USERNAME,PWD); //c.发送sql,执行查找 stmt=connection.createStatement(); //把名字密码一收 String name=request.getParameter("uname"); String pwd=request.getParameter("upwd"); String sql="select count(*) from login where uname='"+name+"' and upwd='"+pwd+"'"; rs=stmt.executeQuery(sql);//返回值表示增删改第几条数据 //d.处理结果 int count=-1; if(rs.next()) { count=rs.getInt(1); } if(count>0){ out.println("登录成功!"); } else{ out.println("登录失败!"); } }catch(ClassNotFoundException e){ e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { try {if(rs!=null){ rs.close(); } if(stmt!=null) { stmt.close(); }if(connection!=null) { connection.close(); } }catch(SQLException e) { e.printStackTrace(); } } %> </body> </html>
6.开始运行,并在浏览器中输入:
http://localhost:9999/MyWebProject/index.jsp
7.zs,abc 登录成功