一、导入jar包,配置properties文件(src路径下)
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
druid-1.2.8.jar
mysql-connector-java-8.0.25.jar
servlet-api.jar
# ????key-value???
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名
username=数据库用户名
password=数据库用户密码
# init size
initialSize=5
# max size
maxActive=10
maxWait=3000
二、用html写一个简易的网页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>添加老师信息</h3>
<form action="teacherServlet" method="post" enctype="multipart/form-data">
<input type="hidden" name="action" value="add">
姓名:<input type="text" name="name"><br/>
年龄:<input type="text" name="age"><br/>
出生日期:<input type="date" name="birthday"><br/>
头像:<input type="file" name="tx" ><br/>
<input type="submit" value="添加">
</form>
</body>
</html>
三、根据表单数据建立好对应的数据库JDBC连接
详情见链接:https://blog.csdn.net/qq_62182919/article/details/142220224?sharetype=blogdetail&sharerId=142220224&sharerefer=PC&sharesource=qq_62182919&sharefrom=from_link
四、创建TeacherServlet ,完成请求响应
因为在上方表单要将图片以二进制字节流上传,所以用到了enctype=“multipart/form-data”
相对应的在Servlet中
@MultipartConfig // 一定要加注解
// 1.设置编码方式
@WebServlet("/teacherServlet")
@MultipartConfig // 一定要加注解
public class TeacherServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
System.out.println("添加学生信息!");
// 处理请求信息
String name = req.getParameter("name");
Integer age = Integer.parseInt(req.getParameter("age"));
String date = req.getParameter("birthday");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date birthday = null;
try {
birthday = sdf.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
// 获取头像的文件信息并进行处理
Part part = req.getPart("tx");
String filename = part.getSubmittedFileName();
filename = UUID.randomUUID().toString().replace("-","")+"-"+filename;
// 将图片上传到指定路径
String path = "E:\\学习日记\\07javaEE课堂笔记\\img\\"+filename;
// 上传
part.write(path);
// 把文件名作为数据保存到数据库之中
Teacher teacher = new Teacher(name,age,birthday,filename);
int num = new TeacherDao().addTeacher(teacher);
if(num!=0){
System.out.println("添加成功!");
resp.sendRedirect("teacherServlet?action=selectAll");
}else{
resp.getWriter().write("<h1>添加失败!</h1>");
}
}
}
五、根据数据库中保存的文件名预览保存在对应文件夹的图片servlet实现请求
// 预览图片
@WebServlet("/down")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.设置编码方式
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// 2.处理请求信息
String filename = req.getParameter("filename");
// 3.以字节流的形式把图片响应给前端
FileInputStream fin = new FileInputStream(new File("E:\\学习日记\\07javaEE课堂笔记\\img",filename));
// 设置响应的图片是1预览还是下载到本地
// 预览:resp.setHeader("Content-Disposition", "filename="+filename);
// 下载:resp.setHeader("Content-Disposition", "attachment;filename="+filename);
resp.setHeader("Content-Disposition", "filename="+filename);
ServletOutputStream out = resp.getOutputStream();
// 读写操作
byte b[] = new byte[1024];
int len = 0;
while((len=fin.read(b))!=-1){
out.write(b,0,len);
}
out.close();
fin.close();
}
}
六、简易的页面用来展示数据库中的数据
在另一个servlet中可以通过下面的响应请求的方式,将需要的网页直接编写出来(注意设置代码编写格式)
预览图片用到了请求 down
out.write(“”);
PrintWriter out = resp.getWriter();
out.write("<table border=1>");
// 表头
out.write("<tr><th>编号</th><th>姓名</th><th>年龄</th><th>出生日期</th><th>操作</th></tr>");
// 表格内容
// 连接数据库,查询所有的老师信息
List<Teacher> teachers = new TeacherDao().findTeachers();
for(Teacher teacher:teachers){
out.write("<tr>");
out.write("<td>"+teacher.getId()+"</td>");
out.write("<td>"+teacher.getName()+"</td>");
out.write("<td>"+teacher.getAge()+"</td>");
out.write("<td>"+teacher.getBirthday()+"</td>");
out.write("<td><img src='down?filename="+teacher.getTx()+"' width='200'></td>");
out.write("<td><a href='teacherServlet?action=del&id="+teacher.getId()+"'>删除</a>"
// + "<a href='teacherServlet?action=update&id="+teacher.getId()+"&name="+teacher.getName()+"&age="+teacher.getAge()+"&birthday="+teacher.getBirthday()+"'>修改</a>"
+ "</td>");
out.write("</tr>");
}
out.write("</table>");
out.write("<a href='add.html'>添加老师信息</a>");
项目路径如下: