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

JDBC连接MySQL数据库,访问数据库信息完成登录功能——保姆级详细教程(附所有java和jsp源代码)众所周知,我们在使用JAVA开发的时候,用户的数据都是存放在数据库当中的,可是市面上有那么多种类的数据库,为了统一各个数据库和java的连接规范,就出现了JDBC。判断连接是否成功使用数据库实现登录获取前端表单的用户输入判断用户名和密码为空查询表判断用户名和密码的匹配实现整体代码(需要自提,记得点赞)Servlet代码(loginServlet.java)jsp代码(index.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

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

两个账户分别登录成功

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

登录失败

请添加图片描述

今天的文章JDBC连接MySQL数据库,访问数据库信息完成登录功能——保姆级详细教程(附所有java和jsp源代码)分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:http://bianchenghao.cn/32621.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注