写点什么

JDBC 连接 MySQL 数据库,访问数据库信息完成登录功能——保姆级详细教程(附所有 java 和 jsp 源代码)

  • 2022 年 6 月 16 日
  • 本文字数:3437 字

    阅读完需:约 11 分钟

JDBC连接MySQL数据库,访问数据库信息完成登录功能——保姆级详细教程(附所有java和jsp源代码)

前言

众所周知,我们在使用 JAVA 开发的时候,用户的数据都是存放在数据库当中的,可是市面上有那么多种类的数据库,为了统一各个数据库和 java 的连接规范,就出现了 JDBC。

JDBC 的介绍

JDBC 为访问不同数据库提供了统一的接口,java 程序员使用 JDBC,可以连接任何提供 JDBC 驱动程序的数据库系统,从而完成对数据库的各种操作。

通过 JDBC 连接 MySQL 数据库

导入 mysql 驱动

这个驱动其实就是一个规范接口,需要连接 MySQL 数据库就下载匹配本机 mysql 版本的对应驱动,然后导入即可。




数据库连接

连接数据库

String url ="jdbc:mysql://localhost:3306/abc";   //abc为数据库名称String  user = "root";        //定义字符串变量存入mysql登录名String password = "123456";     //定义字符串存入mysql登录密码Class.forName("com.mysql.jdbc.Driver");  //加载mysql驱动          Connection connection = DriverManager.getConnection(url,user,password);Statement statement = connection.createStatement();   //建立连接
复制代码

判断连接是否成功

if (conn!=null){            out.print("连接成功"+"<br>");}else{            out.print("连接失败"+"<br>");}
复制代码

使用数据库实现登录

获取前端表单的用户输入

String s1=request.getParameter("username");String s2=request.getParameter("password");request.setAttribute("s1", s1);
复制代码

判断用户名和密码为空

//判断用户名、密码是否为空if(s1 == "" || s1.length() == 0){  request.setAttribute("namemsg","用户名为空!");  request.getRequestDispatcher("index.jsp").forward(request, response);}if(s2== "" || s2.length() == 0){  request.setAttribute("pwdmsg","密码为空!");  request.getRequestDispatcher("index.jsp").forward(request, response);}
复制代码

查询表

String sql = String.format("SELECT * FROM login WHERE `username` = '%s' AND `password` = '%s'",s1,s2);            ResultSet resultSet = statement.executeQuery(sql);//返回的结果集
复制代码

判断用户名和密码的匹配

if (resultSet.next()){  request.getRequestDispatcher("login.jsp").forward(request,response); //匹配成功进入登录成功页面}else if(s1.equals("") || s2.equals("")){  request.getRequestDispatcher("loginf.jsp").forward(request,response);  //用户名和密码有一个村务}else{request.getRequestDispatcher("loginf.jsp").forward(request,response);  //用户和密码全部错误}
复制代码

实现整体代码(需要自提,记得点赞)

Servlet 代码(loginServlet.java)

package servlet;
import java.io.IOException;import java.sql.*;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
/** * @author s * @version 1.0 */@WebServlet("/loginServlet")public class loginServlet extends HttpServlet { private static final long serialVersionUID = 1L;
/** * @see HttpServlet#HttpServlet() */ public loginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String s1=request.getParameter("username"); String s2=request.getParameter("password"); request.setAttribute("s1", s1);
//判断用户名、密码是否为空 if(s1 == "" || s1.length() == 0){ request.setAttribute("namemsg","用户名为空!"); request.getRequestDispatcher("index.jsp").forward(request, response); } if(s2== "" || s2.length() == 0){ request.setAttribute("pwdmsg","密码为空!"); request.getRequestDispatcher("index.jsp").forward(request, response); } //密码部分结束 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8");
//加载mysql驱动 String url ="jdbc:mysql://localhost:3306/abc"; String user = "root"; String password = "123456"; try { Class.forName("com.mysql.jdbc.Driver"); // 连接数据库 Connection connection = DriverManager.getConnection(url,user,password); Statement statement = connection.createStatement(); String sql = String.format("SELECT * FROM login WHERE `username` = '%s' AND `password` = '%s'",s1,s2); ResultSet resultSet = statement.executeQuery(sql);//返回的结果集 if (resultSet.next()){ request.getRequestDispatcher("login.jsp").forward(request,response); }else if(s1.equals("") || s2.equals("")){ request.getRequestDispatcher("loginf.jsp").forward(request,response); } else{request.getRequestDispatcher("loginf.jsp").forward(request,response);} }catch(ClassNotFoundException | SQLException e) { e.printStackTrace(); System.out.println("失败"); } }}
复制代码

jsp 代码(index.jsp)


<%-- Created by IntelliJ IDEA. User: 86151 Date: 2022/5/24 Time: 14:32 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head> <base href="<%=basePath%>"> <title>用户登录</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <style type="text/css"> </style></head><body><div> <form action="loginServlet" method="post"> <table align="center" > <tr> <td>用户名:</td> <td><input type="text" name="username"> <font color="red"> ${requestScope.namemsg}${requestScope.nameError}</font></td> </tr> <tr> <td>密码:</td> <td><input type="password" name="password"> <font color="red"> ${requestScope.pwdError}${requestScope.pwdmsg}</font></td> </tr> <tr> <td></td> <td><input type="submit" value="登录"> <input type="button" value="注册" onclick='location.href=("registered.jsp")' />
</td> </tr> </table> </form></div><%--<p align="center">--%><%-- <a href="goods_bean_index.jsp">管理员登录</a>--%><%--</p>--%>
</body></html>
复制代码

实现效果

登录页面


账号 or 密码 为 null



两个账户分别登录成功




登录失败




发布于: 刚刚阅读数: 4
用户头像

还未添加个人签名 2022.06.02 加入

喜欢Java和py,会更新自己在学习过程中遇到**比较重要的知识点**以及**自己遇见的问题与解决方法**哦,如果你也正在学Java,就请留下一个关注吧

评论

发布
暂无评论
JDBC连接MySQL数据库,访问数据库信息完成登录功能——保姆级详细教程(附所有java和jsp源代码)_数据库_写代码两年半_InfoQ写作社区