Jsp+servlet+SqlServer实现图片上传、图片详情查看、表格分页
emmm。。。回头看这个写的真的一言难尽(来自2022年的画外音)
改进版: 搭建WebService开发环境,改进“图片上传”实验
要求:
通过JavaBean创建表结构(要有存储图片字段)。通过Jsp界面录入数据,具备上传图片功能(单张图片即可)。提供一个列表界面、用分页及表格形式显示这些数据,在列表界面点击某条记录,跳转到详细信息界面,要能把上传的图片显示出来。
一、如果图片无法显示(图裂),在eclipse中refresh项目一下即可。
二、图片均以地址的形式存储在数据库中。
三、表格页面切换的思路:
①上一页按钮,下一页按钮,跳转按钮分别为三个个表单的submit按钮
②点击按钮时,将上一页的页数/下一页的页数/文本框内的页数传入turn_page.jsp进行处理
③turn_page.jsp获取list.jsp传入的页数值page,再将该值回传给list.jsp
④list.jsp初始时,页数值page是空的,但进行了一次跳转之后,该页数值page就非空,获取该值,根据page×n-n ~page×n+1 (n为每页最多应显示的数据数)范围查找数据,最后将查询到的数据集遍历显示在表格中即可!
四、查看详情的思路:查看按钮为表单中的submit按钮,当点击按钮时,即将当前图片的id传入turn_check.jsp中,然后turn_check.jsp将id传入Detail.jsp中,Detail.jsp根据传入的id进行查询,将查询到结果显示即可。
(;´д`)ゞ语言表达能力有限。。
结果展示
2021/11/4 21:27修改了总页数计算错误的bug。。
2021/11/5 11:45修改了文件非图片格式也能上传的bug。。
目录结构
该项目需要使用以下jar包:
jar包下载
Add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片上传</title>
<style>
.info-div{
margin-top:10px;
}
</style>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<div class="info-div">
<label>主题:</label>
<input type="text" name="title">
</div>
<div class="info-div">
<label>图片:</label>
<input type="file" name="uploadImg">
</div>
<div class="info-div">
<input type="submit" value="保存">
</div>
</form>
</body>
</html>
List.jsp
<%@page import="com.bnuz.dao.ImgDao"%>
<%@page import="java.util.List"%>
<%@page import="com.bnuz.javabean.Image"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片列表</title>
</head>
<body>
<form action="turn_add.jsp" method="post" style="height:40px;">
<input type="submit" value="上传" name="s">
</form>
<%
ImgDao imgDao = new ImgDao();
List<Image> images = imgDao.queryAll();
int pages = images.size()/3+((images.size()%3!=0)?1:0); //总页数
int start=0;
//若要每页显示n条数据,则查询范围为:当前页数×n-n ~ 当前页数×n+1
List<Image> pageImages = imgDao.queryScope(0, 4);
if(request.getParameter("page")!=null){
String s = request.getParameter("page");
start = Integer.parseInt(s);
pageImages = imgDao.queryScope(start*3-3, start*3+1);
}
%>
<div style="display:flex; height:30px; ">
<form action="turn_page.jsp?page=<%=start-1 %>" method="post">
<input type="submit" value="上一页">
</form>
<form action="turn_page.jsp" method="post">
<input type="text" name="page" value="<%=request.getParameter("page") %>" style="width:50px;">
<input type="submit" value="跳转">
</form><br>
<form action="turn_page.jsp?page=<%=start+1 %>" method="post">
<input type="submit" value="下一页">
</form>
<label>一共有<%=images.size() %>条数据,共<%=pages %>页</label>
</div>
<table border="1" style="text-align:center;">
<tr>
<th style="width:50px;">id</th>
<th style="width:150px;">主题</th>
<th style="width:100px;">图片</th>
<th style="width:80px;">操作</th>
</tr>
<%
for(Image u:pageImages){
%>
<tr>
<td><%= u.getId() %></td>
<td><%= u.getTitle() %></td>
<td><img style="width:80px;height:50px" src="<%=u.getImgurl()%>"></img></td>
<td>
<form action="turn_check.jsp?num=<%=u.getId() %>" method="post">
<input type="submit" value="查看" name="s">
</form>
</td>
</tr>
<% }%>
</table>
</body>
</html>
Detail.jsp
<%@page import="com.bnuz.dao.ImgDao"%>
<%@page import="com.bnuz.javabean.Image"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>详情页</title>
</head>
<body>
<%
String num = request.getParameter("id");
int n = Integer.parseInt(num);
ImgDao imgDao = new ImgDao();
Image image = imgDao.query(n);
//out.println(image.getImgurl());
%>
<div>
<label>主题:</label>
<label><%=image.getTitle() %></label>
</div>
<div>
<label>发布人:YE</label>
</div>
<div>
<label>图片:</label><br>
<img src="<%=image.getImgurl()%>" style="height:200px;width:300px;">
</div>
</body>
</html>
turn_add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
response.sendRedirect("Add.jsp");
%>
</body>
</html>
turn_check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String num = request.getParameter("num");
response.sendRedirect("Detail.jsp?id="+num);
%>
</body>
</html>
turn_page.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>turn page</title>
</head>
<body>
<%
String num = request.getParameter("page");
if(Integer.parseInt(num)>0){
response.sendRedirect("List.jsp?page="+num);
}
else{
response.sendRedirect("List.jsp?page="+1);
}
%>
</body>
</html>
Image.java
package com.bnuz.javabean;
public class Image {
private int id;
private String title;
private String imgurl;
public Image() {
}
public Image(int id,String title,String url) {
this.id = id;
this.title = title;
this.imgurl = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
}
ImgDao.java
package com.bnuz.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.bnuz.javabean.Image;
import com.bnuz.util.DBUtil;
public class ImgDao {
private Connection conn;
private PreparedStatement ps;
private Statement statement;
//添加
public void add(Image image){
try {
conn=DBUtil.getConn();
String sql="insert into images(title,url)"+" values (?,?)" ;
ps=conn.prepareStatement(sql);
ps.setString(1,image.getTitle());
ps.setString(2, image.getImgurl());
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
//查询全部
public List<Image> queryAll() {
List<Image> images = new ArrayList<Image>();
try {
conn=DBUtil.getConn();
statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery("select * from images");
while(rs.next()) {
int id = rs.getInt("id");
String title = rs.getString("title");
String url = rs.getString("url");
Image image = new Image(id,title,url);
images.add(image);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return images;
}
//查询单条
public Image query(int id) {
Image image = new Image();
try {
conn = DBUtil.getConn();
statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery("select * from images where id="+id);
while(rs.next()) {
image.setId(id);
image.setTitle(rs.getString("title"));
image.setImgurl(rs.getString("url"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return image;
}
//查询某范围
public List<Image> queryScope(int start,int end) {
List<Image> images = new ArrayList<Image>();
try {
conn=DBUtil.getConn();
statement = conn.createStatement();
java.sql.ResultSet rs = statement.executeQuery("select * from images where id>"+start+" and id<"+end+"");
while(rs.next()) {
int id = rs.getInt("id");
String title = rs.getString("title");
String url = rs.getString("url");
Image image = new Image(id,title,url);
images.add(image);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return images;
}
}
DBUtil.java
(这个类里的代码复制关注列表某个大佬的233)
package com.bnuz.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String url = "jdbc:sqlserver://localhost:1433;databaseName=Img;integratedSecurity=true;";
private static String user = "sa";
private static String password = "4580796";
static {
try {
//加载驱动
Class.forName(driver);
} catch (Exception e) {
// TODO: handle exception
}
}
// 创建连接
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
// 关闭连接
public static void closeConn(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("关闭连接失败!");
e.printStackTrace();
}
}
}
}
uploadServlet.java
package com.bnuz.util;
import com.bnuz.dao.ImgDao;
import com.bnuz.javabean.Image;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class upServlet
*/
@WebServlet("/uploadServlet")
public class uploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//数据库以UTF-8编码解析数据
request.setCharacterEncoding("UTF-8");
String name=null;
Image image = new Image();
ImgDao dao=new ImgDao();
//判断请求是否为multipar请求
if(!ServletFileUpload.isMultipartContent(request))
{
throw new RuntimeException("当前请求不支持文件上传");
}
//为基于磁盘的文件项创建一个FileItem工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置临时文件的边界值,大于该值时,上传文件会先保存在临时文件中,否则,上传文件将直接写入到内存
//单位:字节,设置边界值1M,一字节=1024M;
factory.setSizeThreshold(1024*1024*1);
//设置文件临时储存
String temppath=this.getServletContext().getRealPath("/temp");
File temp=new File(temppath);
factory.setRepository(temp);
//创建一个新的文件上传处理程序
ServletFileUpload upload = new ServletFileUpload(factory);
//设置每一个item的头部字符编码,其可以解决文件名中文乱码问题;
upload.setHeaderEncoding("UTF-8");
//设置单个文件的最大边界值(这里是2M)
upload.setFileSizeMax(1024*1024*2);
//设置一次上传所有文件总和的最大值(对上传多个文件起作用,这里最大为5M)
upload.setSizeMax(1024*1024*5);
//解析请求,获取所有的item
try {
//
//调用ServletFileUpload.parseRequest方法解析request对象,
//得到一个保存了所有上传内容的List对象。
List <FileItem> items = upload.parseRequest(request);
//遍历
for(FileItem item:items){
//若item为普通表单项
if(item.isFormField()){
//获取表单中属性名称
String fieldName = item.getFieldName();
if(fieldName.equals("title")){
//获取表单属性的值
name=item.getString("UTF-8");
}
System.out.println(fieldName+"="+name);
//若 item为文件表单项
}else{
//获取文件大小
long size=item.getSize();
//获取文件类型
String contentType = item.getContentType();
//获取上传文件原始名字
String fileName = item.getName();
System.out.println("文件大小:"+size);
System.out.println("文件的类型:"+contentType);
//如果上传的内容不是图片,则跳出循环,不进行处理
if(!"image/jpeg".equals(contentType)) {
break;
}
//获取文件名,处理获取到的上传文件的文件名的路径部分,只保留文件名部分
if(fileName.contains("\\"))
{
//如果包含则截取字符串
fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
}
//设置文件名,因为同名的文件会覆盖,所以要修饰文件名,设置毫秒+文件名
fileName=System.currentTimeMillis()+fileName;
System.out.println("文件的名称:"+fileName);
//获取输入流,其实有上传文件的内容
InputStream inputStream = item.getInputStream();
String path=getServletContext().getRealPath("img/");
File dirFile=new File(path);
if(!dirFile.exists()){
//创建多级目录mkdirs()
dirFile.mkdir();
}
//创建目录文件,将来用于保存上传文件
File file = new File(path, fileName);
//创建文件输出流
OutputStream os=new FileOutputStream(file);
//把输入流中的数据写入到输出流
int len=0;
byte[] buf=new byte[1024];
while((len=inputStream.read(buf))!=-1){
os.write(buf, 0, len);
}
//图片上传到之后的路径
path="img/"+fileName;
image.setTitle(name);
image.setImgurl(path);
//调用ImgDao中的add()方法
dao.add(image);
os.close();
inputStream.close();
//删除临时文件
item.delete();
}
}
//上传完毕后回到List.jsp页面
response.sendRedirect("List.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Demo4</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>com.bnuz.util.uploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
</web-app>
images表
<(_ _)>菜鸟一枚,这个代码写的一言难尽,,如有问题,,欢迎探讨