实现简单页面上对数据的增删改查:Java后台+数据库表+Jsp前端网页设计
这里做一个简单的学生课程信息管理系统,做之前一定要先有自己的思路,要不然对新手来说,很容易乱的。
另有一完整的代码可供参考,网页版记账本,链接https://www.cnblogs.com/sengzhao666/p/10449534.html
一.Java后台程序
可以分为三层:dao层(增删改查底层程序),service层,servlet层(网页与后台程序交互)
这三层之间,层层调用,环环相扣。
首先是写功能写的顺序分别是servlet,service,dao层:
先建立一个实体包,属性如下:
package src.entity; public class types { private int id; private String name; private String teacher; private String classroom; public int getId() { return id; } public void setId(int id) { this.id = 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 types() {} public types(int id, String name, String teacher, String classroom) { this.id = id; this.name = name; this.teacher = teacher; this.classroom = classroom; } public types(String name, String teacher, String classroom) { this.name = name; this.teacher = teacher; this.classroom = classroom; } }
servlet层代码如下:
package src.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import src.entity.types; import src.service.TypeService; public class TypeServlet extends HttpServlet{ private static final long serialVersionUID = 1L; TypeService ts=new TypeService(); /** * 方法选择 */ protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 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 ("byId".equals(method)) { byId(req, resp); } else if ("byName".equals(method)) { byName(req, resp); } else if ("list".equals(method)) { list(req, resp); } } /** * 添加 * @param req * @param resp * @throws IOException * @throws ServletException */ 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"); types type= new types(name, teacher, classroom); //添加后消息显示 if(ts.add(type)) { req.setAttribute("message", "添加成功");//setAttribute方法用于将内容保存在对象中,传到下一个页面中 req.getRequestDispatcher("add.jsp").forward(req,resp);//getRequestDispatcher方法用于进入下一个页面 } else { req.setAttribute("message", "课程名称重复,请重新录入"); req.getRequestDispatcher("add.jsp").forward(req,resp); } } /** * 删除 * @param req * @param resp * @throws IOException * @throws ServletException */ private void delete(HttpServletRequest req, HttpServletResponse resp)throws IOException, ServletException{ req.setCharacterEncoding("utf-8"); String name = req.getParameter("name"); ts.delete(name); req.setAttribute("message", "课程信息删除成功"); req.getRequestDispatcher("delete.jsp").forward(req,resp); } /** * 列表全部 * @param req * @param resp * @throws ServletException */ private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{ req.setCharacterEncoding("utf-8"); List<types> type = ts.list(); req.setAttribute("type",type); req.getRequestDispatcher("list.jsp").forward(req,resp); } /** * 通过ID得到type * 跳转至修改 * @param req * @param resp * @throws ServletException */ private void byId(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{ req.setCharacterEncoding("utf-8"); int id = Integer.parseInt(req.getParameter("id")); types type = ts.byId(id); req.setAttribute("type", type); req.getRequestDispatcher("detail.jsp").forward(req,resp); } /** * 通过名字查找 * 跳转至删除 * @param req * @param resp * @throws IOException * @throws ServletException */ private void byName(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{ req.setCharacterEncoding("utf-8"); String name = req.getParameter("name"); types type = ts.byName(name); if(type == null) { req.setAttribute("message", "查无此课程!"); req.getRequestDispatcher("delete.jsp").forward(req,resp); } else { req.setAttribute("type", type); req.getRequestDispatcher("detail2.jsp").forward(req,resp); } } /** * 修改 * @param req * @param resp * @throws IOException * @throws ServletException */ private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{ req.setCharacterEncoding("utf-8"); int id = Integer.parseInt(req.getParameter("id")); String name = req.getParameter("name"); String teacher = req.getParameter("teacher"); String classroom = req.getParameter("classroom"); types type = new types(id, name, teacher, classroom); ts.update(type); req.setAttribute("message", "修改成功"); req.getRequestDispatcher("TypeServlet?method=list").forward(req,resp); } /** * 查找 * @param req * @param resp * @throws ServletException */ private void select(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"); List<types> type = ts.select(name, teacher, classroom); req.setAttribute("type", type); req.getRequestDispatcher("selectlist.jsp").forward(req,resp); } }
service层代码如下:
package src.service; import java.util.List; import src.dao.TypeDao; import src.entity.types; import src.service.TypeService; public class TypeService{ TypeDao cDao=new TypeDao(); public boolean add(types t) { boolean f=false; if(!cDao.name(t.getName())) { cDao.add(t); f=true; } return f; } public void delete(String name) { cDao.delete(name); } public void update(types t) { cDao.update(t); } /** * 通过ID得到一个Course * @return */ public types byId(int id) { return cDao.byId(id); } /** * 通过Name得到一个Course * @return */ public types byName(String name) { return cDao.byName(name); } /** * 查找 * @return */ public List<types> select(String name, String teacher, String classroom) { return cDao.select(name, teacher, classroom); } /** * 全部数据 * @return */ public List<types> list() { return cDao.list(); } }
Dao层代码如下:
package src.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import src.entity.types; import src.util.Shujuku; public class TypeDao { public boolean add(types type) {//添加 String sql = "insert into message(name, teacher, classroom) values('" + type.getName() + "','" + type.getTeacher() + "','" + type.getClassroom() + "')"; Connection con =Shujuku.conn() ; Statement st= null; boolean f = false; int a = 0; try { st = con.createStatement(); st.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(st, con); } if (a > 0) { f = true; } return f; } public boolean delete(String name) {//删除 String sql="delete from message where name='"+name+"'"; Connection con =Shujuku.conn() ; Statement st= null; boolean f = false; int a = 0; try { st = con.createStatement(); st.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(st, con); } if (a > 0) { f = true; } return f; } public boolean update(types type) {//修改 String sql="update type set name='"+type.getName()+"',teacher='"+type.getTeacher()+"', classroom='" + type.getClassroom()+ "' where id='" + type.getId() + "'"; Connection con =Shujuku.conn() ; Statement st= null; boolean f = false; int a = 0; try { st = con.createStatement(); st.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(st, con); } if (a > 0) { f = true; } return f; } /** * 通过id得到类 * @param id * @return */ public types byId(int id) {//按照id查询,返回一个types对象 String sql = "select * from course where id ='" + id + "'"; Connection con =Shujuku.conn() ; Statement st= null; ResultSet rs = null;//返回一个结果集 types type=null; try { st = con.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { String name = rs.getString("name"); String teacher = rs.getString("teacher"); String classroom = rs.getString("classroom"); type = new types(id, name, teacher, classroom); } } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(rs,st, con); } return type; } /** * 通过名字得到类 * @param name * @return */ public types byName(String name) {//按照名字查询基本与id查询一样,sql语句不同 String sql = "select * from course where name ='" + name + "'"; Connection con =Shujuku.conn() ; Statement st= null; ResultSet rs = null; types type=null; try { st = con.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { int id = rs.getInt("id"); String teacher = rs.getString("teacher"); String classroom = rs.getString("classroom"); type = new types(id, name, teacher, classroom); } } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(rs,st, con); } return type; } public List<types> select(String name, String teacher, String classroom){//模糊查询 String sql="select*from message where"; if (name != "") { sql += "name like '%" + name + "%'"; } if (teacher != "") { sql += "teacher like '%" + teacher + "%'"; } if (classroom != "") { sql += "classroom like '%" + classroom + "%'"; } List<types> list = new ArrayList<>(); Connection con =Shujuku.conn() ; Statement st= null; ResultSet rs = null; try { st = con.createStatement(); rs = st.executeQuery(sql); types bean=null; while (rs.next()) { int id = rs.getInt("id"); String name2 = rs.getString("name"); String teacher2 = rs.getString("teacher"); String classroom2 = rs.getString("classroom"); bean = new types(id, name2, teacher2, classroom2); list.add(bean); } } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(rs,st, con); } return list; } /** * 列表全部数据 * @param name * @param teacher * @param classroom * @return */ public List<types> list(){ String sql = "select * from message"; List<types> list = new ArrayList<>(); Connection con =Shujuku.conn() ; Statement st= null; ResultSet rs = null; try { st = con.createStatement(); rs = st.executeQuery(sql); types bean=null; while (rs.next()) { int id = rs.getInt("id"); String name2 = rs.getString("name"); String teacher2 = rs.getString("teacher"); String classroom2 = rs.getString("classroom"); bean = new types(id, name2, teacher2, classroom2); list.add(bean); } } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(rs,st, con); } return list; } /** * 验证课程名称是否唯一 * true --- 不唯一 * @param name * @return */ public boolean name(String name) { String sql = "select * from course where name ='" + name + "'"; Connection con =Shujuku.conn() ; Statement st= null; ResultSet rs = null; boolean flag=false; try { st = con.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { flag = true; } } catch (Exception e) { e.printStackTrace(); } finally { Shujuku.close(rs,st, con); } return flag; } }
数据库连接信息放在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; } }
二.数据库部分:设id为主键,自增为1
三.网页部分(这里只是简单操作,不美观)
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="TypeServlet?method=list">课程信息修改</a> </div> <div class="a"> <a href="delete.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="TypeServlet?method=add" method="post" οnsubmit="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; } //教师 if(teacher.value != '王建民' && teacher.value != '王辉' && teacher.value != '刘丹' && teacher.value != '刘立嘉' && teacher.value != '杨子光'){ alert('教师名称错误'); return false; } //教室 if(!/^基教/.test(classroom.value) && !/^一教/.test(classroom.value) && !/^二教/.test(classroom.value) && !/^三教/.test(classroom.value)) { alert('上课地点错误'); 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=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="TypeServlet?method=byName" method="post" οnsubmit="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>
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="TypeServlet?method=select" method="post" οnsubmit="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>
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> </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>id</td> <td>课程名称</td> <td>任课教师</td> <td>上课地点</td> <td align="center" colspan="2">操作</td> </tr> <c:forEach items="${courses}" var="item"> <tr> <td>${item.id}</td> <td>${item.name}</td> <td>${item.teacher}</td> <td>${item.classroom}</td> <td><a href="TypeServlet?method=byId&id=${item.id}">修改</a></td> </tr> </c:forEach> </table> </div> </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>
</head>
<body>
<div align="center">
<h1 style="color: red;">课程信息列表</h1>
<a href="index.jsp">返回主页</a>
<table >
<tr>
<td>id</td>
<td>课程名称</td>
<td>任课教师</td>
<td>上课地点</td>
</tr>
<!-- forEach遍历出adminBeans -->
<c:forEach items="${types}" var="item" varStatus="status">
<tr>
<td>${item.id}</td>
<td><a>${item.name}</a></td>
<td>${item.teacher}</td>
<td>${item.classroom}</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
detail.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="TypeServlet?method=update" method="post" οnsubmit="return check()"> <div > 课程名称<input type="text" id="name" name="name" value="${type.name}"/> </div> <div > 任课教师<input type="text" id="teacher" name="teacher" value="${type.teacher}"/> </div> <div > 上课地点<input type="text" id="classroom" name="classroom" value="${type.classroom}"/> </div> <input type="hidden" id="id" name="id" value="${type.id}"/> <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 == '') { alert('课程名称为空'); name.focus(); return false; } if(teacher.value == '') { alert('教师为空'); teacher.focus(); return false; } if(classroom.value == '') { alert('上课地点为空'); classroom.focus(); return false; } //教师 if(teacher.value != '王建民' && teacher.value != '王辉' && teacher.value != '刘丹' && teacher.value != '刘立嘉' && teacher.value != '杨子光'){ alert('教师名称错误'); return false; } //教室 if(!/^基教/.test(classroom.value) && !/^一教/.test(classroom.value) && !/^二教/.test(classroom.value) && !/^三教/.test(classroom.value)) { alert('上课地点错误'); return false; } } </script> </body> </html>
deetail2.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> </head> <body> <div align="center"> <h1 style="color: red;">课程信息删除</h1> <a href="index.jsp">返回主页</a> <table class="tb"> <tr> <td>课程名称</td> <td>${type.name}</td> </tr> <tr> <td>任课教师</td> <td>${type.teacher}</td> </tr> <tr> <td>上课地点</td> <td>${type.classroom}</td> </tr> </table> <div class="a"> <a οnclick="return check()" href="TypeServlet?method=delete&id=${type.id}">删 除</a> </div> </div> <script type="text/javascript"> function check() { if (confirm("真的要删除吗?")){ return true; }else{ return false; } } </script> </body> </html>
注意:WebContent/WEN-INF/lib包下需要放置jstl.jar包和standard.jar包。可自行去网上下载。