본문 바로가기

포트폴리오/Spring Framework

스프링 프레임워크 - 관리자 상품 등록하기

상품을 등록하기위해 상품정보를 저장할 데이터베이스가 필요하다.

상품 테이블을 작성한다.

 

create table product(
    prodnum number(5) primary key,
    name varchar2(200) default 0,
    kind varchar2(20), -- bag, wallet, shoes, acc
    price1 number(7) default 0,
    price2 number(7) default 0,
    price3 number(7) default 0,
    content varchar2(1000) default null,
    image varchar2(50) default 'default.jpg',
    useyn char default 'y', -- 판매 : y, 판매중단 : n
    regdate date default sysdate,
    viewnum number default 0 not null);
    
    create sequence product_seq start with 1 increment by 1;

 

그리고 테이블 관련 이미지들을 저장할 테이블을 작성한다.

create table product_images(
    prodnum number(5),
    name varchar2(20),
    detail_image varchar2(50),
    prodimagenum number(5) primary key,
    constraint fk_prod_image_name foreign key(prodnum)references product(prodnum)
);

create sequence prod_image_seq start with 1 increment by 1;

 

테이블 데이터를 임시 저장할 데이터객체를 생성한다.

 

<ProductVO.java>

package com.portfolio.biz.product.dto;

import java.sql.Timestamp;

import lombok.Data;

@Data
public class ProductVO {
	private int rn;
	private int prodnum;
	private String name;
	private String kind;
	private int price1;
	private int price2;
	private int price3;
	private String content;
	private String image;
	private String useyn;
	private Timestamp regdate;
	private int viewnum;
	private int prodimagenum;
	private String detail_image;
}

 

그리고 상품을 등록하고 조회할 쿼리를 product-mapping.xml 파일에 작성한다.

<product-mapping.xml>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="ProductDAO">
	<select id="maxProductNum" resultType="int">
		select NVL2(max(prodnum), max(prodnum) + 1, 1) from product
	</select>
	
	<insert id="enrollProduct">
		insert into product(prodnum, name, kind, price1,
		price2, price3, content, image)
		values(#{prodnum}, #{name},
		#{kind}, #{price1}, #{price2}, #{price3}, #{content}, #{image})
	</insert>
	
	<insert id="insertProductImage">
		insert into product_images(prodnum, name, detail_image, prodimagenum)
		values(#{prodnum}, #{name}, #{detail_image}, prod_image_seq.nextval)
	</insert>

	<select id="getProductList" parameterType="String"
		resultType="product">
		select * from product
		where kind like '%' || #{kind} || '%'
		order by regdate desc
	</select>

</mapper>

 

그리고 mybatis를 이용하여 데이터들을 가져온다.

<ProductDAO.java>

package com.portfolio.biz.product.impl;

import java.util.HashMap;
import java.util.List;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.portfolio.biz.product.dto.ProductVO;
import com.portfolio.biz.utils.Criteria;

@Repository
public class ProductDAO {
	@Autowired
	private SqlSessionTemplate mybatis;
	
	public void enrollProduct(ProductVO vo) {
		System.out.println("==> Mybatis로 enrollProduct() 기능 처리");
		mybatis.insert("ProductDAO.enrollProduct", vo);
	}
	
	public List<ProductVO> getProductList(String kind){
		System.out.println("==> Mybatis로 getProductList() 기능 처리");
		return mybatis.selectList("ProductDAO.getProductList", kind);
	}
	
	public List<ProductVO> getProductListPaging(String kind, Criteria criteria){
		System.out.println("==> Mybatis로 getProductListPaging() 기능 처리");
		
		HashMap<String, Object> map = new HashMap<>();
		map.put("kind", kind);
		map.put("criteria", criteria);
		return mybatis.selectList("ProductDAO.getProductListPaging", map);
	}
	
	public ProductVO getProductByProdnum(int prodnum) {
		System.out.println("==> Mybatis로 getProductByProdNum() 기능 처리");
		return mybatis.selectOne("ProductDAO.getProductByProdnum", prodnum);
	}
}

 

그리고 실행시킬 서비스 파일을 작성한다.

<ProductService.java>

package com.portfolio.biz.product;

import java.util.List;

import com.portfolio.biz.product.dto.ProductVO;
import com.portfolio.biz.utils.Criteria;

public interface ProductService {

	void enrollProduct(ProductVO vo);
	
	List<ProductVO> getProductList(String kind);
	
	ProductVO getProductByProdnum(int prodnum);
	
	void updateProduct(ProductVO vo);
	
	void updateViewnum(ProductVO vo);

}

 

<ProductServiceImpl.java>

package com.portfolio.biz.product.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.portfolio.biz.product.ProductService;
import com.portfolio.biz.product.dto.ProductVO;
import com.portfolio.biz.utils.Criteria;

@Service("productService")
public class ProductServiceImpl implements ProductService {

	@Autowired
	private ProductDAO productDAO;
	
	@Override
	public void enrollProduct(ProductVO vo) {
		productDAO.enrollProduct(vo);
	}

	@Override
	public List<ProductVO> getProductList(String kind) {
		return productDAO.getProductList(kind);
	}

	@Override
	public ProductVO getProductByProdnum(int prodnum) {
		return productDAO.getProductByProdnum(prodnum);
	}

	@Override
	public void updateViewnum(ProductVO vo) {
		productDAO.updateViewnum(vo);
	}


}

 

그리고 View로 넘겨줄 컨트롤러를 작성한다.

관리자가 상품을 등록할 것이기 때문에 관리자 컨트롤러에서 페이지가 넘어가게하고

상품 컨트롤러에서 등록을 진행한다.

<AdminController.java>

package com.portfolio.view.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.portfolio.biz.employee.AdminService;
import com.portfolio.biz.employee.dto.AdminVO;
import com.portfolio.biz.order.OrderService;
import com.portfolio.biz.order.dto.OrderVO;
import com.portfolio.biz.product.ProductService;
import com.portfolio.biz.product.dto.ProductVO;
import com.portfolio.biz.qna.QnaService;
import com.portfolio.biz.qna.dto.QnaVO;
import com.portfolio.biz.utils.Criteria;
import com.portfolio.biz.utils.PageMaker;

@Controller
@SessionAttributes("adminUser")
public class AdminController {

	@Autowired
	private AdminService adminService;
	@Autowired
	private ProductService productService;

	@RequestMapping(value = "admin_product_list")
	public String adminPorudctListPagingView(
			@RequestParam(value = "kind", defaultValue = "", required = false) String kind, Criteria criteria,
			HttpSession session, Model model) {
		AdminVO employee = (AdminVO) session.getAttribute("adminUser");

		if (employee == null) {
			return "admin/login";
		} else {
			List<ProductVO> productList = productService.getProductListPaging(kind, criteria);

			PageMaker pageMaker = new PageMaker();
			pageMaker.setCri(criteria);

			int productCount = productService.countProductList(kind);
			pageMaker.setTotalCount(productCount);

			model.addAttribute("productList", productList);
			model.addAttribute("pageMaker", pageMaker);
			return "admin/product/productlist";
		}
	}

	@RequestMapping(value = "admin_enroll_product")
	public String adminEnrollProductView(HttpSession session, Model model) {
		AdminVO employee = (AdminVO) session.getAttribute("adminUser");
		String[] kindList = { "bag", "wallet", "shoes", "acc" };
		if (employee == null) {
			return "admin/login";
		} else {
			model.addAttribute("kindList", kindList);
			return "admin/product/enrollproduct";
		}
	}
}

 

<ProductController.java>

package com.portfolio.view.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.portfolio.biz.employee.dto.AdminVO;
import com.portfolio.biz.product.ProductService;
import com.portfolio.biz.product.dto.ProductVO;
import com.portfolio.biz.utils.Criteria;
import com.portfolio.biz.utils.PageMaker;

@Controller
public class ProductController {
	@Autowired
	private ProductService productService;

	@RequestMapping(value = "admin_enroll_product", method = RequestMethod.POST)
	public String enrollProductAction(
			@RequestParam(value = "product_image", defaultValue = "", required = false) MultipartFile uploadFile,
			MultipartHttpServletRequest mtfRequest,
			Model model, HttpSession session, ProductVO vo) {
		AdminVO employee = (AdminVO) session.getAttribute("adminUser");

		if (employee == null) {
			return "admin/login";
		} else {
			List<MultipartFile> detailImgFileList = mtfRequest.getFiles("product_detail_image");
			
			int prodnum = productService.maxProductNum();
			
			vo.setProdnum(prodnum);
			
			String thumnailFileName = "";
			if (!uploadFile.isEmpty()) {
				String root_path = session.getServletContext().getRealPath("WEB-INF/resources/product_images/");

				thumnailFileName = uploadFile.getOriginalFilename();

				File file = new File(root_path + thumnailFileName);

				try {
					uploadFile.transferTo(file);
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			vo.setImage(thumnailFileName);
			vo.setPrice3(vo.getPrice2() - vo.getPrice1());

			productService.enrollProduct(vo);
			
			if(detailImgFileList.size() < 1) {
				vo.setDetail_image("");
				productService.insertProductImage(vo);
			} else {
				for(MultipartFile mf : detailImgFileList) {
					String fileName = mf.getOriginalFilename();
					String detail_img_root_path = session.getServletContext().getRealPath("WEB-INF/resources/product_images/");
					File detailFile = new File(detail_img_root_path + fileName);
					
					try {
						mf.transferTo(detailFile);
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					vo.setDetail_image(fileName);
					productService.insertProductImage(vo);
				}
			}
			return "redirect:admin_product_list";
		}
	}

	@RequestMapping(value = "admin_product_detail")
	public String productDetailView(@RequestParam(value = "prodnum") int prodnum, HttpSession session, Model model) {
		AdminVO employee = (AdminVO) session.getAttribute("adminUser");

		if (employee == null) {
			return "admin/login";
		} else {
			ProductVO product = productService.getProductByProdnum(prodnum);
			model.addAttribute("product", product);
			
			List<ProductVO> productDetailImage = productService.detailProductImage(prodnum);
			
			model.addAttribute("productDetailImage", productDetailImage);
			return "admin/product/productdetail";
		}
	}

	@RequestMapping(value = "admin_modify_product")
	public String modifyProductView(@RequestParam(value = "prodnum") int prodnum, HttpSession session, Model model) {
		AdminVO employee = (AdminVO) session.getAttribute("adminUser");
		ProductVO product = productService.getProductByProdnum(prodnum);
		String[] kindList = { "", "bag", "wallet", "shoes", "acc" };

		if (employee == null) {
			return "admin/login";
		} else {
			model.addAttribute("product", product);
			model.addAttribute("kindList", kindList);
			return "admin/product/modifyproduct";
		}
	}
}

 

 상품 등록하기 위해서 설정이 필요하다.

jamesyleather.tistory.com/401

 

스프링 프레임 워크 - 사진 업로드, 여러장 사진 업로드

HTML에서 사진 업로드를 위해 태그를 사용하여 업로드할 수 있다. 스프링 프레임워크에서 사진 업로드 하기 위해 몇 가지 사전 준비단계가 필요하다. pom.xml에 dependency를 추가해야한다. commons-fileup

jamesyleather.tistory.com

 

728x90
반응형