《老罗Android》学习之web编程实现产品表维护

1. 用程序创建表
在WebContent新建文件夹sql,新建文件sql.txt:
CREATE TABLE `product` (
  `proid` varchar(64) NOT NULL DEFAULT '',
  `proname` varchar(64) DEFAULT NULL,
  `proprice` varchar(64) DEFAULT NULL,
  `proaddress` varchar(64) DEFAULT NULL,
  `proimage` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`proid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在Navicat 8 for mysql中选择数据库,右键--->console---》把内容拷贝进去,回车----》 select * from product; 就用程序创建了一张product表。
2. 添加产品信息

1. 点击产品信息,显示2_1_5.jsp.点击添加,跳转到2_1_5tj.jsp。
   <a href="<%=path%>/product/2_1_5tj.jsp">.... </a>
2. 2_1_5tj.jsp 点确定时,提交添加操作:

<script type="text/javascript">
 function dosubmit(){
   var th = document.form1;
   th.action="<%=path%>/ProductAction?action_flag=add";
   th.submit();
 }
</script>
3. ProductAction.java

product也采用分层架构:
action:控制层,dao:数据访问层,service:服务层
@WebServlet("/ProductAction")
public class ProductAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private ProductService service;   
    public ProductAction() {
        super();
    }
	public void init(ServletConfig config) throws ServletException {
		service = new ProductDao();
	}
	public void destroy() {
		super.destroy();
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	protected 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 {
		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 {
		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 {
		// 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);//每页5条,总记录条数,当前页
		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) {
						e.printStackTrace();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}
}
1) DiskFileItemFactory,创建FileItem,获得它在内存当中的内容。
FileItem: 当form表单提交的时候,<Input>标签所涵盖的内容都会提交到服务器端,所以FileItem表示所有表单中以<Input>开始的内容。
2)fileItem.getName()  windowsxp下得到的是全路径
java 文件路径截取:例如:获取到的文件路径image为C:\My Documents\logo.gif
/**java中\\表示一个\,而regex中\\也表示\,所以当\\\\解析成regex的时候为\\  **/
String temp[] = filePath.split("\\\\");
由于unix中file.separator为斜杠"/",下面这段代码可以处理windows和unix下的所有情况:   
String temp[] = image.replaceAll("\\\\","/").split("/");
String fileName = "";
if(temp.length > 1){
    fileName = temp[temp.length - 1];
}
3) boolean flag = service.addProduct(params);
调用ProductDao.java的addProduct方法。
4.ProductDao.java
public class ProductDao implements ProductService {
	private JdbcUtils jdbcUtils;
	public ProductDao() {
		jdbcUtils = new JdbcUtils();
	}
	public boolean addProduct(List<Object> params) {
		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) {
		} finally {
			jdbcUtils.releaseConn();
		}
		return flag;
	}
	public List<Map<String, Object>> listProduct(String proname, int start,	int end) {
		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) {
		} 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) {
		} finally {
			jdbcUtils.releaseConn();
		}
		return result;
	}
	public boolean delProduct(String[] ids) {
		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) {
		} finally {
			jdbcUtils.releaseConn();
		}
		return flag;
	}

	public Map<String, Object> viewProduct(String proid) {
		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) {
		} finally {
			jdbcUtils.releaseConn();
		}
		return map;
	}
}
5. ProductService.java
定义接口
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);
}
3. 查询产品信息
在2_1_5.jsp中填充查询的数据,先从请求中得到信息:
List<Map<String, Object>> list = (List<Map<String, Object>>)request.getAttribute("listproduct");
DividePage pUtil = (DividePage)request.getAttribute("pUtil");

请求信息是在ProductDao.java中的 listProduct()中设置:
request.setAttribute("pUtil", pUtil);
request.setAttribute("listproduct", list);
request.setAttribute("proname", proname);
request.getRequestDispatcher("/product/2_1_5.jsp").forward(request,	response);
根据从数据库中得到的信息,把它们都罗列在网页上:
<% 
if(!list.isEmpty()){
 for(Map<String,Object> map:list){
%>
<TR bgColor=#ffffff height=2>
  <TD height="28" align="center" valign="top" noWrap>
	<input name="ids" type="checkbox" class="text2" value="<%=map.get("proid") %>">														</TD>
<TD align="center" valign="middle" noWrap>
<span class="foot3"><%=map.get("proname") %></span></TD>
<TD align="center" valign="middle" noWrap class="foot3"><%=map.get("proaddress") %></TD>
<TD align="center" valign="middle">
<span class="foot3"><%=map.get("proprice") %></span></TD>
</TR>
<% 
	}
	}
%>
4.  分页的功能
MySQL当中分页的功能采用的是:limit ?,?
一个问号时:limit ?  //每次提取的最大条数
两个问号时:limit ?,?  //每次提取的最大条数及 开始提取的记录位置
写一个分页的处理类:DividePage.java
public class DividePage {
	private int pageSize;// 表示显示的条数
	private int recordCount;// 表示记录的总条数
	private int currentPage;// 表示当前页
	public DividePage(int pageSize, int recordCount, int currentPage) {
		this.pageSize = pageSize;
		this.recordCount = recordCount;
		setCurrentPage(currentPage);
	}
	public DividePage(int pageSize, int recordCount) {
		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;
	}
}
在2_1_5.jsp中导入在分页功能的包:
<%@ page import="com.product.dbutil.product.util.*" %> 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值