中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

servlet實(shí)現(xiàn)文件上傳數(shù)據(jù)增刪該查

2018-07-20    來源:open-open

容器云強(qiáng)勢上線!快速搭建集群,上萬Linux鏡像隨意使用

控制層:

文件上傳需要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();
		// 獲得選中的復(fù)選框的值
		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();// 獲得記錄的總條數(shù)
		int currentPage = 1;// 當(dāng)前頁是第一頁
		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();
		// 已經(jīng)進(jìn)行分頁之后的數(shù)據(jù)集合
		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();
		// 構(gòu)建一個(gè)文件上傳類
		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");
						}
						// 把數(shù)據(jù)插入到數(shù)據(jù)庫中
					} 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();
	}

}


服務(wù)層:


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);
	// 提取所有產(chǎn)品的信息
	public List<Map<String, Object>> listProduct(String proname,int start,int end);
	
	public int getItemCount();
	
	public Map<String,Object> viewProduct(String proid);
}


數(shù)據(jù)訪問層:


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) 提取產(chǎn)品的信息
	 * 
	 * @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;// 表示顯示的條數(shù)
	private int recordCount;// 表示記錄的總條數(shù)
	private int currentPage;// 表示當(dāng)前頁

	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);
	}

	// 獲得總頁數(shù)
	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);
	}
}


標(biāo)簽: isp 數(shù)據(jù)庫

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇: 自動監(jiān)控url是否可用,如不可用則重啟應(yīng)用,并做相應(yīng)的報(bào)警策略

下一篇: IOS端的搖一搖功能