实现简单页面上对数据的增删改查:Java后台+数据库表+Jsp前端网页设计
项目下载链接:https://pan.baidu.com/s/1UvZ5fzFjxU-GELo9Th3nNg
提取码:kvmc
GitHub源码下载:https://github.com/yishengxiaobai/Java_Course
这里做一个简单的学生课程信息管理系统,做之前一定要先有自己的思路,要不然对新手来说,很容易乱的。
通过本系统,同学们可以添加,删除,查询与修改课程上课地点和课程老师以及课程名称等信息。
运行截图:
数据库设计:
首页:
课程信息录入:
课程信息修改:
课程信息删除:(先查找后删除)
课程信息查询:
另有一完整的代码可供参考,网页版记账本,链接https://www.cnblogs.com/sengzhao666/p/10449534.html
一.建立项目
1. 首先新建一个名为Course的Dynamic Web Project
取完名直接点击完成,或者一直下一步直到完成。
2. 程序分五层
Dao:底层程序
Entity:实体层
Servlet:将界面与底层程序联系起来
Service:可以理解为servlet层与dao层的中转层
Util:连接数据库
注意servlet层不是建立类,而是建立一个Servlet;其他包下均为类。
二.数据库设计
三.系统功能分析
1. 添加
需要一个界面add.jsp
2. 删除
首先需要根据名称查找;deletebyName.jsp
查找后列出结果,删除;delete.jsp
3. 修改
首先列出所有数据;list.jsp
修改界面;update.jsp
4. 查询
查询界面;select.jsp(模糊查询)
显示查询结果界面;selectlist.jsp
四.实现增删改查四项基本功能(以添加功能为例,其他思路相同)
功能解析:
add界面得到数据;
servlet层获得数据;
Service层传递给dao底层程序;
最后dao层执行sql语句:
String sql = "insert into course(name, teacher, classroom) values('" + course.getName() + "','" + course.getTeacher() + "','" + course.getClassroom() + "')";
将数据添加进数据库。
注:推荐写程序时编写顺序也这么来:先想好系统功能,然后编写前端jsp再一步一步往下推。
程序详解:
添加界面add.jsp得到用户键入的数据;
界面执行通过后,action="courseServlet?method=add" 三目运算符将method赋值为add;
Servlet层得到method,判断method值;
String method = req.getParameter("method"); if ("add".equals(method)) { add(req, resp); }
执行add函数。
servlet层add函数获得界面数据:
String name = req.getParameter("name"); String teacher = req.getParameter("teacher"); String classroom = req.getParameter("classroom"); Course course= new Course(name, teacher, classroom);
调用service层函数:
if(service.add(course)) { req.setAttribute("message", "添加成功");//setAttribute方法用于将内容保存在对象中,传到下一个页面中 req.getRequestDispatcher("add.jsp").forward(req,resp);//getRequestDispatcher方法用于进入下一个页面 }
Service层传递给dao底层。
public boolean add(Course course) { boolean bean=false; if(!dao.rename(course.getName())) { //检查是否重名,否的话执行下一步 dao.add(course); bean=true; } return bean; }
Dao层执行添加功能:
String sql = "insert into course(name, teacher, classroom) values('" + course.getName() + "','" + course.getTeacher() + "','" + course.getClassroom() + "')";
五.源代码:
实体层Course.Java:
private String name;
private String teacher;
private String classroom;
public void setId(int id) {
this.id=id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
public Course() {}
this.name = name;
this.teacher = teacher;
this.classroom = classroom;
}
}
servlet层代码如下:
import java.io.IOException;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.courseService;
* Servlet implementation class courseServlet
*/
@WebServlet("/courseServlet")
public class courseServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
/**
* 方法选择
*/
req.setCharacterEncoding("utf-8");
String method = req.getParameter("method");
if ("add".equals(method)) {
add(req, resp);
} else if ("delete".equals(method)) {
delete(req, resp);
} else if ("update".equals(method)) {
update(req, resp);
} else if ("select".equals(method)) {
select(req, resp);
} else if ("getCoursebyName".equals(method)) {
getCoursebyName(req, resp);
} else if ("getCoursebyName2".equals(method)) {
getCoursebyName2(req, resp);
} else if ("list".equals(method)) {
list(req, resp);
}
}
private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
//添加
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String teacher = req.getParameter("teacher");
String classroom = req.getParameter("classroom");
Course course= new Course(name, teacher, classroom);
//判断是否重名
if(service.add(course)) {
req.setAttribute("message", "添加成功");//setAttribute方法用于将内容保存在对象中,传到下一个页面中
req.getRequestDispatcher("add.jsp").forward(req,resp);//getRequestDispatcher方法用于进入下一个页面
} else {
req.setAttribute("message", "课程名称重复,请重新录入");
req.getRequestDispatcher("add.jsp").forward(req,resp);
}
}
// 删除
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
service.delete(name);
req.setAttribute("message", "课程信息删除成功");
req.getRequestDispatcher("deletebyName.jsp").forward(req,resp);
}
private void getCoursebyName2(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
/*
* 通过名字得到
* 跳转至修改
*/
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
Course course =service.getCoursebyName(name);
req.setAttribute("course", course);
req.getRequestDispatcher("update.jsp").forward(req,resp);
}
/*
* 通过名字查找
* 跳转至删除
*/
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
Course course =service.getCoursebyName(name);
if(course == null) {
req.setAttribute("message", "查无此课程!");
req.getRequestDispatcher("deletebyName.jsp").forward(req,resp);
} else {
req.setAttribute("course", course);
req.getRequestDispatcher("delete.jsp").forward(req,resp);
}
}
//列出全部信息
req.setCharacterEncoding("utf-8");
List<Course> course = service.list();
req.setAttribute("courses",course);
req.getRequestDispatcher("list.jsp").forward(req,resp);
}
//修改
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String teacher = req.getParameter("teacher");
String classroom = req.getParameter("classroom");
Course course = new Course(name,teacher, classroom);
int k=service.update(course);
if(k==0) {
req.setAttribute("message", "修改失败");
req.getRequestDispatcher("courseServlet?method=list").forward(req,resp);
}else if(k==1){
req.setAttribute("message", "修改成功");
req.getRequestDispatcher("courseServlet?method=list").forward(req,resp);
}
}
//查找
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String teacher = req.getParameter("teacher");
String classroom = req.getParameter("classroom");
List<Course> course = service.select(name, teacher, classroom);
req.setAttribute("courses", course);
req.getRequestDispatcher("selectlist.jsp").forward(req,resp);
}
}
service层代码如下:
import entity.Course;
Dao dao=new Dao();
public boolean add(Course course) {
boolean bean=false;
if(!dao.rename(course.getName())) {
//检查是否重名,否的话执行下一步
dao.add(course);
bean=true;
}
return bean;
}
public void delete(String name) {
dao.delete(name);
}
public int update(Course course) {
int f=0;
if(dao.update(course)) {
f=1;
}
return f;
}
public Course getCoursebyName(String name) {
//通过Name得到一个Course
return dao.getCoursebyName(name);
}
public List<Course> select(String name, String teacher, String classroom) {
//查找
return dao.select(name, teacher, classroom);
}
//列出表中所有信息
return dao.list();
}
}
Dao层代码如下:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import util.Shujuku;
/*
* 将函数设置为Boolean类型,只返回真值或假值给service层,方便
*/
public boolean rename(String name) {
//搜索数据库表course,检查是否重名
String sql = "select * from courses where name ='" + name + "'";
Connection conn =Shujuku.conn() ;
Statement st= null;
ResultSet rs = null;
boolean bean=false;
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
bean = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Shujuku.close(rs,st, conn);
}
return bean;
}
//添加
String sql = "insert into courses(name, teacher, classroom) values('" + course.getName() + "','" + course.getTeacher() + "','" + course.getClassroom() + "')";
Connection conn =Shujuku.conn() ;
Statement st= null;
boolean bean = false;
int a = 0;
try {
st = conn.createStatement();
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
Shujuku.close(st, conn);
}
if (a > 0) {
bean = true;
}
return bean;
}
// 通过名字删除
boolean f=false;
String sql = "delete from courses where name ='" + name + "'";//删除
Connection conn = Shujuku.conn();
Statement state = null;
int a=0;
try {
state = conn.createStatement();
a=state.executeUpdate(sql);
}catch (Exception e) {
e.printStackTrace();
} finally {
Shujuku.close(state, conn);
}
if(a>0) {
f=true;
}
return f;
}
// 修改
String sql = "update courses set teacher='" + course.getTeacher() + "', classroom='" + course.getClassroom()+"'where name='"+course.getName()+"'";
Connection conn = Shujuku.conn();
Statement state = null;
boolean f = false;
int a = 0;
state = conn.createStatement();
a = state.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
Shujuku.close(state, conn);
}
if (a > 0) {
f = true;
}
return f;
}
String sql = "select * from courses where name ='" + name + "'";
Connection conn =Shujuku.conn() ;
Statement st= null;
ResultSet rs = null;
Course course=null;
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
String teacher = rs.getString("teacher");
String classroom = rs.getString("classroom");
course = new Course(name, teacher, classroom);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Shujuku.close(rs,st, conn);
}
return course;
}
String sql = "select * from courses where ";
if (name !=null) {
sql += "name like '%" + name + "% '";
}else if(name==null) {
sql += " ";
}
if (name !=null&&teacher !=null) {
sql += "and teacher like '%" + teacher + "% '";
}else if(name==null&&teacher !=null) {
sql += "teacher like '%" + teacher + "% '";
}else if(teacher==null) {
sql += " ";
}
if ((name!=null||teacher !=null)&&classroom !=null) {
sql += "and classroom like '%" + classroom + "%'";
}else if(name==null&&teacher==null&&classroom !=null) {
sql += "teacher like '%" + teacher + "% '";
}else if(classroom==null) {
sql += " ";
}
List<Course> list = new ArrayList<>();
Connection conn =Shujuku.conn() ;
Statement st= null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
Course course=null;
while (rs.next()) {
String name2 = rs.getString("name");
String teacher2 = rs.getString("teacher");
String classroom2 = rs.getString("classroom");
course= new Course(name2, teacher2, classroom2);
list.add(course);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Shujuku.close(rs,st, conn);
}
return list;
String sql = "select * from courses";
List<Course> list = new ArrayList<>();
Connection conn =Shujuku.conn() ;
Statement st= null;
ResultSet rs = null;
try {
st = conn.createStatement();
rs = st.executeQuery(sql);
Course course=null;
while (rs.next()) {
String name2 = rs.getString("name");
String teacher2 = rs.getString("teacher");
String classroom2 = rs.getString("classroom");
course= new Course(name2, teacher2, classroom2);
list.add(course);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
Shujuku.close(rs,st, conn);
}
return list;
数据库连接信息放在util包内:(我这里用的是sql server 2008r2)
import java.sql.Connection; import java.sql.DriverManager; public class Shujuku { public static Connection conn(){ String url="jdbc:sqlserver://localhost:1433;DatabaseName=YourShujukuName";//填写你的数据库名 String userName="sa";//填写你的用户名,我的是sa String userPwd="tzk19991029";//填写你的密码,我的是tzk19991029 Connection con=null; try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); System.out.println("加载驱动成功!"); }catch(Exception e){ e.printStackTrace(); System.out.println("加载驱动失败!"); } try{ con=DriverManager.getConnection(url,userName,userPwd); System.out.println("连接数据库成功!"); }catch(Exception e){ e.printStackTrace(); System.out.print("SQL Server连接失败!"); } return con; } }
二.网页部分
index.jsp是首页,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>首页</title>
<style >
.a{
font-size: 26px;
margin-top: 20px;
}
</style>
</head>
<body>
<div align="center">
<h1 style="color: red;">课程基本信息管理系统</h1>
<div class="a">
<a href="add.jsp">课程信息录入</a>
</div>
<div class="a">
<a href="courseServlet?method=list">课程信息修改</a>
</div>
<div class="a">
<a href="deletebyName.jsp">课程信息删除</a>
</div>
<div class="a">
<a href="select.jsp">课程信息查询</a>
</div>
</div>
</body>
</html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
Object message = request.getAttribute("message");
if(message!=null && !"".equals(message)){
%>
<script type="text/javascript">
alert("<%=request.getAttribute("message")%>");
</script>
<%} %>
<div align="center">
<h1 style="color: red;">课程信息录入</h1>
<a href="index.jsp">返回主页</a>
<form action="courseServlet?method=add" method="post" onsubmit="return check()">
<div >
课程名称<input type="text" id="name" name="name"/>
</div>
<div >
任课教师<input type="text" id="teacher" name="teacher" />
</div>
<div >
上课地点<input type="text" id="classroom" name="classroom" />
</div>
<div >
<button type="submit" >保 存</button>
</div>
</form>
</div>
<script type="text/javascript">
function check() {
var name = document.getElementById("name");;
var teacher = document.getElementById("teacher");
var classroom = document.getElementById("classroom");
//非空
if(name.value == '') {
alert('课程名称为空');
name.focus();
return false;
}
if(teacher.value == '') {
alert('教师为空');
teacher.focus();
return false;
}
if(classroom.value == '') {
alert('上课地点为空');
classroom.focus();
return false;
}
}
</script>
</body>
</html>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <style> .tb, td { border: 1px solid black; font-size: 22px; } </style> </head> <body> <% Object message = request.getAttribute("message"); if(message!=null && !"".equals(message)){ %> <script type="text/javascript"> alert("<%=request.getAttribute("message")%>"); </script> <%} %> <div align="center"> <h1 style="color: red;">课程信息列表</h1> <a href="index.jsp">返回主页</a> <table class="tb"> <tr> <td>课程名称</td> <td>任课教师</td> <td>上课地点</td> <td align="center" colspan="2">操作</td> </tr> <c:forEach items="${courses}" var="item"> <tr> <td>${item.name}</td> <td>${item.teacher}</td> <td>${item.classroom}</td> <td><a href="courseServlet?method=getCoursebyName2&name=${item.name}">修改</a></td> </tr> </c:forEach> </table> </div> </body> </html>
deletebyName.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>删除</title> </head> <body> <% Object message = request.getAttribute("message"); if(message!=null && !"".equals(message)){ %> <script type="text/javascript"> alert("<%=request.getAttribute("message")%>"); </script> <%} %> <div align="center"> <h1 style="color: red;">课程信息删除</h1> <a href="index.jsp">返回主页</a> <form action="courseServlet?method=getCoursebyName" method="post" onsubmit="return check()"> <div > 课程名称<input type="text" id="name" name="name"/> </div> <div > <button type="submit" class="b">查 找</button> </div> </form> </div> <script type="text/javascript"> function check() { var name = document.getElementById("name");; //非空 if(name.value == '') { alert('课程名称为空'); name.focus(); return false; } } </script> </body> </html>
delete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
.tb, td {
border: 1px solid black;
font-size: 22px;
}
</style>
</head>
<body>
<div align="center">
<h1 style="color: red;">课程信息删除</h1>
<a href="index.jsp">返回主页</a>
<table class="tb">
<tr>
<td>课程名称</td>
<td>${course.name}</td>
</tr>
<tr>
<td>任课教师</td>
<td>${course.teacher}</td>
</tr>
<tr>
<td>上课地点</td>
<td>${course.classroom}</td>
</tr>
</table>
<div class="a">
<a onclick="return check()" href="courseServlet?method=delete&name=${course.name}">删 除</a>
</div>
</div>
<script type="text/javascript">
function check() {
if (confirm("真的要删除吗?")){
return true;
}else{
return false;
}
}
</script>
</body>
</html>
select.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<h1 style="color: red;">课程信息查询</h1>
<a href="index.jsp">返回主页</a>
<form action="courseServlet?method=select" method="post" onsubmit="return check()">
<div >
课程名称<input type="text" id="name" name="name"/>
</div>
<div >
任课教师<input type="text" id="teacher" name="teacher" />
</div>
<div >
上课地点<input type="text" id="classroom" name="classroom" />
</div>
<div >
<button type="submit" class="b">查 询</button>
</div>
</form>
</div>
<script type="text/javascript">
function check() {
var name = document.getElementById("name");;
var teacher = document.getElementById("teacher");
var classroom = document.getElementById("classroom");
//非空
if(name.value == '' && teacher.value == '' && classroom.value == '') {
alert('请填写一个条件');
return false;
}
}
</script>
</body>
</html>
selectlist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.tb, td {
border: 1px solid black;
font-size: 22px;
}
</style>
</head>
<body>
<div align="center">
<h1 style="color: red;">课程信息列表</h1>
<a href="index.jsp">返回主页</a>
<table class="tb">
<tr>
<td>课程名称</td>
<td>任课教师</td>
<td>上课地点</td>
</tr>
<!-- forEach遍历出adminBeans -->
<c:forEach items="${courses}" var="item">
<tr>
<td>${item.name}</td>
<td>${item.teacher}</td>
<td>${item.classroom}</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% Object message = request.getAttribute("message"); if(message!=null && !"".equals(message)){ %> <script type="text/javascript"> alert("<%=request.getAttribute("message")%>"); </script> <%} %> <div align="center"> <h1 style="color: red;">课程信息修改</h1> <a href="index.jsp">返回主页</a> <form action="courseServlet?method=update&name=${course.name}" method="post" onsubmit="return check()"> <div > 课程名称<input type="text" id="name" name="name" disabled value="${course.name}"/> </div> <div > 任课教师<input type="text" id="teacher" name="teacher" value="${course.teacher}"/> </div> <div > 上课地点<input type="text" id="classroom" name="classroom" value="${course.classroom}"/> </div> <button type="submit">修 改</button> </form> </div> <script type="text/javascript"> function check() { var name = document.getElementById("name"); var teacher = document.getElementById("teacher"); var classroom = document.getElementById("classroom"); //非空 if(teacher.value == '') { alert('教师为空'); teacher.focus(); return false; } if(classroom.value == '') { alert('上课地点为空'); classroom.focus(); return false; } } </script> </body> </html>
注意:WebContent/WEN-INF/lib包下需要放置jstl.jar包和standard.jar包。可自行去网上下载。