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="注册" οnclick='location.href=("registered.jsp")' />

        </td>
      </tr>
    </table>
  </form>
</div>
<%--<p align="center">--%>
<%--  <a href="goods_bean_index.jsp">管理员登录</a>--%>
<%--</p>--%>

</body>
</html>

实现效果

登录页面

请添加图片描述

账号 or 密码 为null

请添加图片描述
请添加图片描述

两个账户分别登录成功

请添加图片描述
请添加图片描述

登录失败

请添加图片描述

  • 48
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 41
    评论
评论 41
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

写代码两年半

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值