java web課程管理系統開發實例(從數據庫連接到代碼)


以下是幾個簡單知識:

JavaBean:用於傳遞數據,擁有與數據相關的邏輯處理

JSP:從Model接收數據並生成HTML

Servlet:接收HTTP請求並控制Model和View

jdbc:用於配置環境

 

前言:相關的軟件下載和環境配置

1、下載並配置JDK。

2、下載eclipse。

3、下載並配置apache-tomcat(服務器)。

4、下載MySQL(數據庫)。

5、下載Navicat for MySQL(數據庫可視化工具),方便對數據庫的操作。

6、下載jdbc用來實現eclipse中的項目與數據庫實現連接。

(看網上教程就好)

一、【建立數據庫】

 庫中設有課程,教師,教室三個值

二、【新建web項目

打開eclipse,點擊File—》New—》other—》Dynamic Web Project

 

點擊Next

需要輸入項目名,最好用英文填寫,完成之后eclipse左側會有剛剛創建的項目出現下圖

 

在我的電腦中,打開你下載的jdbc(也就是mysql-connector-java-8.0.13)所在的文件夾中的

 

 

將mysql-connector-java-8.0.13文件復制

粘貼在eclipse中,你所建立的項目下的 WebContent/WEB-INF/lib 文件夾下,如下圖

接下來便是jsp文件和java文件的寫入了.

代碼如下:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>Insert title here</title>
 8 <style>
 9     .a{
10         margin-top: 20px;
11     }
12     .b{
13         font-size: 20px;
14         width: 160px;
15         color: white;
16         background-color: greenyellow;
17     }
18 </style>
19 </head>
20 <body>
21     <%
22          Object message = request.getAttribute("message");
23          if(message!=null && !"".equals(message)){
24       
25     %>
26          <script type="text/javascript">
27               alert("<%=request.getAttribute("message")%>");
28          </script>
29     <%} %>
30     <div align="center">
31         <h1 style="color: red;">課程信息錄入</h1>
32         <a href="index.jsp">返回主頁</a>
33         <form action="CourseServlet?method=add" method="post" onsubmit="return check()">
34             <div class="a">
35                 課程名稱<input type="text" id="name" name="name"/>
36             </div>
37             <div class="a">
38                 任課教師<input type="text" id="teacher" name="teacher" />
39             </div>
40             <div class="a">
41                 上課地點<input type="text" id="classroom" name="classroom" />
42             </div>
43             <div class="a">
44                 <button type="submit" class="b">保   存</button>
45             </div>
46         </form>
47     </div>
48     <script type="text/javascript">
49         function check() {
50             var name = document.getElementById("name");;
51             var teacher = document.getElementById("teacher");
52             var classroom = document.getElementById("classroom");
53              
54             //非空
55             if(name.value == '') {
56                 alert('課程名稱為空');
57                 name.focus();
58                 return false;
59             }
60             if(teacher.value == '') {
61                 alert('教師為空');
62                 teacher.focus();
63                 return false;
64             }
65             if(classroom.value == '') {
66                 alert('上課地點為空');
67                 classroom.focus();
68                 return false;
69             }
70              
71             //教師
72             if(teacher.value != '王建民' && teacher.value != '王輝' && teacher.value != '劉丹' && teacher.value != '劉立嘉' && teacher.value != '楊子光'){
73                 alert('教師名稱錯誤');
74                 return false;
75             }
76              
77             //教室
78             if(!/^基教/.test(classroom.value) && !/^一教/.test(classroom.value) && !/^二教/.test(classroom.value) && !/^三教/.test(classroom.value)) {
79                 alert('上課地點錯誤');
80                 return false;
81             }
82         }
83     </script>
84 </body>
85 </html>
add.jsp
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>Insert title here</title>
 8 <style>
 9     .a{
10         margin-top: 20px;
11     }
12     .b{
13         font-size: 20px;
14         width: 160px;
15         color: white;
16         background-color: greenyellow;
17     }
18 </style>
19 </head>
20 <body>
21     <%
22          Object message = request.getAttribute("message");
23          if(message!=null && !"".equals(message)){
24       
25     %>
26          <script type="text/javascript">
27               alert("<%=request.getAttribute("message")%>");
28          </script>
29     <%} %>
30     <div align="center">
31         <h1 style="color: red;">課程信息刪除</h1>
32         <a href="index.jsp">返回主頁</a>
33         <form action="CourseServlet?method=getcoursebyname" method="post" onsubmit="return check()">
34             <div class="a">
35                 課程名稱<input type="text" id="name" name="name"/>
36             </div>
37             <div class="a">
38                 <button type="submit" class="b">查   找</button>
39             </div>
40         </form>
41     </div>
42     <script type="text/javascript">
43         function check() {
44             var name = document.getElementById("name");;
45              
46             //非空
47             if(name.value == '') {
48                 alert('課程名稱為空');
49                 name.focus();
50                 return false;
51             }
52         }
53     </script>
54 </body>
55 </html>
del.jsp
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>Insert title here</title>
 8 <style>
 9     .a{
10         margin-top: 20px;
11     }
12     .b{
13         font-size: 20px;
14         width: 160px;
15         color: white;
16         background-color: greenyellow;
17     }
18     .tb, td {
19         border: 1px solid black;
20         font-size: 22px;
21     }
22 </style>
23 </head>
24 <body>
25     <div align="center">
26         <h1 style="color: red;">課程信息刪除</h1>
27         <a href="index.jsp">返回主頁</a>
28         <table class="tb">
29             <tr>
30                 <td>課程名稱</td>
31                 <td>${course.name}</td>
32             </tr>
33             <tr>
34                 <td>任課教師</td>
35                 <td>${course.teacher}</td>
36             </tr>
37             <tr>
38                 <td>上課地點</td>
39                 <td>${course.classroom}</td>
40             </tr>
41         </table>
42         <div class="a">
43             <a onclick="return check()" href="CourseServlet?method=del&id=${course.id}">刪   除</a>
44         </div>
45     </div>
46     <script type="text/javascript">
47         function check() {
48             if (confirm("真的要刪除嗎?")){
49                 return true;
50             }else{
51                 return false;
52             }
53         }
54     </script>
55 </body>
56 </html>
detail.jsp
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>Insert title here</title>
 8 <style>
 9     .a{
10         margin-top: 20px;
11     }
12     .b{
13         font-size: 20px;
14         width: 160px;
15         color: white;
16         background-color: greenyellow;
17     }
18 </style>
19 </head>
20 <body>
21     <%
22          Object message = request.getAttribute("message");
23          if(message!=null && !"".equals(message)){
24       
25     %>
26          <script type="text/javascript">
27               alert("<%=request.getAttribute("message")%>");
28          </script>
29     <%} %>
30     <div align="center">
31         <h1 style="color: red;">課程信息修改</h1>
32         <a href="index.jsp">返回主頁</a>
33         <form action="CourseServlet?method=update" method="post" onsubmit="return check()">
34             <div class="a">
35                 課程名稱<input type="text" id="name" name="name" value="${course.name}"/>
36             </div>
37             <div class="a">
38                 任課教師<input type="text" id="teacher" name="teacher" value="${course.teacher}"/>
39             </div>
40             <div class="a">
41                 上課地點<input type="text" id="classroom" name="classroom" value="${course.classroom}"/>
42             </div>
43             <input type="hidden" id="id" name="id" value="${course.id}"/>
44             <div class="a">
45                 <button type="submit" class="b">修   改</button>
46             </div>
47         </form>
48     </div>
49     <script type="text/javascript">
50         function check() {
51             var name = document.getElementById("name");;
52             var teacher = document.getElementById("teacher");
53             var classroom = document.getElementById("classroom");
54              
55             //非空
56             if(name.value == '') {
57                 alert('課程名稱為空');
58                 name.focus();
59                 return false;
60             }
61             if(teacher.value == '') {
62                 alert('教師為空');
63                 teacher.focus();
64                 return false;
65             }
66             if(classroom.value == '') {
67                 alert('上課地點為空');
68                 classroom.focus();
69                 return false;
70             }
71              
72             //教師
73             if(teacher.value != '王建民' && teacher.value != '王輝' && teacher.value != '劉丹' && teacher.value != '劉立嘉' && teacher.value != '楊子光'){
74                 alert('教師名稱錯誤');
75                 return false;
76             }
77              
78             //教室
79             if(!/^基教/.test(classroom.value) && !/^一教/.test(classroom.value) && !/^二教/.test(classroom.value) && !/^三教/.test(classroom.value)) {
80                 alert('上課地點錯誤');
81                 return false;
82             }
83         }
84     </script>
85 </body>
86 </html>
detail2.jsp
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>首頁</title>
 8 <style>
 9     .a{
10         font-size: 26px;
11         margin-top: 20px;
12     }
13 </style>
14 </head>
15 <body>
16     <div align="center">
17         <h1 style="color: red;">課程基本信息管理系統</h1>
18         <div class="a">
19             <a href="add.jsp">課程信息錄入</a>
20         </div>
21         <div class="a">
22             <a href="CourseServlet?method=list">課程信息修改</a>
23         </div>
24         <div class="a">
25             <a href="del.jsp">課程信息刪除</a>
26         </div>
27         <div class="a">
28             <a href="search.jsp">課程信息查詢</a>
29         </div>
30     </div>
31 </body>
32 </html>
index
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>Insert title here</title>
 9 <style>
10     .a{
11         margin-top: 20px;
12     }
13     .b{
14         font-size: 20px;
15         width: 160px;
16         color: white;
17         background-color: greenyellow;
18     }
19     .tb, td {
20         border: 1px solid black;
21         font-size: 22px;
22     }
23 </style>
24 </head>
25 <body>
26     <%
27          Object message = request.getAttribute("message");
28          if(message!=null && !"".equals(message)){
29       
30     %>
31          <script type="text/javascript">
32               alert("<%=request.getAttribute("message")%>");
33          </script>
34     <%} %>
35     <div align="center">
36         <h1 style="color: red;">課程信息列表</h1>
37         <a href="index.jsp">返回主頁</a>
38         <table class="tb">
39             <tr>
40                 <td>id</td>
41                 <td>課程名稱</td>
42                 <td>任課教師</td>
43                 <td>上課地點</td>
44                 <td align="center" colspan="2">操作</td>
45             </tr>
46             <c:forEach items="${courses}" var="item">
47                 <tr>
48                     <td>${item.id}</td>
49                     <td>${item.name}</td>
50                     <td>${item.teacher}</td>
51                     <td>${item.classroom}</td>
52                     <td><a href="CourseServlet?method=getcoursebyid&id=${item.id}">修改</a></td>
53                 </tr>
54             </c:forEach>
55         </table>
56     </div>
57 </body>
58 </html>
list.jsp
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html>
 4 <html>
 5 <head>
 6 <meta charset="UTF-8">
 7 <title>Insert title here</title>
 8 <style>
 9     .a{
10         margin-top: 20px;
11     }
12     .b{
13         font-size: 20px;
14         width: 160px;
15         color: white;
16         background-color: greenyellow;
17     }
18 </style>
19 </head>
20 <body>
21     <div align="center">
22         <h1 style="color: red;">課程信息查詢</h1>
23         <a href="index.jsp">返回主頁</a>
24         <form action="CourseServlet?method=search" method="post" onsubmit="return check()">
25             <div class="a">
26                 課程名稱<input type="text" id="name" name="name"/>
27             </div>
28             <div class="a">
29                 任課教師<input type="text" id="teacher" name="teacher" />
30             </div>
31             <div class="a">
32                 上課地點<input type="text" id="classroom" name="classroom" />
33             </div>
34             <div class="a">
35                 <button type="submit" class="b">查   詢</button>
36             </div>
37         </form>
38     </div>
39     <script type="text/javascript">
40         function check() {
41             var name = document.getElementById("name");;
42             var teacher = document.getElementById("teacher");
43             var classroom = document.getElementById("classroom");
44              
45             //非空
46             if(name.value == '' && teacher.value == '' && classroom.value == '') {
47                 alert('請填寫一個條件');
48                 return false;
49             }
50         }
51     </script>
52 </body>
53 </html>
search.jsp
 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>Insert title here</title>
 9 <style>
10     .a{
11         margin-top: 20px;
12     }
13     .b{
14         font-size: 20px;
15         width: 160px;
16         color: white;
17         background-color: greenyellow;
18     }
19     .tb, td {
20         border: 1px solid black;
21         font-size: 22px;
22     }
23 </style>
24 </head>
25 <body>
26     <div align="center">
27         <h1 style="color: red;">課程信息列表</h1>
28         <a href="index.jsp">返回主頁</a>
29         <table class="tb">
30             <tr>
31                 <td>id</td>
32                 <td>課程名稱</td>
33                 <td>任課教師</td>
34                 <td>上課地點</td>
35             </tr>
36             <!-- forEach遍歷出adminBeans -->
37             <c:forEach items="${courses}" var="item" varStatus="status">
38                 <tr>
39                     <td>${item.id}</td>
40                     <td><a>${item.name}</a></td>
41                     <td>${item.teacher}</td>
42                     <td>${item.classroom}</td>
43                 </tr>
44             </c:forEach>
45         </table>
46     </div>
47 </body>
48 </html>
searchlist.jsp

直接在上圖中一起建立包和類

 1 package com.hjf;
 2  
 3 public class Course {
 4  
 5     private int id;
 6     private String name;
 7     private String teacher;
 8     private String classroom;
 9      
10     public int getId() {
11         return id;
12     }
13     public void setId(int id) {
14         this.id = id;
15     }
16     public String getName() {
17         return name;
18     }
19     public void setName(String name) {
20         this.name = name;
21     }
22     public String getTeacher() {
23         return teacher;
24     }
25     public void setTeacher(String teacher) {
26         this.teacher = teacher;
27     }
28     public String getClassroom() {
29         return classroom;
30     }
31     public void setClassroom(String classroom) {
32         this.classroom = classroom;
33     }
34      
35     public Course() {}
36      
37     public Course(int id, String name, String teacher, String classroom) {
38         this.id = id;
39         this.name = name;
40         this.teacher = teacher;
41         this.classroom = classroom;
42     }
43      
44     public Course(String name, String teacher, String classroom) {
45         this.name = name;
46         this.teacher = teacher;
47         this.classroom = classroom;
48     }
49 }
Course.java
  1 package com.hjf;
  2  
  3 import java.sql.Connection;
  4  
  5 import java.sql.ResultSet;
  6 import java.sql.SQLException;
  7 import java.sql.Statement;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10  
 11  
 12  
 13 /**
 14  * 課程Dao
 15  * Dao層操作數據
 16  * @author Hu
 17  *
 18  */
 19 public class CourseDao {
 20  
 21     /**
 22      * 添加
 23      * @param course
 24      * @return
 25      */
 26     public boolean add(Course course) {
 27         String sql = "insert into course(name, teacher, classroom) values('" + course.getName() + "','" + course.getTeacher() + "','" + course.getClassroom() + "')";
 28         Connection conn = DBUtil.getConn();
 29         Statement state = null;
 30         boolean f = false;
 31         int a = 0;
 32          
 33         try {
 34             state = conn.createStatement();
 35             state.executeUpdate(sql);
 36         } catch (Exception e) {
 37             e.printStackTrace();
 38         } finally {
 39             DBUtil.close(state, conn);
 40         }
 41          
 42         if (a > 0) {
 43             f = true;
 44         }
 45         return f;
 46     }
 47  
 48     /**
 49      * 刪除
 50      *
 51      * @param id
 52      * @return
 53      */
 54     public boolean delete (int id) {
 55         boolean f = false;
 56         String sql = "delete from course where id='" + id + "'";
 57         Connection conn = DBUtil.getConn();
 58         Statement state = null;
 59         int a = 0;
 60          
 61         try {
 62             state = conn.createStatement();
 63             a = state.executeUpdate(sql);
 64         } catch (SQLException e) {
 65             e.printStackTrace();
 66         } finally {
 67             DBUtil.close(state, conn);
 68         }
 69          
 70         if (a > 0) {
 71             f = true;
 72         }
 73         return f;
 74     }
 75  
 76     /**
 77      * 修改
 78      * @param name
 79      * @param pass
 80      */
 81     public boolean update(Course course) {
 82         String sql = "update course set name='" + course.getName() + "', teacher='" + course.getTeacher() + "', classroom='" + course.getClassroom()
 83             + "' where id='" + course.getId() + "'";
 84         Connection conn = DBUtil.getConn();
 85         Statement state = null;
 86         boolean f = false;
 87         int a = 0;
 88  
 89         try {
 90             state = conn.createStatement();
 91             a = state.executeUpdate(sql);
 92         } catch (SQLException e) {
 93             e.printStackTrace();
 94         } finally {
 95             DBUtil.close(state, conn);
 96         }
 97          
 98         if (a > 0) {
 99             f = true;
100         }
101         return f;
102     }
103      
104     /**
105      * 驗證課程名稱是否唯一
106      * true --- 不唯一
107      * @param name
108      * @return
109      */
110     public boolean name(String name) {
111         boolean flag = false;
112         String sql = "select name from course where name = '" + name + "'";
113         Connection conn = DBUtil.getConn();
114         Statement state = null;
115         ResultSet rs = null;
116          
117         try {
118             state = conn.createStatement();
119             rs = state.executeQuery(sql);
120             while (rs.next()) {
121                 flag = true;
122             }
123         } catch (SQLException e) {
124             e.printStackTrace();
125         } finally {
126             DBUtil.close(rs, state, conn);
127         }
128         return flag;
129     }
130      
131     /**
132      * 通過ID得到類
133      * @param id
134      * @return
135      */
136     public Course getCourseById(int id) {
137         String sql = "select * from course where id ='" + id + "'";
138         Connection conn = DBUtil.getConn();
139         Statement state = null;
140         ResultSet rs = null;
141         Course course = null;
142          
143         try {
144             state = conn.createStatement();
145             rs = state.executeQuery(sql);
146             while (rs.next()) {
147                 String name = rs.getString("name");
148                 String teacher = rs.getString("teacher");
149                 String classroom = rs.getString("classroom");
150                 course = new Course(id, name, teacher, classroom);
151             }
152         } catch (Exception e) {
153             e.printStackTrace();
154         } finally {
155             DBUtil.close(rs, state, conn);
156         }
157          
158         return course;
159     }
160      
161     /**
162      * 通過name得到Course
163      * @param name
164      * @return
165      */
166     public Course getCourseByName(String name) {
167         String sql = "select * from course where name ='" + name + "'";
168         Connection conn = DBUtil.getConn();
169         Statement state = null;
170         ResultSet rs = null;
171         Course course = null;
172          
173         try {
174             state = conn.createStatement();
175             rs = state.executeQuery(sql);
176             while (rs.next()) {
177                 int id = rs.getInt("id");
178                 String teacher = rs.getString("teacher");
179                 String classroom = rs.getString("classroom");
180                 course = new Course(id, name, teacher, classroom);
181             }
182         } catch (Exception e) {
183             e.printStackTrace();
184         } finally {
185             DBUtil.close(rs, state, conn);
186         }
187          
188         return course;
189     }
190      
191     /**
192      * 查找
193      * @param name
194      * @param teacher
195      * @param classroom
196      * @return
197      */
198     public List<Course> search(String name, String teacher, String classroom) {
199         String sql = "select * from course where ";
200         if (name != "") {
201             sql += "name like '%" + name + "%'";
202         }
203         if (teacher != "") {
204             sql += "teacher like '%" + teacher + "%'";
205         }
206         if (classroom != "") {
207             sql += "classroom like '%" + classroom + "%'";
208         }
209         List<Course> list = new ArrayList<>();
210         Connection conn = DBUtil.getConn();
211         Statement state = null;
212         ResultSet rs = null;
213  
214         try {
215             state = conn.createStatement();
216             rs = state.executeQuery(sql);
217             Course bean = null;
218             while (rs.next()) {
219                 int id = rs.getInt("id");
220                 String name2 = rs.getString("name");
221                 String teacher2 = rs.getString("teacher");
222                 String classroom2 = rs.getString("classroom");
223                 bean = new Course(id, name2, teacher2, classroom2);
224                 list.add(bean);
225             }
226         } catch (SQLException e) {
227             e.printStackTrace();
228         } finally {
229             DBUtil.close(rs, state, conn);
230         }
231          
232         return list;
233     }
234      
235     /**
236      * 全部數據
237      * @param name
238      * @param teacher
239      * @param classroom
240      * @return
241      */
242     public List<Course> list() {
243         String sql = "select * from course";
244         List<Course> list = new ArrayList<>();
245         Connection conn = DBUtil.getConn();
246         Statement state = null;
247         ResultSet rs = null;
248  
249         try {
250             state = conn.createStatement();
251             rs = state.executeQuery(sql);
252             Course bean = null;
253             while (rs.next()) {
254                 int id = rs.getInt("id");
255                 String name2 = rs.getString("name");
256                 String teacher2 = rs.getString("teacher");
257                 String classroom2 = rs.getString("classroom");
258                 bean = new Course(id, name2, teacher2, classroom2);
259                 list.add(bean);
260             }
261         } catch (SQLException e) {
262             e.printStackTrace();
263         } finally {
264             DBUtil.close(rs, state, conn);
265         }
266          
267         return list;
268     }
269  
270 }
CourseDao.java
 1 package com.hjf;
 2  
 3 import java.util.List;
 4  
 5 /**
 6  * CourseService
 7  * 服務層
 8  * @author Hu
 9  *
10  */
11 public class CourseService {
12  
13     CourseDao cDao = new CourseDao();
14      
15     /**
16      * 添加
17      * @param course
18      * @return
19      */
20     public boolean add(Course course) {
21         boolean f = false;
22         if(!cDao.name(course.getName())) {
23             cDao.add(course);
24             f = true;
25         }
26         return f;
27     }
28      
29     /**
30      * 刪除
31      */
32     public void del(int id) {
33         cDao.delete(id);
34     }
35      
36     /**
37      * 修改
38      * @return
39      */
40     public void update(Course course) {
41         cDao.update(course);
42     }
43      
44     /**
45      * 通過ID得到一個Course
46      * @return
47      */
48     public Course getCourseById(int id) {
49         return cDao.getCourseById(id);
50     }
51  
52     /**
53      * 通過Name得到一個Course
54      * @return
55      */
56     public Course getCourseByName(String name) {
57         return cDao.getCourseByName(name);
58     }
59      
60     /**
61      * 查找
62      * @return
63      */
64     public List<Course> search(String name, String teacher, String classroom) {
65         return cDao.search(name, teacher, classroom);
66     }
67      
68     /**
69      * 全部數據
70      * @return
71      */
72     public List<Course> list() {
73         return cDao.list();
74     }
75 }
CourseService
  1 package com.hjf;
  2  
  3 import java.io.IOException;
  4  
  5  
  6 import java.util.List;
  7  
  8 import javax.servlet.ServletException;
  9 import javax.servlet.annotation.WebServlet;
 10 import javax.servlet.http.HttpServlet;
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.servlet.http.HttpServletResponse;
 13  
 14 @WebServlet("/CourseServlet")
 15 public class CourseServlet extends HttpServlet {
 16      
 17     private static final long serialVersionUID = 1L;
 18  
 19     CourseService service = new CourseService();
 20      
 21     /**
 22      * 方法選擇
 23      */
 24     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 25         req.setCharacterEncoding("utf-8");
 26         String method = req.getParameter("method");
 27         if ("add".equals(method)) {
 28             add(req, resp);
 29         } else if ("del".equals(method)) {
 30             del(req, resp);
 31         } else if ("update".equals(method)) {
 32             update(req, resp);
 33         } else if ("search".equals(method)) {
 34             search(req, resp);
 35         } else if ("getcoursebyid".equals(method)) {
 36             getCourseById(req, resp);
 37         } else if ("getcoursebyname".equals(method)) {
 38             getCourseByName(req, resp);
 39         } else if ("list".equals(method)) {
 40             list(req, resp);
 41         }
 42     }
 43  
 44     /**
 45      * 添加
 46      * @param req
 47      * @param resp
 48      * @throws IOException
 49      * @throws ServletException
 50      */
 51     private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
 52         req.setCharacterEncoding("utf-8");
 53         String name = req.getParameter("name");
 54         String teacher = req.getParameter("teacher");
 55         String classroom = req.getParameter("classroom");
 56         Course course = new Course(name, teacher, classroom);
 57          
 58         //添加后消息顯示
 59         if(service.add(course)) {
 60             req.setAttribute("message", "添加成功");
 61             req.getRequestDispatcher("add.jsp").forward(req,resp);
 62         } else {
 63             req.setAttribute("message", "課程名稱重復,請重新錄入");
 64             req.getRequestDispatcher("add.jsp").forward(req,resp);
 65         }
 66     }
 67      
 68     /**
 69      * 全部
 70      * @param req
 71      * @param resp
 72      * @throws ServletException
 73      */
 74     private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
 75         req.setCharacterEncoding("utf-8");
 76         List<Course> courses = service.list();
 77         req.setAttribute("courses", courses);
 78         req.getRequestDispatcher("list.jsp").forward(req,resp);
 79     }
 80  
 81     /**
 82      * 通過ID得到Course
 83      * @param req
 84      * @param resp
 85      * @throws ServletException
 86      */
 87     private void getCourseById(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
 88         req.setCharacterEncoding("utf-8");
 89         int id = Integer.parseInt(req.getParameter("id"));
 90         Course course = service.getCourseById(id);
 91         req.setAttribute("course", course);
 92         req.getRequestDispatcher("detail2.jsp").forward(req,resp);
 93     }
 94  
 95     /**
 96      * 通過名字查找
 97      * 跳轉至刪除
 98      * @param req
 99      * @param resp
100      * @throws IOException
101      * @throws ServletException
102      */
103     private void getCourseByName(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
104         req.setCharacterEncoding("utf-8");
105         String name = req.getParameter("name");
106         Course course = service.getCourseByName(name);
107         if(course == null) {
108             req.setAttribute("message", "查無此課程!");
109             req.getRequestDispatcher("del.jsp").forward(req,resp);
110         } else {
111             req.setAttribute("course", course);
112             req.getRequestDispatcher("detail.jsp").forward(req,resp);
113         }
114     }
115      
116     /**
117      * 刪除
118      * @param req
119      * @param resp
120      * @throws IOException
121      * @throws ServletException
122      */
123     private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
124         req.setCharacterEncoding("utf-8");
125         int id = Integer.parseInt(req.getParameter("id"));
126         service.del(id);
127         req.setAttribute("message", "刪除成功!");
128         req.getRequestDispatcher("del.jsp").forward(req,resp);
129     }
130      
131     /**
132      * 修改
133      * @param req
134      * @param resp
135      * @throws IOException
136      * @throws ServletException
137      */
138     private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
139         req.setCharacterEncoding("utf-8");
140         int id = Integer.parseInt(req.getParameter("id"));
141         String name = req.getParameter("name");
142         String teacher = req.getParameter("teacher");
143         String classroom = req.getParameter("classroom");
144         Course course = new Course(id, name, teacher, classroom);
145          
146         service.update(course);
147         req.setAttribute("message", "修改成功");
148         req.getRequestDispatcher("CourseServlet?method=list").forward(req,resp);
149     }
150      
151     /**
152      * 查找
153      * @param req
154      * @param resp
155      * @throws ServletException
156      */
157     private void search(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
158         req.setCharacterEncoding("utf-8");
159         String name = req.getParameter("name");
160         String teacher = req.getParameter("teacher");
161         String classroom = req.getParameter("classroom");
162         List<Course> courses = service.search(name, teacher, classroom);
163         req.setAttribute("courses", courses);
164         req.getRequestDispatcher("searchlist.jsp").forward(req,resp);
165     }
166 }
CourseServlet.java
 1 package com.hjf;
 2  
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8  
 9 /**
10  * 數據庫連接工具
11  * @author Hu
12  *
13  */
14 public class DBUtil {
15      
16     public static String db_url = "jdbc:mysql://localhost:3306/course?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
17     public static String db_user = "root";
18     public static String db_pass = "123";
19      
20     public static Connection getConn () {
21         Connection conn = null;
22          
23         try {
24             Class.forName("com.mysql.jdbc.Driver");//加載驅動
25             conn = DriverManager.getConnection(db_url, db_user, db_pass);
26         } catch (Exception e) {
27             e.printStackTrace();
28         }
29          
30         return conn;
31     }
32      
33     /**
34      * 關閉連接
35      * @param state
36      * @param conn
37      */
38     public static void close (Statement state, Connection conn) {
39         if (state != null) {
40             try {
41                 state.close();
42             } catch (SQLException e) {
43                 e.printStackTrace();
44             }
45         }
46          
47         if (conn != null) {
48             try {
49                 conn.close();
50             } catch (SQLException e) {
51                 e.printStackTrace();
52             }
53         }
54     }
55      
56     public static void close (ResultSet rs, Statement state, Connection conn) {
57         if (rs != null) {
58             try {
59                 rs.close();
60             } catch (SQLException e) {
61                 e.printStackTrace();
62             }
63         }
64          
65         if (state != null) {
66             try {
67                 state.close();
68             } catch (SQLException e) {
69                 e.printStackTrace();
70             }
71         }
72          
73         if (conn != null) {
74             try {
75                 conn.close();
76             } catch (SQLException e) {
77                 e.printStackTrace();
78             }
79         }
80     }
81  
82 }
DBUtil.java

關於為什么有的類需要單獨一個包

為了不同項目間更好的對接.

附:

 目錄說明 
com.astar 
- config 用於放置配置文件,資源文件等。如Spring配置文件applicationContext.xml 
- background 后台管理層結構 
- common 項目中公用的文件,如下 
- constant 常量 
- enumeration 枚舉類 
- util 工具類 
- dao 抽象接口及實現類,用於放置封裝好的底層數據訪問操作。如JPA的CURD 
- service 抽象業務接口及實現類,用於調用同層dao目錄中的DAO對象,便於被實現和繼承 
- controller 控制層,通過SpringMVC 實現請求處理,並轉發。 
- entity 實體層,用於放置項目中的公用實體 
- filter 過濾層,放置過濾器 
- center/finance/printer/keeper/editor 這是項目中的角色,每個角色作為一個獨立層,便於分工和解耦,使每層中的業務功能內聚 
- service 獨立的,特有的業務 
- dao 通過該層自己來處理DAO

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM