JavaWeb servlet jsp 上传图片,图片存入数据库,图片从数据库中取出,页面显示图片
Posted 霜序0.2℃
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb servlet jsp 上传图片,图片存入数据库,图片从数据库中取出,页面显示图片相关的知识,希望对你有一定的参考价值。
文章目录
前言
通过javaBean创建表结构,通过jsp界面录入数据,具备上传图片的功能,并提供一个列表界面,用分页及表格形式显示这些数据,在列表界面点击某条记录,跳到详细信息界面,能把上传的照片显示出来
效果:
首先,代码仅供参考,本人水平有限,没有用jsp写过太多代码,很多地方我自己都觉得很不好,好在功能算是勉强完成了,如果有想交流的可以在评论留言,欢迎交流
简单说,这次作业就是一个巨型缝合怪,东凑凑西凑凑,页面用了layui的表格,强行从后台传json到页面,以及layui
的bug,分页操作,前端的数据无法传到后端,导致徒有其表无法分页…
(除了分页其他都做了,分页其实也是可以的,只要它能将limit和page两个参数放到url上就行,我在sql那里有注释的一个版本就是)
因为作业是放在一块的,很难弄…
里面存留了一些方法,可能是调试或者没有用的,但是我没删掉
如果有些不太懂的,可以看最底下的参考,我很多代码都是参考里面的
DBUtil
数据库工具类,里面只有两个有用的方法Connection
和closeConn
package top.sehnsucht.Util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @Description:
* @Author: Cai
* @CreateTime: 2021/10/29
*/
public class DBUtil {
// 定义数据库连接参数
public static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/xxxx";
public static final String USERNAME = "root";
public static final String PASSWORD = "xxxxxx";
// 注册数据库驱动
static {
try {
Class.forName(DRIVER_CLASS_NAME);
} catch (ClassNotFoundException e) {
System.out.println("注册失败!");
e.printStackTrace();
}
}
// 获取连接
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
// 关闭连接
public static void closeConn(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("关闭连接失败!");
e.printStackTrace();
}
}
}
//测试
public static void main(String[] args) throws SQLException {
System.out.println(DBUtil.getConn());
}
}
ImageUtil
特殊变量it,在ImageDBUtil.readImage2DB中数据库表进行id自增
里面2个方法,最主要的是readBin2Image
,用来读取表中图片获取输出流,然后存入本地
package top.sehnsucht.Util;
import java.io.*;
import java.sql.Blob;
/**
* @Description:
* @Author: Cai
* @CreateTime: 2021/10/29
*/
public class ImageUtil {
public static Integer it = 1;
/**
* 读取本地图片获取输入流
* @param path
* @return
* @throws IOException
*/
public static FileInputStream readImage(String path) throws IOException {
return new FileInputStream(new File(path));
}
/**
* 读取表中图片直接存到本地
* @param in
* @param targetPath
*/
public static void readBin2Image(Blob in, String targetPath) throws Exception{
File file = new File(targetPath);
OutputStream outputStream = new FileOutputStream(file);
outputStream.write(in.getBytes(1,(int)in.length()));
}
}
UrlUtil
url工具类,不过没有用上,因为参数根本没传过来…
package top.sehnsucht.Util;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:
* @Author: Cai
* @CreateTime: 2021/10/31
*/
public class UrlUtil {
/**
* 获取请求地址中的某个参数
*
* @param url
* @param name
* @return
*/
public static String getParam(String url, String name) {
return urlSplit(url).get(name);
}
/**
* 去掉url中的路径,留下请求参数部分
*
* @param url url地址
* @return url请求参数部分
*/
private static String truncateUrlPage(String url) {
String strAllParam = null;
String[] arrSplit = null;
url = url.trim().toLowerCase();
arrSplit = url.split("[?]");
if (url.length() > 1) {
if (arrSplit.length > 1) {
for (int i = 1; i < arrSplit.length; i++) {
strAllParam = arrSplit[i];
}
}
}
return strAllParam;
}
/**
* 将参数存入map集合
*
* @param url url地址
* @return url请求参数部分存入map集合
*/
public static Map<String, String> urlSplit(String url) {
Map<String, String> mapRequest = new HashMap<String, String>();
String[] arrSplit = null;
String strUrlParam = truncateUrlPage(url);
if (strUrlParam == null) {
return mapRequest;
}
arrSplit = strUrlParam.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]");
//解析出键值
if (arrSplitEqual.length > 1) {
//正确解析
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
} else {
if (arrSplitEqual[0] != "") {
//只有参数没有值,不加入
mapRequest.put(arrSplitEqual[0], "");
}
}
}
return mapRequest;
}
}
ImageDBUtil
两个方法readImage2DB
和readDB2Image
,2就是to,即数据库和图片的相互转换
package top.sehnsucht.Util;
import top.sehnsucht.vo.Page;
import java.io.FileInputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:
* @Author: Cai
* @CreateTime: 2021/10/29
*/
public class ImageDBUtil {
/**
* 将图片插入数据库
* @param path filename
*/
public static void readImage2DB(String path, String filename) {
Connection conn = null;
PreparedStatement ps = null;
FileInputStream in = null;
try {
in = ImageUtil.readImage(path + "\\\\" + filename);
conn = DBUtil.getConn();
String sql = "insert into photo (id,name,photo)values(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setInt(1, ImageUtil.it++);//数据库表我弄成自增的了
ps.setString(2, filename);
ps.setBinaryStream(3, in, in.available());
int count = ps.executeUpdate();
if (count > 0) {
System.out.println("插入成功!");
} else {
System.out.println("插入失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(conn);
if (null != ps) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**
* 读取数据库中图片
* @param targetPath
*/
public static void readDB2Image(String targetPath) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConn();
String sql = "select * from photo";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Blob in = rs.getBlob("photo");
System.out.println("看我在哪,文件名为: " + targetPath);
ImageUtil.readBin2Image(in, targetPath);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(conn);
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**
* 将数据库里面的id和name取出,并放到ArrayList里面,以便用fastjson转化
* @param page
* @return
*/
public static ArrayList<Map<String,String>> selectImg(Page page) {
Connection conn = null;
PreparedStatement ps = null;
FileInputStream in = null;
ResultSet rs = null;
ArrayList<Map<String,String>> arrs = new ArrayList<>();
try {
conn = DBUtil.getConn();
String sql = "select id,name from photo order by id" ;
// String sql = "select id,name from photo order by id limit " + page.getStart() + "," + page.getLimit() ;
ps = conn.prepareStatement(sql);
rs = ps.executeQuery(sql);
while (rs.next()) {
Map<String,String> map = new HashMap();
Integer id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("查询: " + id + " " + name);
map.put("id",id.toString());
map.put("name", name);
arrs.add(map);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(conn);
if (null != ps) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return arrs;
}
/**
* 查询数据库有多少条信息,最后返回前端
* @return
*/
public static int selectCount() {
Connection conn = null;
PreparedStatement ps = null;
FileInputStream in = null;
ResultSet rs = null;
int ans = 0;
try {
conn = DBUtil.getConn();
String sql = "select id,name from photo ";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery(sql);
while (rs.next()) {
ans = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(conn);
if (null != ps) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return ans;
}
}
ForwardServlet /data
查看是不是有jsp后缀的bug,可以忽略
package top.sehnsucht.pic;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Description:
* @Author: Cai
* @CreateTime: 2021/10/31
*/
public class ForwardServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getRequestURL());
RequestDispatcher rs = req.getRequestDispatcher("pic/data.jsp");
rs.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
UploadServlet /upload
文件上传功能
package top.sehnsucht.pic;
import org.apache.commons.fileupload.以上是关于JavaWeb servlet jsp 上传图片,图片存入数据库,图片从数据库中取出,页面显示图片的主要内容,如果未能解决你的问题,请参考以下文章
webjsp中用fileupload上传图片,选择图片后没有反应