• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
๑¹¹
博客园    首页    新随笔    联系   管理    订阅  订阅

前端与数据库简单交互

一、实现

1、下面服务器和数据库的代码用了两种写法,注意对应,方法1被注释掉了。

2、以下为代码实现,仅供参考。

HTML(前端)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>前端与数据库交互</title>
<style type="text/css">
@import url("Style0.css");
</style>
<script type="text/javascript" src="0.js"></script>
<script>
function Check(){
    if(document.Form.Name.value=="")
    {
    alert("姓名不能为空!");
    return false;
    }
else if(document.Form.psword.value.length<6||document.Form.psword.value.length>10)
    {
    alert("密码长度应在6-10位!");
    return false;
    }
else if(document.Form.radio0.value!="男"&&document.Form.radio0.value!="女")
    {
    alert("请选择性别为男或者女,人妖请联系程序员!\n                       call  13856854188");
    return false;
    }
else 
    return true;
}
</script>
</head>
<body bgcolor=pink>
<form action="test" method="post" name="Form" onsubmit="return Check()">
<p align="center"><br/>
<input type="text" name="Name" value="姓名" class=describe0 onfocus="Input()" onblur="Verify()"><br/>
<input type="password" name="psword" value="password" class=describe0 onfocus="Input()" onblur="Verify()"><br/>
<input type="radio" name="radio0" value="男" class=radioclass><font size=5 color="red" face="楷体">男
<input type="radio" name="radio0" value="女">女</font><br/>
<input type="submit" value="登录" class=describe0></p>
</form>
</body>
</html>
CSS样式
@charset "UTF-8";
.describe0{
color:red;
background-color:pink;
height:40px;
text-align:center;
font-size:25px;
font-family:楷体;
cursor:help;            /*必须分号隔开*/
}
.describe1{
    color:green;
    height:400px;
    width:400px;
    text-align:center;
}
JS控制
function Input(){
    if(document.Form.Name.value=="姓名"){
        document.Form.Name.value="";
    }
    if(document.Form.psword.value=="password"){
        document.Form.psword.value="";
    }
}

SEVERLET(服务器)
package Java_web.Java_web0;
import java.io.IOException;
//import java.io.PrintWriter;
//import java.sql.Connection;
//import java.sql.ResultSet;
import java.sql.SQLException;
//import java.sql.Statement;

import javax.servlet.ServletException;
//import javax.servlet.ServletRequest;
//import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Java_web.Java_web1.Dbbase;


public class servlet0 extends HttpServlet{


    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    /*法1:
     * private static final long serialVersionUID = 1L;

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException 
    {
        // TODO Auto-generated method stub
        req.setCharacterEncoding("utf-8");
        res.setContentType("text/html;charset=utf-8");
        PrintWriter print=res.getWriter();
        String psword=req.getParameter("psword");
        String Name=req.getParameter("Name");
        //调用方法
        Dbbase db = new Dbbase();
        Connection con = null ;
        try {
            con=db.communicate();
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Statement seach=null;
        try {
            seach=(Statement)con.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String sql="select * from table0 where username='"+Name+"'and password='"+psword+"'";
        ResultSet result = null;
        try {
            result=seach.executeQuery(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            if(result.next())
            {
                print.println("<html><head><title>前端与数据库交互</title></head><body bgcolor=pink><meta http-equiv='Content-Type;content=text/html;charset=utf-8'>");
                print.println("<br/><div align=center><font face='楷体' size=6 color=red>前端与数据库交互<br/>姓名:"+Name+"<br/>密码:"+psword+"</font></div></body></html>");
                print.close();
            }
            else
            {
                print.println("<html><head><title>前端与数据库交互</title></head><body bgcolor=pink><meta http-equiv='Content-Type;content=text/html;charset=utf-8'>");
                print.println("<br/><div align=center><font face='楷体' size=6 color=red>数据库中没有所查询用户!</font></div></body></html>");
                print.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }*/
//法2:
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String Name=req.getParameter("Name");
        String psword=req.getParameter("psword");
        Dbbase db=new Dbbase();
        boolean flag=false;
        try {
            flag=db.test(Name,psword);
        } catch (ClassNotFoundException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(flag)
        {//如果前端传递的参数存在,就转发到后台主页面//转发
            req.getRequestDispatcher("main.jsp").forward(req, resp);
        }
        else
        {//如果不存在,重新回到登录页面//重定向
            resp.sendRedirect("0.jsp");//打开新0.jsp页面,是重新定向,前后页面不是一个request。
            //req.getRequestDispatcher("0.jsp").forward(req, resp);//刷新页面,是请求转发,前后页面共享一个request ; 
        }
    }
}
DATABASE(数据库)
package Java_web.Java_web1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Dbbase
{
    //法1:
    /*public Connection communicate() throws ClassNotFoundException, SQLException
    {
        Class.forName("com.mysql.cj.jdbc.Driver");//数据库驱动
        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/first_database?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong","root","123456");
        return con;
    }*/

//法2:
        public Statement cheack() throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");//数据库驱动
        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/first_database?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong","root","123456");
        Statement st=null;
        st=(Statement)con.createStatement();
        return st;
    }
    public Boolean test(String Name,String psword) throws ClassNotFoundException, SQLException {
        String sql="select * from table0 where username='"+Name+"'and password='"+psword+"'";
        ResultSet result = null;
        Statement st=this.cheack();
        result=st.executeQuery(sql);
        if(result.next())
            return true;
        else
            return false;
    }
}

跳转页面(0.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 bgcolor=pink>
<br/><div align=center><font face='楷体' size=6 color=red>登录失败,数据库中无此用户!</font></div>
</body>
</html>
跳转页面(main.jsp)
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>前端与数据库交互</title>
</head>
<body bgcolor=pink>
<br/><div align=center><font face='楷体' size=6 color=red>登陆成功,该用户在数据库中查得!</font></div>
</body>
</html>
WEB.XML(配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>0</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>servlet0</servlet-name>
        <servlet-class>Java_web.Java_web0.servlet0</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>servlet0</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>

二、文件及结果

1、注意要在lib目录下添加jar包,且mysql版本不一样jar包则不同,jdbc命令略有不同,我的mysql是8.0,注意版本要一致否则可能出错。

2、部分截图如下,供参考。


图1 数据库表


图2 工程路径及文件存放路径


图3 工程所需库


界面 1


界面 2


界面 3


作者:ThinkerOne
出处:https://www.cnblogs.com/zwsmile/p/14150552.html
声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
posted @ 2020-03-31 15:38  ๑¹¹  阅读(2181)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3