JavaWeb+MySQL實作課程管理系統
Hello,大家好,本周博主為大家帶來一個簡單的基于JavaWeb的課程管理系統,內容詳細,好了,下面步入正題
開發環境
- jdk1.8
- mysql5.7
技術堆疊:
后端:JavaWeb+MySQL
前端:bootstarp+jsp
資料表
category分類表:
CREATE TABLE `category` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '分類id',
`cat_name` varchar(20) NOT NULL COMMENT '分類名稱',
PRIMARY KEY (`id`)
)
course課程表:
CREATE TABLE `course` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '課程id',
`course_name` varchar(20) NOT NULL COMMENT '課程名稱',
`cat_id` int(11) NOT NULL COMMENT '所屬分類的id',
`lesson_nums` int(11) DEFAULT NULL COMMENT '課程數量',
`price` decimal(7,2) DEFAULT NULL COMMENT '課程價格',
`cover_img` varchar(255) DEFAULT NULL COMMENT '課程封面圖',
`buy_count` int(11) DEFAULT NULL COMMENT '課程購買的數量',
`view_count` int(11) DEFAULT NULL COMMENT '查看課程的數量',
`status` int(11) DEFAULT NULL COMMENT '課程狀態:0:下架,1:上架',
PRIMARY KEY (`id`)
)
專案簡介
課程管理系統,可對課程分類,對課程進行增刪改查操作,課程支持上傳封面圖,可對課程名稱,價格,分類進行多條件查詢,實作課程串列的分頁
效果圖

專案結構
Java原始碼

前端結構

核心代碼
BaseServlet
該類為通用類,該類繼承于HttpServlet,攔截所有請求并通過反射的方式呼叫方法
public class BaseServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 獲取請求的URI路徑,如果 /user/login 如果訪問 /user/register
String uri = req.getRequestURI();
//2. 獲取最后 / 后面的內容, login register
String methodName = uri.substring(uri.lastIndexOf("/") + 1);
//3. 呼叫方法
try {
Method m = this.getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
m.invoke(this, req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
RouteServlet
路由跳轉類,因為所有的jsp頁面都放進了/WEB-INF下,該目錄下的檔案只支持轉發方式來訪問,一是封裝了跳轉的方法,二是跳轉時可攜帶資料
@WebServlet("/route/*")
public class RouteServlet extends BaseServlet{
CourseService courseService = new CourseServiceImpl();
CategoryService categoryService = new CategoryServiceImpl();
private static final Integer PAGE_SIZE = 2;
public void list(HttpServletRequest req, HttpServletResponse resp) {
try {
String courseName = req.getParameter("course_name");
String cid = req.getParameter("cid");
String min = req.getParameter("min");
String max = req.getParameter("max");
String strPageNumb = req.getParameter("pageNumb");
Integer pageNumb = 1;
if (!StringUtils.isEmpty(strPageNumb) && NumberUtils.isDigits(strPageNumb)) {
pageNumb = Integer.valueOf(strPageNumb);
}
PageInfo pager = courseService.queryList(pageNumb, PAGE_SIZE, courseName, cid, min, max);
List<Category> categoryList = categoryService.queryList();
req.setAttribute("courseName", courseName);
req.setAttribute("cid", cid);
req.setAttribute("min", min);
req.setAttribute("max", max);
req.setAttribute("categoryList", categoryList);
req.setAttribute("pager", pager);
req.getRequestDispatcher("/WEB-INF/list.jsp")
.forward(req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void add(HttpServletRequest req, HttpServletResponse resp) {
try {
List<Category> categoryList = categoryService.queryList();
req.setAttribute("categoryList", categoryList);
req.getRequestDispatcher("/WEB-INF/add.jsp")
.forward(req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void edit(HttpServletRequest req, HttpServletResponse resp) {
try {
String id = req.getParameter("id");
Course course = courseService.getById(id);
List<Category> categoryList = categoryService.queryList();
req.setAttribute("categoryList", categoryList);
req.setAttribute("course", course);
req.getRequestDispatcher("/WEB-INF/edit.jsp")
.forward(req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FileUploadUtils
檔案工具上傳類,該類封裝了上傳檔案方法
public class FileUploadUtils extends HttpServlet{
/**
* @param basePath 用戶指定的上傳目錄
* @return 回傳上傳之后的檔案名稱
* @throws FileUploadException
*/
public static String upload(String basePath,HttpServletRequest req) throws Exception{
//1. 先上傳檔案,并回傳上傳的檔案名稱,便于將來通過名字找到該檔案
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//將request請求的內容決議成List集合 {input[type=file],input[type=text],}
List<FileItem> list = fileUpload.parseRequest(req);
String dbpath = "";
for(FileItem item:list){
if(item.isFormField()){
//普通的文本框: <input type="text" name="username" value="張三豐">
String fieldName = item.getFieldName(); //獲取欄位名 username\route_id
String fieldValue = item.getString("UTF-8");//獲取欄位值 張三豐
req.setAttribute(fieldName, fieldValue);
}else{
//檔案上傳框 <input type="file" class="form-control" name="img_src">
//1. 獲取檔案輸入流
InputStream input = item.getInputStream();
if(input.available() > 0){
//2. 獲取檔案輸出流
//String basePath = "D:/uploads/";
//確定目標檔案名
String destFileName = UUID.randomUUID().toString().replace("-", "");
//確定目標檔案后綴:.png .jpg .gif
String originName = item.getName();
String suffix = originName.substring(originName.lastIndexOf("."));
//保存到資料庫中的相對路徑
dbpath = destFileName+suffix;
//如果當前檔案的父級目錄不存在,則創建
File destFile = new File(basePath+dbpath);
if(!destFile.getParentFile().isDirectory()){
destFile.getParentFile().mkdirs();
}
//創建檔案輸出流
FileOutputStream output = new FileOutputStream(destFile);
//3. 開始讀寫(上傳、拷貝)
byte[] arr = new byte[1024];
int res = 0;
while( (res = input.read(arr)) > 0){
output.write(arr, 0, res);
}
//關閉資源
input.close();
output.close();
}
}
}
return dbpath; // 回傳檔案名稱
}
}
前端部分代碼
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 lang="en">
<head>
<%
request.setAttribute("APP_PATH", request.getContextPath());
%>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 相對路徑,相對于當前訪問的檔案的位置開始查找 -->
<link rel="stylesheet" href="${APP_PATH}/static/admin/css/bootstrap.min.css">
<style>
.cus-container{
width: 1368px;
}
.success th,table td{text-align:center;}
</style>
</head>
<body>
<div class="container cus-container">
<h3 class="text-center" style="font-weight:bold">課程串列</h3>
<div>
<!-- 搜索框div -->
<div id="search-user" style="float: left; margin: 10px 0px;">
<form class="form-inline" action="${APP_PATH }/route/list" method="post" >
<div class="form-group">
<label for="course_name">課程名稱</label>
<input type="text" name="course_name" value="${courseName }" class="form-control" id="course_name" >
</div>
<div class="form-group">
<label>課程分類</label>
<select class="form-control" name="cid">
<option value="">請選擇</option>
<c:forEach items="${categoryList }" var="cat">
<option value="${cat.id }" ${cid == cat.id ? "selected":""}>${cat.cat_name}</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label for="exampleInputName2">價格:</label>
<input type="text" name="min" value="${min }" class="form-control" >-<input type="text" name="max" value="${max }" class="form-control" >
</div>
<input type="submit" class="btn btn-default" value="查詢">
</form>
</div>
</div>
<div>
<!-- 添加、洗掉的按鈕 -->
<div style="float: right;margin: 10px 0px;">
<a class="btn btn-primary" href="${APP_PATH}/route/add">添加課程</a>
</div>
</div>
<table class="table table-bordered clearfix">
<tr class="success">
<th>課程式號</th>
<th>課程名稱</th>
<th>分類名稱</th>
<th>總課時</th>
<th>課程價格</th>
<th>課程封面</th>
<th>購買數量</th>
<th>觀看數量</th>
<th>狀態</th>
<th>操作</th>
</tr>
<c:forEach items="${pager.courseList }" var="course">
<tr>
<td style="vertical-align:middle;width:100px">
${course.id }
</td>
<td style="vertical-align:middle;width:135px">
${course.course_name }
</td>
<td style="vertical-align:middle;">
${course.cat_name }
</td>
<td style="vertical-align:middle;">
${course.lesson_nums }
</td>
<td style="vertical-align:middle;">
${course.price }
</td>
<td style="width:200px;height:100px;vertical-align:middle;">
<img src="http://127.0.0.1/upload/images/${course.cover_img }" style="width:100%;height:100%">
</td>
<td style="vertical-align:middle;">
${course.buy_count }
</td>
<td style="vertical-align:middle;">
${course.view_count }
</td>
<td style="vertical-align:middle;">
<c:if test="${course.status == 0 }">已下架</c:if>
<c:if test="${course.status == 1 }">已上架</c:if>
</td>
<td style="vertical-align:middle;width:135px">
<a class="btn btn-default btn-sm" href="${APP_PATH}/route/edit?id=${course.id}">修改</a>
<a class="btn btn-default btn-sm" href="${APP_PATH}/course/delete?id=${course.id}&cover_img=${course.cover_img}">洗掉</a>
</td>
</tr>
</c:forEach>
</table>
<!-- 分頁導航 -->
<div>
<!-- 分頁導航 -->
<nav style="float: left;">
<ul class="pagination">
<li ${pager.pageNumb == 1 ? "class='disabled'":""}>
<a href="${APP_PATH }/route/list?pageNumb=${pager.prevPageNumb}&course_name=${courseName}&cid=${cid}&min=${min}&max=${max}" aria-label="Previous">
<span aria-hidden="true">上一頁</span>
</a>
</li>
<c:forEach begin="1" end="${pager.pageCount }" var="i">
<li ${pager.pageNumb == i ? "class='active'":"" }>
<a href="${APP_PATH }/route/list?pageNumb=${i}&course_name=${courseName}&cid=${cid}&min=${min}&max=${max}">${i}</a>
</li>
</c:forEach>
<li ${pager.pageNumb == pager.pageCount ? "class='disabled'":""}>
<a href="${APP_PATH }/route/list?pageNumb=${pager.nextPageNumb}&course_name=${courseName}&cid=${cid}&min=${min}&max=${max}" aria-label="Previous">
<span aria-hidden="true">下一頁</span>
</a>
</li>
</ul>
</nav>
<div style="float: right;margin-top: 25px;">
<span>共${pager.total}條記錄,分${pager.pageCount}頁顯示</span>
</div>
</div>
</div>
</body>
</html>
add.jsp
注意:form表單需加 enctype=“multipart/form-data”
將表單設定為支持圖片上傳
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<%
request.setAttribute("APP_PATH", request.getContextPath());
%>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="${APP_PATH}/static/admin/css/bootstrap.min.css">
<script src="${APP_PATH}/static/admin/js/jquery-2.1.0.min.js"></script>
<script src="${APP_PATH}/static/admin/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container cus-container">
<h3 class="text-center" style="font-weight:bold">添加課程</h3>
<form action="${APP_PATH}/course/addHandle" method="post"
enctype="multipart/form-data">
<div class="form-group">
<label for="user">課程名稱:</label>
<input type="text" class="form-control" name="course_name">
</div>
<div class="form-group">
<label for="user">所屬分類:</label>
<select class="form-control" name="cid">
<option value="0">請選擇</option>
<c:forEach items="${categoryList }" var="cat">
<option value="${cat.id }">${cat.cat_name }</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label for="user">課程封面圖:</label>
<input type="file" class="form-control" name="cover_img">
</div>
<div class="form-group">
<label for="user">課時數:</label>
<input type="text" class="form-control" name="lesson_nums">
</div>
<div class="form-group">
<label for="user">價格:</label>
<input type="text" class="form-control" name="price">
</div>
<div class="form-group">
<label for="user">狀態:</label>
<div class="radio">
<label>
<input type="radio" name="status" value=1>
上架
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="status" value="0">
下架
</label>
</div>
</div>
<div class="text-center">
<input type="submit" class="btn btn-primary" value="提交">
<button type="reset" class="btn btn-default">重置</button>
</div>
</form>
</div>
</body>
</html>
結語
專案到此就結束了,對本專案感興趣的小伙伴,可在下方鏈接獲取完整專案
戳,獲取完整專案 —> 專案地址
提取碼: hmpp
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/301509.html
標籤:java
