前端与数据库简单交互
一、实现
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器