//上传字段 String fileName=item.getName(); fileName=fileName.substring(fileName.lastIndexOf(

本文详细介绍了图书管理系统后台的各类操作,包括图书类别管理、图书信息添加、浏览及展示,以及订单查询等关键功能。同时,文章还阐述了图书上传流程,涉及文件上传、图片保存与路径设置,确保系统能高效地处理多媒体内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.itheima.tfy.web.servlet;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import com.itheima.tfy.domain.Book;
import com.itheima.tfy.domain.Category;
import com.itheima.tfy.domain.Page;
import com.itheima.tfy.serice.impl.BusinessServiceImpl;
import com.itheima.tfy.util.BookStoreLogger;
import com.itheima.tfy.util.IdGenertor;


public class ManagerServlet extends HttpServlet {
  private BusinessServiceImpl bs=new BusinessServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String operation=request.getParameter("operation");
if("addCategory".equals(operation)){

addCategory(request,response);
}
if("ShowAllCategory".equals(operation)){
ShowAllCategory(request,response);
}
if("addBookUI".equals(operation)){
addBookUI(request,response);
}
if("addBook".equals(operation)){
addBook(request,response);
}
if("ShowAllBooks".equals(operation)){
ShowAllBooks(request,response);
}
if("ShowAllOrders".equals(operation)){
ShowAllOrders(request,response);
}


}
//查询所有的订单
private void ShowAllOrders(HttpServletRequest request,
HttpServletResponse response) {


}
//查询显示所有的图书
private void ShowAllBooks(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String pagenum=request.getParameter("pagenum");
String categoryId=request.getParameter("categoryId");
Page page= bs.findManagerBookPage(pagenum,categoryId);
request.setAttribute("page", page);
BookStoreLogger.info("查询显示所有的图书,图书数量:"+page.getRecords());
request.getRequestDispatcher("/manager/listBooks.jsp").forward(request, response);

}
//转向添加图书页面,主要目的是显示图书分类,便于选择
private void addBookUI(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<Category> cs=bs.findAllCategory();
BookStoreLogger.info("转向添加图书页面,显示图书分类,查询结果为:"+cs.size());
System.out.println("addBookUI");
request.setAttribute("cs", cs);
request.getRequestDispatcher("/manager/addBook.jsp").forward(request, response);
}
//添加图书,保存图书信息,上传图片
private void addBook(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//保存上传路径
String storePath=getServletContext().getRealPath("/images");
try{

Book book=new Book();
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
boolean isMultipart=ServletFileUpload.isMultipartContent(request);

if(isMultipart){
List<FileItem> items=upload.parseRequest(request);
for(FileItem item:items){
if(item.isFormField()){
//普通字段
// String fileName=item.getName();
String fileName=item.getFieldName();
String fileValue=item.getString("UTF-8");
BeanUtils.setProperty(book, fileName, fileValue);
}else{
//上传字段
String fileName=item.getName();
fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
fileName=IdGenertor.getId()+"_"+fileName;

String storeFile=storePath+"\\"+fileName;

InputStream in=item.getInputStream();
OutputStream out=new FileOutputStream(storeFile);
int len=-1;
byte [] b=new byte[1024];
while((len=in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
out.close();
item.delete();
book.setImage("/images/"+fileName);
}
}
}

BookStoreLogger.info("将要保存的书的信息内容"+book);
bs.addBook(book);
request.setAttribute("message", "添加成功");
}catch(Exception e){
BookStoreLogger.error(e.getMessage());
request.setAttribute("message", "服务器忙");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);


}
//查询显示所有的分类信息
private void ShowAllCategory(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<Category> cs=bs.findAllCategory();

BookStoreLogger.info("查询显示所有的分类信息,分类结果:"+cs.size());
request.setAttribute("cs",cs);
request.getRequestDispatcher("/manager/listCategory.jsp").forward(request, response);

}
//添加分类
private void addCategory(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException   {
try{
Category c=new Category();
BeanUtils.populate(c, request.getParameterMap());
BookStoreLogger.info("将要保存的分类内容"+c);
bs.addCategory(c);
request.setAttribute("message", "添加成功");
}catch(Exception e){
BookStoreLogger.error(e.getMessage());
request.setAttribute("message", "服务器忙");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


doGet(request, response);
}


}
private static final String SAVE_PATH = "C:/car/headImg"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); String json = "{}"; try { // 创建保存目录 File saveDir = new File(SAVE_PATH); if (!saveDir.exists()) saveDir.mkdirs(); // 获取表单数据 String username = request.getParameter("username"); String password = request.getParameter("password"); String sex = request.getParameter("sex"); String realname = request.getParameter("realname"); String email = request.getParameter("email"); String telephone = request.getParameter("telephone"); String idNum = request.getParameter("idNum"); int phone = Integer.parseInt(telephone); int id = Integer.parseInt(idNum); // 处理头像上传 Part filePart = request.getPart("headimg"); String fileName = getFileName(filePart); String filePath = ""; if (fileName != null && !fileName.isEmpty()) { // 生成唯一文件名 String ext = fileName.substring(fileName.lastIndexOf(".")); String uniqueName = UUID.randomUUID() + ext; filePath = SAVE_PATH + File.separator + uniqueName; // 保存文件 try ( InputStream fileContent = (InputStream) filePart.getInputStream()) { Files.copy(fileContent, Paths.get(filePath)); } } // 创建用户对象 User user = new User(username,password,sex,realname,email,phone,id,filePath); // 保存到数据库(需实现UserService) UserService userService = new UserServiceImpl(); int result = userService.addUser(user); if (result > 0) { // 手动拼接JSON字符串 json = "{\"code\":200, \"msg\":\"用户添加成功\"}"; } else { json = "{\"code\":500, \"msg\":\"数据库操作失败\"}"; } } catch (Exception e) { String escapedMsg = e.getMessage() .replace("\\", "\\\\") // 转义反斜杠 .replace("\"", "\\\""); // 转义双引号 json = "{\"code\":500, \"msg\":\"服务器错误: " + escapedMsg + "\"}"; } out.print(json.toString()); out.flush(); } // 获取上传文件名 private String getFileName(Part part) { String contentDisp = part.getHeader("content-disposition"); String[] tokens = contentDisp.split(";"); for (String token : tokens) { if (token.trim().startsWith("filename")) { return token.substring(token.indexOf("=") + 2, token.length() - 1); } } return ""; }更具上面的内容用合适的方法进行修改
最新发布
06-16
String path = application.getRealPath ("") .replace ('\\', '/'); if (!path.endsWith("/")) { path +="/”; System.out.println("--------path-------" + path); DiskFileUpload fu = new DiskFileUpload(); // 设置允许用户上传文件大小,单位:字节 fu.setSizeMax(10000000); // maximum size that will be stored in memory? // 设置最多只允许在内存中存储的数据,单位:字节 fu.setSizeThreshold(4096); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录 fu.setRepositoryPath(path + "/temp"); //开始读取上传信息 List fileItems = fu.parseRequest(request); System.out.println("path:" + path); String ImportPath = ””; String FileName = //依次处理每个上传的文件 Iterator iter = fileItems.iterator () ; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); ImportPath = new ExeSQL().getOneValue("select SYSVARVALUE from ldsysvar where sysvar = 'CustomerRecordTemPData'"); System.out.println("上传路径:"+ ImportPath); //忽略其他不是文件域的所有表单信息 if (!item.isFormField()) String name =item.getName(); System.out.println("name:" + name); long size = item.getSize(); if ((name == null ll name.equals("")) && size -= 0) continue; aSerNo = PubFunl.CreateMaxNo ("DoubleRecordSerNo", 6) ; FileName = name.replace('\\', '/'); F'ileName = FileName.substring(FileName.lastIndexOf ("/") + 1) ; FileName = aSerNo + FileName; System.out.println("FileName: " + FileName); System.out.println("I--" + ImportPath + FileName); 给上述代码添加注释,若调用方法,请解释一下,谢谢
03-08
给下面的代码写注释try { stmt = con.createStatement(); String sql = "select * from building where number='"+number+"'; "; rs = stmt.executeQuery(sql); } catch (SQLException e2) { e2.printStackTrace(); } String imgPath=""; try { if(rs.next()) { String num = rs.getString("number"); String location = rs.getString("location"); String name = rs.getString("name"); String space = rs.getString("space"); String color = rs.getString("color"); String img= rs.getString("img"); imgPath = rs.getString("img"); String username= rs.getString("username"); field1.setText(num); field1.setEnabled(false); field2.setText(location); //field2.setEnabled(false); field3.setText(username); //field3.setEnabled(false); field4.setText(space); //field4.setEnabled(false); field5.setText(color); //field5.setEnabled(false); } else { JOptionPane.showMessageDialog(null,"没有此编号的民居的详细信息!"); new Guanliyuan(true); } } catch (HeadlessException e2) { e2.printStackTrace(); } catch (SQLException e2) { e2.printStackTrace(); } if(imgPath!=""&&imgPath!=null) { File file3 = new File(imgPath); try { buffimg = ImageIO.read(file3); } catch (IOException a) { a.printStackTrace(); } filename = file3.getName(); String cat = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); if (cat.equalsIgnoreCase("JPG") || cat.equalsIgnoreCase("GIF") || cat.equalsIgnoreCase("PNG") || cat.equalsIgnoreCase("JPEG")) { ic = new ImageIcon(imgPath); ia = ic.getImage(); int height = ic.getIconHeight(); int width = ic.getIconWidth(); jLabelImg.setSize(width, height); jLabelImg.setIcon(ic); repaint(); } else { JOptionPane.showMessageDialog(null, " 该软件只支持 JPG 、GIF 、 PNG格式的图像文件 ", " 提示 ", JOptionPane.INFORMATION_MESSAGE); } } }
07-17
try { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); Path tempFile = Files.createTempFile(System.currentTimeMillis() + "", suffix); file.transferTo(tempFile); // 1、获取文件输入流 InputStream inputStream = file.getInputStream(); Workbook book; String fileName = file.getOriginalFilename(); if (fileName.endsWith("xls")) { book = new HSSFWorkbook(inputStream); }else{ book = new XSSFWorkbook(inputStream); } LambdaQueryWrapper<ZzxQuickTestingTree> lambdaQueryWrapper = new LambdaQueryWrapper(); lambdaQueryWrapper.apply(true, " del_flag = '0' ") .apply(true, "parent_id = -1 " ) .orderByAsc(ZzxQuickTestingTree::getId); List<ZzxQuickTestingTree> treelist = zzxQuickTestingTreeService.list(lambdaQueryWrapper); Map<String,String> treeMap = new HashMap<>(); for (ZzxQuickTestingTree trees:treelist) { treeMap.put(trees.getName(),trees.getType()); } //获取一个工作表(sheet页),下标从0开始 Sheet sheet = book.getSheetAt(0); for (int i = 2; i <= sheet.getLastRowNum() ; i++) { // 获取行数 Row row = sheet.getRow(i); // 获取单元格 取值 if(row.getCell(2) == null || "".equals(row.getCell(2))){ continue; } String value0 = row.getCell(1).getStringCellValue();//样本类型 String value1 = row.getCell(2).getStringCellValue();//标准名称 if(value1 == null || "".equals(value1)){ continue; } String value2 = row.getCell(3).getStringCellValue();//标准编号 String value3 = row.getCell(4).getStringCellValue();//制定机关(多机关以"/"分割) String value4 = row.getCell(5).getStringCellValue();//标准类别 //String value5 = row.getCell(6).getStringCellValue();//实施时间 String value6 = row.getCell(7).getStringCellValue();//时效性 //String value7 = row.getCell(8).getStringCellValue();//公布日期 String value8 = row.getCell(9).getStringCellValue();//手动录入内容或者文档链接地址 String value9 = row.getCell(10).getStringCellValue();//说明 Date value5 =null; if(row.getCell(6) != null && HSSFDateUtil.isCellDateFormatted(row.getCell(6))){ value5 = row.getCell(6).getDateCellValue(); }else{ value5 = DateUtils.parseDate(row.getCell(6).getStringCellValue(),"YYYY-MM-DD"); } Date value7 =null; if(row.getCell(8) != null && HSSFDateUtil.isCellDateFormatted(row.getCell(8))){ value7 = row.getCell(8).getDateCellValue(); }else{ value7 = DateUtils.parseDate(row.getCell(8).getStringCellValue(),"YYYY-MM-DD"); } log.info("获取excel第"+i +"行:" + value1+ ";" + value2+ ";"+ value3+";" + value4+";" + value5+";" + value6+";" + value7+";" + value8+";"); // 判断该名称的标准是否已存在 String value = value1 + " " + value2; Map columnMap = new HashMap(); columnMap.put("lable", value); columnMap.put("del_flag", 0); List<ZzxQuickTestBasis> list = zzxQuickTestBasisService.listByMap(columnMap); /** * 根据标准类型生成唯一标准type值 */ String sampleType = treeMap.get(value0); String type = ""; switch (sampleType){ case "sample_type_1": type = "test_basis_1"; break; case "sample_type_2": type = "test_basis_2"; break; case "sample_type_3": type = "test_basis_3"; break; case "sample_type_4": type = "test_basis_4"; break; } // 根据type查询对应标准最大序号值 int maxTypeValue = zzxQuickTestBasisService.getMaxTypeValue(type); // 在最大序号基础上增加1作为新数据的type序号 } 请根据以上Java代码片段复原出所解析的xlsx表格结构
06-05
/** * 上传视频,前端分片上传 * * @return */ @PostMapping("/upload") public R upload(ChunkInfo chunk) { final Integer MAX_SIZE = 100 * 1024 * 1024; if (Objects.isNull(chunk) || StringUtils.isBlank(chunk.getFilename()) || null == chunk.getChunkNumber() || StringUtils.isBlank(chunk.getIdentifier())) { return R.errorParam(); } Assert.isFalse(chunk.getTotalSize() >= MAX_SIZE, "文件最大不能超过100MB"); //获取clientId Long clientId = AccountUtil.getClientId(); MultipartFile file = chunk.getMultipartFile(); try { byte[] bytes = file.getBytes(); Path path = Paths.get(FileInfoUtils.generateCommonPath(uploadFolder, chunk, clientId)); //文件写入指定路径 Files.write(path, bytes); } catch (IOException e) { e.printStackTrace(); return R.failed(); } return R.ok(); } @PostMapping("/mergeFile") public R mergeFile(@RequestBody ChunkInfoVO chunkInfo) { if (Objects.isNull(chunkInfo) || StringUtils.isBlank(chunkInfo.getFilename()) || StringUtils.isBlank(chunkInfo.getIdentifier())) { return R.errorParam(); } Long clientId = AccountUtil.getClientId(); Long updateBy = AccountUtil.getAccountId(); /** * 根据文件类型 , 配置路径文件夹 */ String filename = chunkInfo.getFilename(); //取名称的前30个字 String substring = chunkInfo.getFilename().substring(0, filename.lastIndexOf(".")); if (substring.length() > 30) { filename = substring.substring(0, 30) + ".mp4"; } /** * 进行文件的合并操作 */ String file = uploadFolder + File.separator + clientId + File.separator + chunkInfo.getIdentifier() + File.separator + filename; String folder = uploadFolder + File.separator + clientId + File.separator + chunkInfo.getIdentifier(); String fileSuccess = FileInfoUtils.merge(file, folder, filename); log.info("文件名:" + filename); log.info("文件:" + file); log.info("文件夹:" + folder); log.info("合并状态:" + fileSuccess); chunkInfo.setLocation(file); if (HttpStatus.HTTP_INTERNAL_ERROR == Integer.parseInt(fileSuccess)) { return R.failed().setMsg("上传失败"); } boolean flag = HttpStatus.HTTP_OK == Integer.parseInt(fileSuccess); /** * 文件合并成功后,将文件直接上传到云点播 */ if (flag) { try { String uploadPart = tosHelperUtil.uploadPart(filename, file); return R.ok(); } catch (Exception e) { throw new RuntimeException(e); } } return R.failed(); } 请你检查这两个方法是否正确 如果不正确请你修改 并在合并方法补充 捕获视频第一帧 当作封面 public File generateVideoCover(File file) throws Exception { FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(file); grabber.start(); // 获取第一帧 Frame frame = grabber.grabImage(); Java2DFrameConverter converter = new Java2DFrameConverter(); BufferedImage image = converter.getBufferedImage(frame, 1.0); // 保存临时文件 File tempFile = File.createTempFile("cover", ".jpg"); ImageIO.write(image, "jpg", tempFile); grabber.stop(); return tempFile; }可使用此方法 但需要你补充调用地方的逻辑
03-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值