servlet實現文件上傳數據增刪該查

gxw6 9年前發布 | 2K 次閱讀 Java

控制層:

文件上傳需要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);
    }
}


 本文由用戶 gxw6 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!