任务
1.通过连接数据库完成用户登录模块。
2.登录成功后查询出一张数据库表中的内容;登录不成功返回登录页面。
3.登录页面端要有空值和非法字符验证。
4.登录成功后对一张表中数据进行增加、删除、修改和查询操作。
代码
数据库相关代码
创建数据库
名字为jdbcHomework,字符编码为utf8
数据库创建表
学生表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`Sid` char(11) CHARACTER SET utf8 NOT NULL,
`Sname` char(50) CHARACTER SET utf8 DEFAULT NULL,
`Ssex` char(2) CHARACTER SET utf8 DEFAULT NULL,
`Sclass` char(50) CHARACTER SET utf8 DEFAULT NULL,
`Syuanxi` char(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`Sid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='jdbc作业';
用户表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`Userid` char(11) NOT NULL,
`Username` char(50) DEFAULT NULL,
`Userpwd` varchar(12) DEFAULT NULL,
PRIMARY KEY (`Userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='jdbc作业';
数据库的表中插入数据
学生表
INSERT INTO `student` VALUES ('20221104122', '李静静', '女', '计科(专升本)1班', '计算机');
INSERT INTO `student` VALUES ('20221104204', '柯柯', '女', '计科(专升本)2班', '计算机');
INSERT INTO `student` VALUES ('20221104250', 'zyp', '男', '自动化1班', '自动化');
用户表
INSERT INTO `user` VALUES ('20221104122', '洛可可', '666666');
INSERT INTO `user` VALUES ('root', '洛可可', 'root');
myeclipse中代码
src的jdbcHomework包中的代码
功能:连接数据库
1.LinkMysql.java为连接mysql的代码,包括驱动、密码、url,用于登录界面、登录检查、增删改查的后台处理
2.ConnectionFactory.java为为连接mysql的代码,包括驱动、密码、url,用于登录成功后界面linkMysql.jsp连接数据库
3.本次学习时上面类使用方法是通过javaBean的id获取链接,从而连接到数据库;下面类使用方法是通过在开头导入该类,代码中新建类并用 “新建的类名.getConnection();” 方法获取链接,从而连接到数据库
1.LinkMysql
package jdbcHomework;
import java.sql.*;
public class LinkMysql {
//驱动程序
private String driverName = "com.mysql.jdbc.Driver";
//设置数据库连接URL
private String url = "jdbc:mysql://localhost:3306/jdbcHomework?useUnicode=true&characterEncoding=utf-8";
private String user = "root";//数据库登录用户名
private String password = "root";//数据库登录密码
public String getDriverName() {
return driverName;
}
public void setDriverName(String driverName) {
this.driverName = driverName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Connection getConnection() {
try {
Class.forName(driverName);
return DriverManager.getConnection(url, user, password);
} catch (Exception e) {
//e.printStackTrace();
System.out.println("驱动异常");
return null;
}
}
}
2.ConnectionFactory
package jdbcHomework;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
private String driverClassName = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/jdbcHomework?useUnicode=true&characterEncoding=utf-8";
private String userName = "root";
private String password = "root";
/*
private static ConnectionFactory connectionFactory=null;
private ConnectionFactory() {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ConnectionFactory(){
}
*/
public Connection getConnection() throws SQLException
{
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("驱动异常");
}
return DriverManager.getConnection(url, userName, password);
}
/*
public static ConnectionFactory getInstance()
{
if (null==connectionFactory) {
connectionFactory=new ConnectionFactory();
}
return connectionFactory;
}
*/
}
WebRoot/jdbcHomework下的代码
1.登录主界面代码
login.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录页面</title>
<script type="text/javascript">
function checkForm() {
var id = document.forms["form1"]["id"].value;
var name = document.forms["form1"]["name"].value;
var pwd = document.forms["form1"]["pwd"].value;
// 检查是否为空值
if (id === "" || name === "" || pwd === "") {
alert("请输入完整的信息");
return false;
}
// 检查是否包含非法字符
var illegalChars = /[^\w\s]/;
if (illegalChars.test(id) || illegalChars.test(pwd)) {
alert("输入包含非法字符");
return false;
}
return true;
}
</script>
</head>
<%-- 用于首次登录 --%>
<body bgcolor="pink">
<div class="top" align="center">
<h1>欢迎来到洛可可学生管理系统!!</h1>
</div>
<br>
<div class="center" align="center">
<form name="form1" action="/myFirstTest/jdbcHomework/logincheck.jsp" method="post" " οnsubmit="return checkForm();">
<table border="1" bgcolor="rgb(248, 169, 182)">
<tr>
<td>学号:</td>
<td><input type="text" name="id" ></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name" ></td>
</tr>
<tr>
<td>密码:</td>
<td width="50"><input type="password" name="pwd"></td>
</tr>
<tr >
<td colspan="2" align="center">
<input type="submit" value="登录"/>
<input type="reset"/>
</td>
</tr>
</table>
</form>
</div>
<div class="bottom" align="center">
</div>
</body>
</html>
2.登录检查代码
logincheck.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录检查</title>
</head>
<body>
<jsp:useBean id="link" class="jdbcHomework.LinkMysql"></jsp:useBean>
<%
/*获取到login.jsp页面登录时学生的学号、姓名、密码*/
request.setCharacterEncoding("utf-8");
String studentId = request.getParameter("id");
String studentName = request.getParameter("name");
String pwd = request.getParameter("pwd");
System.out.println("学号:"+studentId+",姓名:"+studentName+",密码:"+pwd); //控制台输出获取到的登录时学生的学号、姓名、密码
/*连接数据库并执行相关操作*/
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
con = link.getConnection();
String sql="select * from user where Userid=? and Username=? and Userpwd=?";
ps=con.prepareStatement(sql);
ps.setString(1,studentId);
ps.setString(2, studentName);
ps.setString(3,pwd);
rs=ps.executeQuery();
if(rs.next()){
System.out.println("登录成功!");
//response.sendRedirect("/myFirstTest/jdbcHomework/linkMysql.jsp");
out.print("<script type='text/javascript'> alert('登陆成功!!');window.location='/myFirstTest/jdbcHomework/linkMysql.jsp';</script>");
}
else{
System.out.println("登录失败!");
//response.sendRedirect("/myFirstTest/jdbcHomework/login.jsp");
out.print("<script type='text/javascript'> alert('登陆失败,请重新登录!!');window.location='/myFirstTest/jdbcHomework/login.jsp';</script>");
}
rs.close();
ps.close();
con.close();
%>
</body>
</html>
3.登录成功页面代码
linkMysql.jsp
<%@ page language="java" import="java.util.*, java.sql.*,jdbcHomework.ConnectionFactory" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录成功页面</title>
</head>
<%-- 在浏览器上显示所有学生信息 --%>
<body bgcolor="pink">
<div class="top" align="center" >
<h1>欢迎加入到洛可可学生管理系统</h1>
</div>
<div class="center" align="center">
<table border="1" bgcolor="rgb(248, 169, 182)" align="center">
<tr>
<th width="87" align="center">学号</th>
<th width="87" align="center">姓名</th>
<th width="87" align="center">性别</th>
<th width="87" align="center">班级</th>
<th width="87" align="center">院系</th>
<th width="87" align="center">操作</th>
</tr>
<%
Connection con= null;
Statement stmt=null;
ResultSet rs=null;
//Class.forName("com.mysql.jdbc.Driver");
/*3306为端口号,student为数据库名,url后面加的?useUnicode=true&characterEncoding=gbk是为了处理向数据库中添加数据时出现乱码的问题。*/
//String url="jdbc:mysql://localhost:3306/jdbcHomework?useUnicode=true&characterEncoding=utf-8";
//con=DriverManager.getConnection(url,"root","root");
ConnectionFactory cf = new ConnectionFactory();
con = cf.getConnection();
stmt=con.createStatement();
String sql="select * from student";
rs=stmt.executeQuery(sql);
while(rs.next()){
%>
<tr>
<td><%=rs.getString("Sid")%></td>
<td><%=rs.getString("Sname")%></td>
<td><%=rs.getString("Ssex")%></td>
<td><%=rs.getString("Sclass")%></td>
<td><%=rs.getString("Syuanxi")%></td>
<td><a href="/myFirstTest/jdbcHomework/deleteStu.jsp?Sid=<%=rs.getString("Sid")%>">删除</a>
<a href="/myFirstTest/jdbcHomework/updateStu.jsp?Sid=<%=rs.getString("Sid")%>">修改</a></td>
</tr>
<%}
rs.close();
stmt.close();
con.close();
%>
</table>
</div>
<br>
<div class="bottom" align="center">
<a href="/myFirstTest/jdbcHomework/add.jsp">添加学生信息</a>
<a href="/myFirstTest/jdbcHomework/login.jsp">登录界面</a>
</div>
</body>
</html>
4.删除学生信息后台处理代码
deleteStu.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>删除学生信息</title>
</head>
<body>
<jsp:useBean id="link" class="jdbcHomework.LinkMysql"></jsp:useBean>
<%
request.setCharacterEncoding("utf-8");
String Sid = request.getParameter("Sid");
System.out.println(Sid);
Connection con=null;
PreparedStatement ps=null;
//ResultSet rs=null;
con = link.getConnection();
String sql="delete from student where Sid=? ";
ps=con.prepareStatement(sql);
ps.setString(1,Sid);
int i=ps.executeUpdate();
if(i>0){
System.out.println("删除成功!");
//response.sendRedirect("linkMysql.jsp");
out.print("<script type='text/javascript'> alert('删除成功!');window.location='linkMysql.jsp';</script>");
}
else{
System.out.println("删除的学生不存在!");
//response.sendRedirect("linkMysql.jsp");
out.print("<script type='text/javascript'> alert('删除失败!');window.location='linkMysql.jsp';</script>");
}
ps.close();
con.close();
%>
</body>
</html>
5.修改学生信息主界面代码
deleteStu.jsp
<%@ page language="java" import="java.util.*, java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>修改学生信息页面</title>
</head>
<body bgcolor="pink">
<div class="top" align="center">
<h1>欢迎来到洛可可学生系统修改(更新)页面</h1>
</div>
<hr>
<div class="center" align="center">
<jsp:useBean id="link" class="jdbcHomework.LinkMysql"></jsp:useBean>
<%
String Sid = request.getParameter("Sid");
session.setAttribute("Updateid", Sid); //用于更新处理获取学生id信息
System.out.println("修改学号为"+Sid+"的学生信息");
Connection con=null;
PreparedStatement ps=null;
con=link.getConnection();
String sql="select * from student where Sid=? ";
ps=con.prepareStatement(sql);
ps.setString(1,Sid);
ResultSet rs=ps.executeQuery();
if(rs.next()){
%>
<form action="/myFirstTest/jdbcHomework/doupdate.jsp" method="post" >
<table border="1" bgcolor="rgb(248, 169, 182)" >
<tr>
<th>学号:</th>
<td><%=rs.getString(1) %></td>
</tr>
<tr>
<th>姓名:</th>
<td><input type="text" name="Sname" value="<%=rs.getString(2) %>"></td>
</tr>
<tr>
<th>性别:</th>
<td><input type="text" name="sex" value="<%=rs.getString(3) %>"></td>
</tr>
<tr>
<th>班级:</th>
<td><input type="text" name="banji" value="<%=rs.getString(4) %>"></td>
</tr>
<tr>
<th>院系:</th>
<td><input type="text" name="yuanxi" value="<%=rs.getString(5) %>"></td>
</tr>
</table>
<br>
<input type="submit" value="修改完成">
</form>
<%
}
rs.close();
ps.close();
con.close();
%>
</div>
<hr>
<br>
<div class="bottom" align="center">
<a href="/myFirstTest/jdbcHomework/linkMysql.jsp">返回上一界面</a>
<a href="/myFirstTest/jdbcHomework/login.jsp">切换账号</a>
</div>
</body>
</html>
5.修改学生信息后台处理代码
doupdate.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>更新学生信息处理</title>
</head>
<body>
<jsp:useBean id="link" class="jdbcHomework.LinkMysql"></jsp:useBean>
<%
request.setCharacterEncoding("utf-8");
String Sid = (String)session.getAttribute("Updateid");
String Sname = request.getParameter("Sname");
String sex = request.getParameter("sex");
String banji = request.getParameter("banji");
String yuanxi = request.getParameter("yuanxi");
System.out.println(Sid+Sname+sex+banji+yuanxi);
Connection con=null;
PreparedStatement ps=null;
con=link.getConnection();
String sql="update student set Sname=?,Ssex=?,Sclass=?,Syuanxi=? where Sid=?";
ps=con.prepareStatement(sql);
ps.setString(1,Sname);
ps.setString(2, sex);
ps.setString(3,banji);
ps.setString(4,yuanxi);
ps.setString(5,Sid);
int i=ps.executeUpdate();
if(i>0){
System.out.println("修改成功!");
//response.sendRedirect("linkMysql.jsp");
out.print("<script type='text/javascript'> alert('学生信息修改成功!');window.location='linkMysql.jsp';</script>");
}
else{
System.out.println("修改失败!");
//response.sendRedirect("linkMysql.jsp");
out.print("<script type='text/javascript'> alert('学生信息修改失败!');window.location='login.jsp';</script>");
}
ps.close();
con.close();
%>
</body>
</html>
6.添加学生信息主界面代码
add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>添加学生信息页面</title>
<script>
function checkForm() {
var id = document.forms["form1"]["id"].value;
var sex = document.forms["form1"]["sex"].value;
// 验证学号非空且为数字组成的11位以内
if (id.trim() === "") {
alert("学号不能为空");
return false;
}
if (!/^\d{1,11}$/.test(id)) {
alert("请输入有效的学号(数字组成的11位以内)");
return false;
}
// 验证性别为男、女或留空
if (sex.trim() !== "" && sex.trim() !== "男" && sex.trim() !== "女") {
alert("性别只能是男、女");
return false;
}
return true;
}
</script>
</head>
<body bgcolor="pink">
<div class="top" align="center">
<h1>欢迎来到洛可可学生系统添加页面</h1>
</div>
<div class="center" align="center">
<form name="form1" action="/myFirstTest/jdbcHomework/doadd.jsp" method="post" onsubmit="return checkForm();">
<table>
<tr>
<td>学号:</td>
<td><input type="text" name="id" ></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name" ></td>
</tr>
<tr>
<td>性别:</td>
<td width="50"><input type="text" name="sex"></td>
</tr>
<tr>
<td>班级:</td>
<td width="50"><input type="text" name="banji"></td>
</tr>
<tr>
<td>院系:</td>
<td width="50"><input type="text" name="yuanxi"></td>
</tr>
<tr >
<td colspan="2" align="center">
<input type="submit" value="添加"/>
<input type="reset"/>
</td>
</tr>
</table>
</form>
</div>
<br>
<div align="center">
<a href="/myFirstTest/jdbcHomework/linkMysql.jsp">返回上一界面</a>
<a href="/myFirstTest/jdbcHomework/login.jsp">切换账号</a>
</div>
</body>
</html>
6.添加学生信息后台处理代码
doadd.jsp
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>添加学生信息后台处理</title>
</head>
<body>
<jsp:useBean id="link" class="jdbcHomework.LinkMysql"></jsp:useBean>
<%
request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String banji = request.getParameter("banji");
String yuanxi = request.getParameter("yuanxi");
Connection con=null;
PreparedStatement ps=null;
con = link.getConnection();
String sql="insert into student(Sid,Sname,Ssex,Sclass,Syuanxi) values(?,?,?,?,?)";
ps=con.prepareStatement(sql);
ps.setString(1,id);
ps.setString(2, name);
ps.setString(3,sex);
ps.setString(4,banji);
ps.setString(5,yuanxi);
int i=ps.executeUpdate();
if(i>0){
System.out.println("添加成功!");
//response.sendRedirect("/myFirstTest/jdbcHomework/linkMysql.jsp");
out.print("<script type='text/javascript'> alert('添加成功!');window.location='/myFirstTest/jdbcHomework/linkMysql.jsp';</script>");
}
else{
System.out.println("添加失败,请重新输入!");
//response.sendRedirect("/myFirstTest/jdbcHomework/add.jsp");
out.print("<script type='text/javascript'> alert('添加失败!');window.location='/myFirstTest/jdbcHomework/add.jsp';</script>");
}
ps.close();
con.close();
%>
</body>
</html>
效果
运行初始界面
输入错误用户信息登录返回登录页面
弹窗提示登录失败,请重新登录!
点击确定后返回登录界面
有空信息登录提示并返回登录界面
只输入一个信息
弹框提示请输入完整信息
点击确定继续输入
输入两个信息
弹框提示输入完整信息
点击确定可继续输入
输入非法字符登录提示并返回登录界面
弹框提示输入包含非法字符
点击确定即可重新输入,可重置重新输入或修改错误的信息
输入正确用户信息登录进入系统
输入正确学号、姓名、密码后控制台输出登录成功,页面跳转至登录成功页面(显示数据库学生信息表)
弹窗提示登录成功! 点击确定即可跳转到登录成功页面【学生信息查询页面】
1.登录成功后控制台输出登录成功提示
2.点击记录后面的删除与修改可进行相关操作,点击表单后面的添加学生信息可跳转到添加学生信息页面
3.点击登录界面可跳转到登录页面进行账号切换
添加学生信息功能
1.在主界面信息表后面都有一个添加学生信息选项,点击即可跳转至学生信息添加页面,之后输入信息点击添加即可完成添加学生信息功能
添加前
添加
添加后
2.在添加学生信息页面表格下面有返回上一界面和切换账号超链接,点击返回上一界面即跳转到登录成功页面【学生信息查询页面】,点击切换账号即跳转到登录界面
添加学生信息页面
点击返回上一界面
点击切换账号
删除学生信息功能
在主界面信息每行后面都有一个删除选项,点击即可删除该行信息
删除前
删除后
修改学生信息功能
1.在主界面信息每行后面都有一个修改选项,点击即可跳转至修改该行信息页面,可以修改该行信息(学号不可更改)
修改前
修改
修改后
2.在添加学生信息页面表格下面有返回上一界面和切换账号超链接,点击返回上一界面即跳转到登录成功页面【学生信息查询页面】,点击切换账号即跳转到登录界面