javaweb添加课程mysql8.0版本
Posted stdxxd
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaweb添加课程mysql8.0版本相关的知识,希望对你有一定的参考价值。
搞了好几天终于搞好了,虽然代码有些不同但是功能实现,并且于mysql 8.0版本。废话不多说直接开搞。
需要的工具
自己去下 简单的雅痞。
结构如下
lib目录下必须导入连接包 否则会出现错误500无法连接
两个jsp文件不要添加在web-inf里面 因为这里面导入东西是无法访问的
直接在webapp里面新建jsp文件,代码如下。
ClassDao.java
package ceshi;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import ceshi.DBUtil;
import ceshi.HaveClass;
import ceshi.ClassDao;
public class ClassDao {
public void add(HaveClass course) {
//或得数据库连接对象
Connection connection = DBUtil.getConnection();
//准备SQL语句
String sql =null; //"select count(*) from tab_user where username=?";
//声明数据库准备执行对象,但是没有实例化,赋值为空
PreparedStatement preparedStatement = null;
//声明一个结果集对象,用于接收,我们我们pre执行后,发送到数据库的sql语句,然后数据库执行,在然后返回到我们程序端的
//结果集对象
//ResultSet resultSet = null;
/*数据库,让数据库处理,然后把结果集返回回来,用resultSet.
//这个是重点,这里才是真正连接数据库,然后执行的地方
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
if(resultSet.getInt(1)>0)
throw new UserException("用户已存在");
}*/
try {
sql="insert into grade(classname,classtea,classspace) value(?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, course.getClassname());
preparedStatement.setString(2, course.getTeachername());
preparedStatement.setString(3, course.getPlace());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//DBUtil.close(resultSet);
DBUtil.close(preparedStatement);
DBUtil.close(connection);
}
}
}
DBUtil.java
package ceshi;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBUtil {
public static Connection getConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e1) {
e1.printStackTrace();
}
String user = "root";
String password = "123456";
String url = "jdbc:mysql://localhost:3306/test?&useSSL=false&serverTimezone=UTC";
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(PreparedStatement preparedStatement) {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
HaveClass.java
package ceshi;
public class HaveClass {
private String teachername;
private String place;
private String classname;
public String getTeachername() {
return teachername;
}
public void setTeachername(String teachername) {
this.teachername = teachername;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
}
addClass.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>课程添加</title>
</head>
<body>
<center><%=request.getAttribute("result") %>
<form action="class.jsp" method ="get">
<table align="center" border="1" >
<tr>
<td>课程名</td>
<td>
<input type="text" name="classname"/>
</td>
</tr>
<tr>
<td>任课老师</td>
<td>
<input type="text" name="classtea"/>
</td>
</tr>
<tr>
<td>课堂地点</td>
<td>
<input type="text" name="classspace"/>
</td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="添加"/></td>
</tr>
</table>
</form>
</center>
</body>
</html>
class.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="ceshi.HaveClass"%>
<%@ page import="ceshi.ClassDao"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%
String classname = request.getParameter("classname");
String classtea = request.getParameter("classtea");
String classspace = request.getParameter("classspace");
if(classtea.equals("王建民")||classtea.equals("刘丹")||classtea.equals("刘立嘉")||classtea.equals("王辉")||classtea.equals("杨子光"))
{
}
else
{
request.setAttribute("result","请输入在职老师");
%>
<jsp:forward page="addClass.jsp"></jsp:forward>
<%
}
if(classspace.startsWith("基教")||classspace.startsWith("一教")||classspace.startsWith("二教")||classspace.startsWith("三教"))
{
}
else
{
request.setAttribute("result","请输入正确地点");
%>
<jsp:forward page="addClass.jsp"></jsp:forward>
<%
}
HaveClass course=new HaveClass();
course.setClassname(classname);
course.setTeachername(classtea);
course.setPlace(classspace);
ClassDao classDao=new ClassDao();
classDao.add(course);
request.setAttribute("result","课程添加成功");
%>
<jsp:forward page="addClass.jsp"></jsp:forward>
<body>
</body>
</html>
代码如上。
表格怎么建立自己去csdn 具体图如下
注意test 与grade 代表的什么 代码中自己可以改 如果你建立的表不是这个名字的话。
运行代码会出现
自己输入 软件工程 王建民 基教 会出现
然后你的表里面会出现
前面两个是测试的,第三个是我写这个随笔输入的。
下面是参考的网站
现在讲一下会出现问题xampp 如果你安装过mysql会出现端口冲突建议把已经安装mysql删掉。
如何你安装过虚拟机也会出现端口占用具体xampp安装教程https://blog.csdn.net/sliencect/article/details/118001059?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163488972316780274168041%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=163488972316780274168041&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_click~default-2-118001059.first_rank_v2_pc_rank_v29&utm_term=xampp%E5%AE%89%E8%A3%85%E6%95%99%E7%A8%8B%E4%B8%8E%E9%85%8D%E7%BD%AE&spm=1018.2226.3001.4187
具体软件还是推荐自己去百度一下直接就有,官网下载有点麻烦,反正我是下载不了不知道为什么。
Navicat 自己去官网下载 怎么激活可以去csdn下载激活工具。
代码参考的学长网站
https://blog.csdn.net/weixin_33841722/article/details/94314309?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163488500316780271548971%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=163488500316780271548971&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-94314309.first_rank_v2_pc_rank_v29&utm_term=%E8%AF%BE%E7%A8%8B%E6%B7%BB%E5%8A%A0&spm=1018.2226.3001.4187
他的代码缺少class类 我的代码并没有缺少,可以放心使用。
JavaWeb+MySQL实现课程管理系统
JavaWeb+MySQL实现课程管理系统
Hello,大家好,本周博主为大家带来一个简单的基于JavaWeb的课程管理系统,内容详细,好了,下面步入正题
开发环境
- jdk1.8
- mysql5.7
技术栈:
后端:JavaWeb+MySQL
前端:bootstrap+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())
//普通的文本框:
String fieldName = item.getFieldName(); //获取字段名 username\\route_id
String fieldValue = item.getString("UTF-8");//获取字段值 张三丰
req.setAttribute(fieldName, fieldValue);
else
//文件上传框
//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 tdtext-align:center;
</style>
</head>
<body>
<div class="container cus-container">
<h3 class="text-center" style="font-weight:bold">课程列表</h3>
<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 classLinux系统安装MySQL8.0版本详细教程亲测有效