页面分页实现、文件上传和下载

分页实现

思路:

  • 确定每页显示的数据数量

  • 确定分页显示所需的总页数

  • 编写SQL查询语句,实现数据查询

    • # oracle
      select * from (select  ROWNUM rn,t.* from (select * from 要查询的表名 [where 条件][...] ) t where ROWNUM <= 结束索引) temp where temp.rn >= 开始索引;
      
  • 在面中进行分页显示设置

封装Pageable类

import java.util.List;

public class Pageable<Type> {
    private int currPageNo; 		// 当前页码
    private int pageSize; 			// 页面大小,即每页显示记录数
    private int totalCount; 		// 总记录数
    private int totalPageCount; 	// 总页数
    List<Type> list; 				// 每页Type类型的集合

    public Pageable() {
    }

    public Pageable(int currPageNo, int pageSize) {
        this.currPageNo = currPageNo;
        this.pageSize = pageSize;
    }

    public int getCurrPageNo() {
        return currPageNo;
    }

    public void setCurrPageNo(int currPageNo) {
        this.currPageNo = currPageNo;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int gettotalPageCount() {
        return totalPageCount;
    }

    public void settotalPageCount(int totalPageCount) {
        this.totalPageCount = totalPageCount;
    }

    public List<Type> getList() {
        return list;
    }

    public void setList(List<Type> list) {
        this.list = list;
    }
}

计算总页数:

totalPageCunt = (int)Math.celi(1.0 * totalCount / pageSize)

开始索引:

startIndex = (currPageNo - 1 ) * pageSize + 1

结束索引

endIndex= currPageNo * pageSize + 1

文件上传

前端代码

<!-- 文件上传一定要有enctype="multipart/form-data" 且必须为post提交 -->
<form action='#' method='post' enctype="multipart/form-data">
    账号:<input type="text" name="username" placeholder="请输入账号"><br>
    密码:<input type="password" name="password" placeholder="请输入密码"><br>
    <input type="file" name="file"><br>
    <input type="submit" value="上传">
</form>

后端代码

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

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@WebServlet("/uploadFile")
public class UploadFileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletOutputStream out = response.getOutputStream();
        try {
            // 文件上传
            // 1、创建文件工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024 * 1024 * 10); // 设置缓存大小

            String realPath = getServletContext().getRealPath("/tempfile");
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            factory.setRepository(file);

            // 2、创建upload对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            request.setCharacterEncoding("utf8");
            // 设置单文件大小
            upload.setSizeMax(1024 * 500);
            // 设置总文件大小
            upload.setFileSizeMax(1024 * 1024 * 5);
            // 3、解析request
            List<FileItem> list = null;

            list = upload.parseRequest(request);


            // 4、遍历集合
            for (FileItem item : list) {
                if (item.isFormField()) { // 普通的表单字段
                    String fieldName = item.getFieldName();
                    String value = item.getString();
                    value = new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                    System.out.println(fieldName + " - " + value);
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    long size = item.getSize();
                    if ("".equals(fileName) && size == 0) {
                        break;
                    }
                    String contentType = item.getContentType();
                    System.out.println(fieldName + " - " + fileName + " - " + size + " - " + contentType);
                    if (!contentType.contains("image")) {
                        out.print("文件只能是图片!");
                        return;
                    }

                    String suffix = fileName.substring(fileName.lastIndexOf('.'));
                    String simpleName = fileName.substring(0, fileName.lastIndexOf('.'));

                    String newFileName = simpleName + "_" + new Date().getTime() + suffix;
                    realPath = getServletContext().getRealPath("/upload");
                    file = new File(realPath + "/" + newFileName);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    file.createNewFile();
                    // 保存起来
                    item.write(file);
                }
            }
        } catch (FileUploadBase.SizeLimitExceededException e) {
            out.print("文件太大了!最大500kb哦!");
        } catch (Exception ignore) {
        }
        response.sendRedirect(request.getContextPath() + "/fileList.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

用到的JAR包

  • commons-fileupload-1.2.1.jar
  • commons-io-1.3.2.jar

文件下载

前台jsp代码

<%@ page import="java.io.File" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件展示</title>
</head>
<body>
<%
    String realPath = application.getRealPath("/upload");
    File path = new File(realPath);
    if (!path.exists()) {
        out.print("文件夹不存在!");
        return;
    }
    File[] files = path.listFiles();
%>
<ul>
    <%
        for (File file : files) {
    %>
    <li><%=file.getName()%>&nbsp;&nbsp;<a href="<%=request.getContextPath()%>/downloadFile?fileName=<%=file.getName()%>">下载</a></li>
    <%
        }
    %>
</ul>
</body>
</html>

后台代码

import javax.activation.MimetypesFileTypeMap;
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 java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet("/downloadFile")
public class DownloadFileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        // 获取请求文件名
        String fileName = request.getParameter("fileName");
        // 获取文件路径
        String filePath = getServletContext().getRealPath("/upload") + "/" + fileName;
        // 设置Content-Disposition
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF8"));
        //好了 ,现在通过IO流来传送数据
        FileInputStream input = new FileInputStream(filePath);
        OutputStream output = response.getOutputStream();
        byte[] buff = new byte[1024 * 10];//可以自己 指定缓冲区的大小
        int len = 0;
        while ((len = input.read(buff)) > -1) {
            output.write(buff, 0, len);
        }
        //关闭输入输出流
        input.close();
        output.close();
        response.sendRedirect(request.getContextPath() + "/fileList.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

posted @ 2020-10-15 11:45  YeCaiYu  阅读(276)  评论(0编辑  收藏  举报