listproductaction.java

来自「一个很不错的网上小型购物系统」· Java 代码 · 共 54 行

JAVA
54
字号
package action;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import service.ProductService;
import service.ServiceFactory;
import domain.Product;

public class ListProductAction extends Action {
	ProductService productService = ServiceFactory.getProductService();

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		List list = productService.findAll();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Product product = (Product) it.next();
			ServletContext ctx = this.getServlet().getServletContext();
			String fileName = ctx.getRealPath("res" + "/" + product.getId()
					+ ".jpg");
			File file = new File(fileName);
			if (!file.exists()) {
				InputStream is = product.getPic().getBinaryStream();
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(file));
				int b = -1;
				while ((b = is.read()) != -1) {
					bos.write(b);
				}
				bos.close();
				is.close();
			}
		}
		request.setAttribute("productList", list);
		ActionForward forward = new ActionForward("ProductListView");
		return forward;
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?