SpringMVC02之CRUD和文件上传下载

简介: SpringMVC02之CRUD和文件上传下载

1.CRUD


CRUD是4个单词的首字母,CRUD分别指增加(Create)、读取查询(Retrieve)、更新(Update)和删除(Delete)这4个单词的首字母。


(1)C:Create(增加) 对应 create table table1;


(2)R:Retrieve(查询)对应 select * from table1;


(3)U:Update(更新) 对应 update table1 set col1=value1 where id=value2;


(4)D:Delete(删除)对应 delete from table1 where id=value1;


2. springmvc的文件上传


       2.1 添加文件上传相关依赖

<dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.3</version>
</dependency>

       2.2 配置文件上传解析器(CommonsMultipartResolver)

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
</bean>

       2.3 表单提交方式为method="post" enctype="multipart/form-data"


       2.4 文件项用spring提供的MultipartFile进行接收


       2.5 上传文件


     注:springmvc文件上传关键代码

     File targetFile = ....;

     MultipartFile mf = ....;

     String fileName = mf.getOriginalFilename();

     mf.transferTo(targetFile);


       2.6 下载文件

@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(@RequestParam String fileId){
   //先根据文件id查询对应图片信息
   //下载关键代码
   File file=new File(bookFile.getUrl());
   HttpHeaders headers = new HttpHeaders();//http头信息
   String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
   headers.setContentDispositionFormData("attachment", downloadFileName);
   headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
   //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
   return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}


3.文件上传三要素


(1)表单的提交方式必须是POST请求

(2)表单中必须有一个文件上传项:<input type=“file” name=“upload”/>,文件上传项必须有name属性和值;

(3)表单的enctype属性的值必须是multipart/form-data


4.代码


下面是数据库表:

create table t_book_file
(
  file_id varchar(32) primary key comment '文件ID',
  real_name varchar(50) not null comment '文件名称',
  content_type varchar(50) not null comment '文件类型',
  url varchar(256) not null comment '文件路径'
);

下面就是代码了:


BookFile.java

package com.zking.ssm.model;
public class BookFile {
    private String fileId;
    private String realName;
    private String contentType;
    private String url;
    public BookFile(String fileId, String realName, String contentType, String url) {
        this.fileId = fileId;
        this.realName = realName;
        this.contentType = contentType;
        this.url = url;
    }
    public BookFile() {
        super();
    }
    public String getFileId() {
        return fileId;
    }
    public void setFileId(String fileId) {
        this.fileId = fileId;
    }
    public String getRealName() {
        return realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }
    public String getContentType() {
        return contentType;
    }
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
}

BookFileMapper.java

package com.zking.ssm.mapper;
import com.zking.ssm.model.BookFile;
import org.springframework.stereotype.Repository;
@Repository
public interface BookFileMapper {
    int deleteByPrimaryKey(String fileId);
    int insert(BookFile record);
    int insertSelective(BookFile record);
    BookFile selectByPrimaryKey(String fileId);
    int updateByPrimaryKeySelective(BookFile record);
    int updateByPrimaryKey(BookFile record);
}

BookFileVo

package com.zking.ssm.vo;
import com.zking.ssm.model.BookFile;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
@Data
public class BookFileVo extends BookFile {
    //书本ID
    private Integer bookId;
    //文件对象
    private MultipartFile bFile;
}

IBookFileService

package com.zking.ssm.service;
import com.zking.ssm.model.BookFile;
import com.zking.ssm.vo.BookFileVo;
import org.springframework.stereotype.Repository;
public interface IBookFileService {
    int addBookFile(BookFileVo bookFileVo);
    BookFile selectOne(String fileId);
}

BookFileServiceImpl

package com.zking.ssm.service.impl;
import com.zking.ssm.mapper.BookFileMapper;
import com.zking.ssm.mapper.BookMapper;
import com.zking.ssm.model.Book;
import com.zking.ssm.model.BookFile;
import com.zking.ssm.service.IBookFileService;
import com.zking.ssm.vo.BookFileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;
@Service
public class BookFileServiceImpl implements IBookFileService {
    @Autowired
    private BookFileMapper bookFileMapper;
    @Autowired
    private BookMapper bookMapper;
    @Transactional
    @Override
    public int addBookFile(BookFileVo bookFileVo) {
    //生成上传图片的FileID
    String fileID= UUID.randomUUID().toString().replace("-","");
    //新增书本图片信息t_book_file
    bookFileVo.setFileId(fileID);
    bookFileMapper.insert(bookFileVo);
    //根据书本ID修改书本的Book_image
    Book book=new Book();
    book.setBookId(bookFileVo.getBookId());
    book.setBookImage(fileID);
    bookMapper.updateBookImageById(book);
        return 1;
    }
    @Override
    public BookFile selectOne(String fileId) {
        return bookFileMapper.selectByPrimaryKey(fileId);
    }
}

BookFileController

package com.zking.ssm.controller;
import com.zking.ssm.model.BookFile;
import com.zking.ssm.service.IBookFileService;
import com.zking.ssm.service.IBookService;
import com.zking.ssm.vo.BookFileVo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@Controller
@RequestMapping("/bookFile")
public class BookFileController {
    public static final String DETAIL_PATH="D:/Y1/SSM/ssm/target/ssm/uploads/";
    @Autowired
    private IBookService bookService;
    @Autowired
    private IBookFileService bookFileService;
    //文件上传与下载宗旨:文件从哪里来,放哪里去!!!
    /**
     * 上传:文件从客户端来,上传服务器指定位置
     */
    @RequestMapping("/upload")
    public String upload(BookFileVo bookFileVo, HttpServletRequest req){
        try {
            MultipartFile bFile = bookFileVo.getBFile();
            //图片保存路径(相对路径),例如:/uploads/1.jpg
            String filePath=DETAIL_PATH+bFile.getOriginalFilename();
            //将相对路径转换成绝对路径,例如:D:/uploads/1.jpg
            String absolutePath = this.transfor(req, filePath);
            //思路:
            //1.将客户端的图片保存到服务器上指定的位置
            bFile.transferTo(new File(absolutePath));
            //2.在t_book_file表添加一条图片记录信息
            //3.根据书本ID更新书本信息表中的book_image
            bookFileVo.setRealName(bFile.getOriginalFilename());
            bookFileVo.setContentType(bFile.getContentType());
            bookFileVo.setUrl(filePath);
            bookFileService.addBookFile(bookFileVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/book/qureyBookPager";
    }
    /**
     * 下载:将服务器上指定的文件下载到客户端中
     */
    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(HttpServletRequest req,@RequestParam String fileId){
        try {
            //先根据文件id查询对应图片信息
            BookFile bookFile = bookFileService.selectOne(fileId);
            //将相对路径转换成绝对路径
            String filePath=this.transfor(req,bookFile.getUrl());
            //下载关键代码
            File file=new File(filePath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(bookFile.getRealName().getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        }
return null;
    }
    /**
     * 将相对路径转换成绝对路径
     * @param req
     * @param relativePath
     * @return
     */
    private String transfor(HttpServletRequest req,String relativePath){
        return req.getServletContext().getRealPath(relativePath);
    }
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html>
<head>
    <%@include file="/common/head.jsp"%>
</head>
<>
<h1>Hello SpringMvc!!!</h1><br>
<div style="position: absolute;top: 10px;right: 10px"><a onclick="return confirm('确定退出吗')" href="${ctx}/user/logout">安全退出</a></div>
<shiro:hasRole name="管理员">
    <a href="${ctx}/book/toBookList">跳转到书本列表页</a>
    <a href="${ctx}/page/book/addBook">跳转到书本新增页</a><br/>
</shiro:hasRole>
</body>
</html>

bookList.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
   <%@include file="/common/head.jsp"%>
</head>
<body>
<h1>书本列表</h1>
<form action="${ctx}/book/qureyBookPager" method="post">
   <label>书本名称:</label> <input type="text" name="bookName"/>
   <input type="submit" value="查询">
</form>
<a href="${ctx}/page/book/addBook">书本新增</a>
<table width="100%" border="1" cellspacing="0" cellpadding="0">
   <tr>
      <th>书本编号</th>
      <th>书本名称</th>
      <th>书本图片</th>
      <th>书本价格</th>
      <th>书本类型</th>
      <th>操作</th>
   </tr>
   <c:forEach items="${books}" var="b">
      <tr>
         <td>${b.bookId}</td>
         <td>${b.bookName}</td>
         <td>
            <c:if test="${empty b.bookImage}">
               未上传图片
            </c:if>
            <c:if test="${not empty b.bookImage}">
               <img src="${ctx}/bookFile/download?fileId=${b.bookImage}" width="150px"/>
            </c:if>
         </td>
         <td>${b.bookPrice}</td>
         <td>${b.bookType}</td>
         <td>
            <a href="${ctx}/book/getOne?bookId=${b.bookId}&type=detail">详情</a>
            <a href="${ctx}/book/getOne?bookId=${b.bookId}&type=edit">编辑</a>
            <a onclick="return confirm('确认删除?');" href="${ctx}/book/delBook?bookId=${b.bookId}">删除</a>
            <c:if test="${empty b.bookImage}">
               <a href="${ctx}/page/book/uploadBook?bookId=${b.bookId}">文件上传</a>
            </c:if>
            <c:if test="${not empty b.bookImage}">
               <a href="${ctx}/bookFile/download?fileId=${b.bookImage}">文件下载</a>
            </c:if>
         </td>
      </tr>
   </c:forEach>
</table>
${pageBean}
</body>
</html>

我就没有把所有的代码放上来了,其他的增删改页面和我之前那些差不多,相信大家也都会了,下面是那个界面图,很简洁的一个页面,也就是i给大家做个示例,所以不要太纠结哈,功能能用就行哈!!!

相关文章
|
5月前
|
Java 数据库连接 数据库
SpringMVC之增删改查(CRUD)项目模拟
SpringMVC之增删改查(CRUD)项目模拟
58 0
|
5月前
|
Java 测试技术 Maven
SpringMVC的整合完成CRUD
SpringMVC的整合完成CRUD
34 0
|
7月前
SpringMVC实战crud增删改查1
SpringMVC实战crud增删改查1
18 0
|
4月前
|
前端开发 数据库
SpringMVC之CRUD(增删改查)
SpringMVC之CRUD(增删改查)
27 0
|
4月前
|
数据库
SpringMVC之CRUD------增删改查
SpringMVC之CRUD------增删改查
38 0
|
5月前
|
XML Java 数据格式
学习SpringMvc第三战-利用SpringMvc实现CRUD
学习SpringMvc第三战-利用SpringMvc实现CRUD
|
5月前
|
Java 数据库连接 Maven
SpringMvc 之crud增删改查应用
SpringMvc 之crud增删改查应用
43 0
|
6月前
|
SQL
SpringMVC系列(三)之CRUD增删改查
SpringMVC系列(三)之CRUD增删改查
|
6月前
|
前端开发 Java 数据库连接
SpringMVC增删改查(CRUD)的实现
SpringMVC增删改查(CRUD)的实现
19 0
|
6月前
|
设计模式 前端开发 Java
SpringMVC的整合完成CRUD(增删改查)
SpringMVC的整合完成CRUD(增删改查)
21 0