返回顶部

收藏

servlet实现文件上传数据增删该查

更多

控制层:

文件上传需要import org.apache.commons.fileuploadjar包

package com.product.dbutil.product.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
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;

import com.product.dbutil.product.dao.ProductDao;
import com.product.dbutil.product.service.ProductService;
import com.product.dbutil.product.util.DividePage;
import com.product.dbutil.product.util.UUIDTools;

public class ProductAction extends HttpServlet {

    private ProductService service;

    /**
     * Constructor of the object.
     */
    public ProductAction() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);

    }

    /**
     * The doPost method of the servlet. <br>
     * 
     * This method is called when a form has its tag value method equals to
     * post.
     * 
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String action_flag = request.getParameter("action_flag");
        if (action_flag.equals("add")) {
            addProduct(request, response);
        } else if (action_flag.equals("list")) {
            listProduct(request, response);
        } else if (action_flag.equals("del")) {
            delProduct(request, response);
        }else if(action_flag.equals("view")){
            viewProduct(request, response);
        }

        out.flush();
        out.close();
    }

    private void viewProduct(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String proid = request.getParameter("proid");
        Map<String,Object> map = service.viewProduct(proid);
        request.setAttribute("map", map);
        request.getRequestDispatcher("/product/2_1_5xs.jsp").forward(request, response);
    }

    private void delProduct(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String path = request.getContextPath();
        // 获得选中的复选框的值
        String[] ids = request.getParameterValues("ids");
        boolean flag = service.delProduct(ids);
        if (flag) {
            response.sendRedirect(path
                    + "/servlet/ProductAction?action_flag=list");
        }
    }

    private void listProduct(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // String path = request.getContextPath();
        // 接收用户的查询名字
        String proname = request.getParameter("proname");
        int recordCount = service.getItemCount();// 获得记录的总条数
        int currentPage = 1;// 当前页是第一页
        String pageNum = request.getParameter("pageNum");
        if (pageNum != null) {
            currentPage = Integer.parseInt(pageNum);
        }
        DividePage pUtil = new DividePage(5, recordCount, currentPage);
        int start = pUtil.getFromIndex();
        int end = pUtil.getToIndex();
        // 已经进行分页之后的数据集合
        List<Map<String, Object>> list = service.listProduct(proname, start,
                end);
        request.setAttribute("pUtil", pUtil);
        request.setAttribute("listproduct", list);
        request.setAttribute("proname", proname);
        request.getRequestDispatcher("/product/2_1_5.jsp").forward(request,
                response);
    }

    private void addProduct(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // 表单含有文件要提交
        String path = request.getContextPath();
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        // 构建一个文件上传类
        ServletFileUpload servletFileUpload = new ServletFileUpload(
                diskFileItemFactory);
        servletFileUpload.setFileSizeMax(3 * 1024 * 1024);
        servletFileUpload.setSizeMax(6 * 1024 * 1024);// 上传文件总大小
        List<FileItem> list = null;
        List<Object> params = new ArrayList<Object>();
        params.add(UUIDTools.getUUID());
        try {
            // 解析request的请求
            list = servletFileUpload.parseRequest(request);
            // 取出所有表单的值:判断非文本字段和文本字段
            for (FileItem fileItem : list) {
                if (fileItem.isFormField()) {
                    if (fileItem.getFieldName().equals("proname")) {
                        params.add(fileItem.getString("utf-8"));
                    }
                    if (fileItem.getFieldName().equals("proprice")) {
                        params.add(fileItem.getString("utf-8"));
                    }
                    if (fileItem.getFieldName().equals("proaddress")) {
                        params.add(fileItem.getString("utf-8"));
                    }
                } else {
                    try {
                        String image = fileItem.getName();
                        params.add(image);
                        String upload_path = request.getRealPath("/upload");
                        System.out.println("--->>" + upload_path);
                        //
                        File real_path = new File(upload_path + "/" + image);
                        fileItem.write(real_path);
                        boolean flag = service.addProduct(params);
                        if (flag) {
                            response
                                    .sendRedirect(path
                                            + "/servlet/ProductAction?action_flag=list");
                        }
                        // 把数据插入到数据库中
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * Initialization of the servlet. <br>
     * 
     * @throws ServletException
     *             if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
        service = new ProductDao();
    }

}

服务层:

package com.product.dbutil.product.service;

import java.util.List;
import java.util.Map;

public interface ProductService {

    public boolean addProduct(List<Object> params);

    public boolean delProduct(String[] ids);
    // 提取所有产品的信息
    public List<Map<String, Object>> listProduct(String proname,int start,int end);

    public int getItemCount();

    public Map<String,Object> viewProduct(String proid);
}

数据访问层:

package com.product.dbutil.product.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import com.product.dbutil.jdbc.JdbcUtils;
import com.product.dbutil.product.service.ProductService;

public class ProductDao implements ProductService {

    private JdbcUtils jdbcUtils;

    public ProductDao() {
        // TODO Auto-generated constructor stub
        jdbcUtils = new JdbcUtils();
    }

    public boolean addProduct(List<Object> params) {
        // TODO Auto-generated method stub
        boolean flag = false;
        try {
            String sql = "insert into product(proid,proname,proprice,proaddress,proimage) values(?,?,?,?,?)";
            jdbcUtils.getConnection();
            flag = jdbcUtils.updateByPreparedStatement(sql, params);
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            jdbcUtils.releaseConn();
        }
        return flag;
    }

    /*
     * (non-Javadoc) 提取产品的信息
     * 
     * @see com.product.dbutil.product.service.ProductService#listProduct()
     */
    public List<Map<String, Object>> listProduct(String proname, int start,
            int end) {
        // TODO Auto-generated method stub
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        String sql = "select * from product where (1=1) ";
        // limit ?,?
        StringBuffer buffer = new StringBuffer(sql);
        List<Object> params = new ArrayList<Object>();
        if (proname != null) {
            buffer.append(" and proname like ? ");
            params.add("%" + proname + "%");
        }
        buffer.append("limit ?,? ");
        params.add(start);
        params.add(end);
        try {
            jdbcUtils.getConnection();
            list = jdbcUtils.findMoreResult(buffer.toString(), params);
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            jdbcUtils.releaseConn();
        }
        return list;
    }

    public int getItemCount() {
        int result = 0;
        Map<String, Object> map = null;
        String sql = " select count(*) mycount from product ";
        try {
            jdbcUtils.getConnection();
            map = jdbcUtils.findSimpleResult(sql, null);
            result = Integer.parseInt(map.get("mycount").toString());
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            jdbcUtils.releaseConn();
        }
        // TODO Auto-generated method stub
        return result;
    }

    public boolean delProduct(String[] ids) {
        // TODO Auto-generated method stub
        boolean flag = false;
        try {
            jdbcUtils.getConnection();
            String[] sql = new String[ids.length];
            if (ids != null) {
                for (int i = 0; i < ids.length; i++) {
                    sql[i] = "delete from product where proid='" + ids[i] + "'";
                }
            }
            flag = jdbcUtils.deleteByBatch(sql);
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            jdbcUtils.releaseConn();
        }
        return flag;
    }

    public Map<String, Object> viewProduct(String proid) {
        // TODO Auto-generated method stub
        Map<String, Object> map = null;
        try {
            String sql = "select * from product where proid = ? ";
            List<Object> params = new ArrayList<Object>();
            params.add(proid);
            jdbcUtils.getConnection();
            map = jdbcUtils.findSimpleResult(sql, params);
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            jdbcUtils.releaseConn();
        }
        return map;
    }

}

分页查找工具类:

package com.product.dbutil.product.util;

public class DividePage {

    private int pageSize;// 表示显示的条数
    private int recordCount;// 表示记录的总条数
    private int currentPage;// 表示当前页

    public DividePage(int pageSize, int recordCount, int currentPage) {
        // TODO Auto-generated constructor stub
        this.pageSize = pageSize;
        this.recordCount = recordCount;
        setCurrentPage(currentPage);
    }

    public DividePage(int pageSize, int recordCount) {
        // TODO Auto-generated constructor stub
        this(pageSize, recordCount, 1);
    }

    // 获得总页数
    public int getPageCount() {
        int size = recordCount / pageSize;
        int mod = recordCount % pageSize;
        if (mod != 0) {
            size++;
        }
        return recordCount == 0 ? 1 : size;
    }

    public int getFromIndex() {
        return (currentPage - 1) * pageSize;
    }

    public int getToIndex() {
        return pageSize;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        int validPage = currentPage <= 0 ? 1 : currentPage;
        validPage = validPage > getPageCount() ? getPageCount() : validPage;
        this.currentPage = validPage;
    }

    public int getPageSize() {
        return pageSize;
    }

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

    public int getRecordCount() {
        return recordCount;
    }

    public void setRecordCount(int recordCount) {
        this.recordCount = recordCount;
    }
}

唯一ID工具类:

package com.product.dbutil.product.util;

import java.util.UUID;

public class UUIDTools {

    public UUIDTools() {
        // TODO Auto-generated constructor stub
    }

    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-", "").substring(0, 6);
    }
}

标签:java

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. coder4 发表 2017-12-15 05:16:05 SpringBoot调整Configuration的执行顺序
  2. Liwen 发表 2013-08-30 19:03:42 Neo4j Server启动失败
  3. anLA7856 发表 2017-12-13 12:24:15 Java8中的WeakHashMap
  4. coder4 发表 2017-11-22 05:35:26 SpringBoot实现从配置中注入多级Map到bean中
  5. coder4 发表 2017-11-17 17:41:48 maven学习手记+nexus配置+更换中央仓库为阿里云仓库
  6. coder4 发表 2017-11-21 06:34:13 Spring实现Transactional执行成功/回滚后执行额外操作
  7. coder4 发表 2017-12-06 10:25:18 gradle如何配置发布maven包到nexus私服
  8. coder4 发表 2017-12-06 10:03:11 gradle如何配置maven私服的认证
  9. coder4 发表 2017-12-08 07:54:42 gradle中如何实现maven的bom功能
  10. coder4 发表 2017-12-08 08:53:16 压力测试工具gatling
  11. 加多 发表 2017-12-10 11:35:09 诡异的类型转换
  12. Hesey Wang 发表 2017-11-17 03:39:50 2017 JavaOne参会感想

发表评论