Java後臺+資料庫+Java web前端(新手)
阿新 • • 發佈:2018-12-19
實現簡單頁面上對資料的增刪改查:Java後臺+資料庫表+Jsp前端網頁設計
這裡做一個簡單的學生課程資訊管理系統,做之前一定要先有自己的思路,要不然對新手來說,很容易亂的。
一.Java後臺程式
可以分為三層:dao層(增刪改查底層程式),service層,servlet層(網頁與後臺程式互動)
這三層之間,層層呼叫,環環相扣。
首先是寫功能寫的順序分別是servlet,service,dao層:
先建立一個實體包,屬性如下:
package src.entity; public class types { private int id; privateString 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" 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; } //教師 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" 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>
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" 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>
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" onsubmit="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 onclick="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包。可自行去網上下載。