Study/JSP

JSP 쇼핑몰 MVC 모델2로 변경하기-2

토기발 2022. 5. 21. 20:38

어제 올린 카테고리에 이어 상품 등록 / 수정 / 삭제 / 목록 / 상세 기능을 MVC 모델2로 변경합니다.

개인 공부용이므로 잘못된 부분이 있으면 언제나 지적 환영합니다^_^~

 

 


 

prod_input.jsp은 cate_input과 동일하게 request.getAttribute()를 사용하기 때문에 생략한다.

 

ProdInputCommand.java

public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		CategoryDAO cdao = new CategoryDAOImpl();	
		List<CategoryDTO> clist = cdao.listCate();
		if(clist == null || clist.size() == 0){
			req.setAttribute("msg", "카테고리를 먼저 등록해 주세요!!");
			req.setAttribute("url", "cate_input.admin");
			return "message.jsp";
		}
		req.setAttribute("listCate", clist);
		return "WEB-INF/shop/admin/prod_input.jsp";
	}

카테고리가 등록되어 있어야 상품 등록이 가능하도록 코드를 작성했다.

카테고리 리스트를 불러내기 위해 CategoryDAOImpl() 호출, listCate() 실행

카테고리가 등록되어 있지 않으면 카테고리 등록창으로 보내고, 카테고리가 있다면 setAttribute()로 jsp에 정보를 넘겨주기 위해 속성값을 정한다.

 

prod_input_ok.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page import="com.oreilly.servlet.*, java.io.*" %>    
<!-- prod_input_ok.jsp -->
<%
		MultipartRequest mr = null;
		String upPath = application.getRealPath("/myshop/images");
		int length = 10*1024*1024;
		try{
			mr = new MultipartRequest(request, upPath, length, "EUC-KR");   
		}catch(IOException e){%>
			<script type="text/javascript">
				alert("상품 등록 실패!! 상품 등록 페이지로 이동합니다.")
				location.href="prod_input.jsp"
			</script>
<%		e.printStackTrace();
			return;
		}%>    
<jsp:useBean id="pdao" class="my.shop.ProductBean" />
<jsp:useBean id="pool" class="my.db.ConnectionPoolBean" scope="application"/>
<jsp:setProperty property="pool" name="pdao" value="<%=pool%>"/>
<% 
		int res = pdao.insertProd(mr);
		String msg = null, url = null;
		if (res>0){
			msg = "상품 등록 성공!! 상품 목록페이지로 이동합니다.";
			url = "prod_list.jsp";					
		}else {
			msg = "상품 등록 실패!! 상품 등록페이지로 이동합니다.";
			url = "prod_input.jsp";	
		}
%>
<script type="text/javascript">
alert("<%=msg%>")
location.href="<%=url%>"
</script>

mvc모델1의 jsp이다. 이미지파일을 업로드하기 위해 MultipartRequest를 사용했다.

이 파일에는 사용자에게 보여줄 뷰가 없기에 모델2에서는 삭제하고 정보는 커멘드에 작성한다. 

 

ProdInputOkCommand.java

public class ProdInputOkCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		MultipartRequest mr = null;
		String upPath = req.getServletContext().getRealPath("/images");
		int length = 10*1024*1024;
		try{
			mr = new MultipartRequest(req, upPath, length, "EUC-KR");
		}catch(IOException e){
			System.out.println("MultipartRequest 객체 생성 중 오류 발생!!");
			e.printStackTrace();
			req.setAttribute("msg", "상품 등록 실패!! 상품 등록 페이지로 이동합니다.");
			req.setAttribute("url", "prod_input.admin");
			return "message.jsp";
		}
		ProductDAO dao = new ProductDAOImpl();
		int res = dao.insertProduct(mr);
		String msg = null, url = null;
		if (res>0) {
			msg = "상품등록성공!! 상품목록페이지로 이동합니다.";
			url = "prod_list.admin";
		}else {
			msg = "상품등록실패!! 상품등록페이지로 이동합니다.";
			url = "prod_input.admin";
		}
		req.setAttribute("msg", msg);
		req.setAttribute("url", url);
		return "message.jsp";
	}

}

jsp 파일에 있는 alert과 location.href를 req.setAttribute()로 변경했다.

message.jsp 코드는 이렇다.

<%
		String msg = (String)request.getAttribute("msg");
		String url = (String)request.getAttribute("url");
%>
<script type="text/javascript">
	alert("<%=msg%>")
	location.href="<%=url%>"
</script>

req.setAttribute()에서 받은 msg를 팝업으로 출력하고 url로 이동하게 된다. 

 

 

 


 

 

prod_update.jsp (모델1)

<%
		String pnum = request.getParameter("pnum");
		if (pnum==null || pnum.trim().equals("")){
			response.sendRedirect("prod_list.jsp");
			return;
		}
		%>
<jsp:useBean id="pdao" class="my.shop.ProductBean" /> 
<jsp:useBean id="pool" class="my.db.ConnectionPoolBean" scope="application"/>
<jsp:setProperty property="pool" name="pdao" value="<%=pool%>"/>
<%	
		ProductDTO pdto = pdao.getProduct(Integer.parseInt(pnum));
		String upPath = request.getServletContext().getRealPath("/myshop/images");
%>
<%@ include file="top.jsp" %>
<div align="center">
	<form name="f" action="prod_update_ok.jsp" method="post" enctype="multipart/form-data">

 

 

prod_update.jsp (모델2)

<%	
		ProductDTO pdto = (ProductDTO)request.getAttribute("getProduct"); 
		String upPath = request.getServletContext().getRealPath("/images");
%>
<%@ include file="top.jsp" %>
<div align="center">
	<form name="f" action="prod_update_ok.admin" method="post" enctype="multipart/form-data">

 

 

ProdUpdateCommand.java

public class ProdUpdateCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String pnum = req.getParameter("pnum");
		ProductDAO dao = new ProductDAOImpl();
		ProductDTO dto = dao.getProduct(Integer.parseInt(pnum));
		req.setAttribute("getProduct", dto);
		return "WEB-INF/shop/admin/prod_update.jsp";
	}

 

모델2로 변경하면서 유효성 검사가 생략되었다. 주소로 검색해서 들어올 수가 없기 때문에 필요가 없기 때문이다.

하지만 pnum의 값은 필요하기 때문에 커멘드에서 getParameter를 사용하여 가져왔다.

 

 

pdao.getProduct(Integer.parseInt(pnum))

모델 2에서는 jsp에서 dao를 사용하지 않기 때문에 커멘드에서 dao.getProduct(Integer.parseInt(pnum))를 만들어서 jsp에 뿌려주어야 한다.
1. 먼저 ProductDAOImpl()을 호출 후 getProduct()를 실행한다.
2. 그 후 그 값을 setAttribute()에 넣어 jsp에 보낼 준비를 한다. 
3. jsp에서는 request.getAttribute("getProduct")로 값을 받아서 뿌려준다. 
4. 이 때, 값을 object로 받기 때문에 (ProductDTO)로 형변환을 해준다.

 

 

form태그의 acrion에 있는 주소가 모델 1,2가 다른데 모델2는 web.xml에 맵핑했던 이름으로 변경해야 한다.

.jsp로는 이동하지 못한다.

 

 

ProdUpdateOkCommand.java

public class ProdUpdateOkCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		MultipartRequest mr = null;
		String upPath = req.getServletContext().getRealPath("/images");
		int length = 10*1024*1024;
		try{
			mr = new MultipartRequest(req, upPath, length, "EUC-KR");
		}catch(IOException e){
			System.out.println("MultipartRequest 객체 생성 중 오류 발생!!");
			e.printStackTrace();
			req.setAttribute("msg", "상품 수정 실패!! 상품 수정 페이지로 이동합니다.");
			req.setAttribute("url", "prod_update.admin?pnum=" + mr.getParameter("pnum"));
			return "message.jsp";
		}
		ProductDAO dao = new ProductDAOImpl();
		int res = dao.updateProduct(mr);
		String msg = null, url = null;
		if (res>0) {
			msg = "상품수정성공!! 상품목록페이지로 이동합니다.";
			url = "prod_list.admin";
		}else {
			msg = "상품수정실패!! 상품등록페이지로 이동합니다.";
			url = "prod_update.admin?pnum=" + mr.getParameter("pnum");
		}
		req.setAttribute("msg", msg);
		req.setAttribute("url", url);
		return "message.jsp";
	}

ProdInputOkCommand와 거의 동일하다.

 

 

 


 

 

prod_delete.jsp

<%
		request.setCharacterEncoding("EUC-KR");
		String pnum = request.getParameter("pnum");
		String pimage = request.getParameter("pimage");
		
		if (pnum==null || pimage==null || pnum.trim().equals("") || pimage.trim().equals("")){
			response.sendRedirect("prod_list.jsp");
			return;
		}
%>
<jsp:useBean id="pdao" class="my.shop.ProductBean" /> 
<jsp:useBean id="pool" class="my.db.ConnectionPoolBean" scope="application"/>
<jsp:setProperty property="pool" name="pdao" value="<%=pool%>"/>
<%
		int res = pdao.deleteProd(Integer.parseInt(pnum));
		String msg = null, url = "prod_list.jsp";
		if (res>0){
			String upPath = config.getServletContext().getRealPath("/myshop/images");
			File file = new File(upPath, pimage);
			if (file.exists()){
				file.delete();
				msg = "상품삭제성공(이미지삭제 성공)!! 상품목록페이지로 이동합니다.";
			}else {
				msg = "상품삭제성공(이미지삭제 실패)!! 상품목록페이지로 이동합니다.";
			}
		}else {
			msg = "상품삭제실패!! 상품목록페이지로 이동합니다.";			
		}
%>
<script type="text/javascript">
	alert("<%=msg%>")
	location.href="<%=url%>"
</script>

 

 

ProdDeleteCommand.java

 

public class ProdDeleteCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String pnum = req.getParameter("pnum");
		String pimage = req.getParameter("pimage");
		
		ProductDAO dao = new ProductDAOImpl();
		int res = dao.deleteProduct(Integer.parseInt(pnum));
		String msg = null, url = "prod_list.admin";
		if (res>0){
			String upPath = req.getServletContext().getRealPath("/images");
			File file = new File(upPath, pimage);
			if (file.exists()){
				file.delete();
				msg = "상품삭제성공(이미지삭제 성공)!! 상품목록페이지로 이동합니다.";
			}else {
				msg = "상품삭제성공(이미지삭제 실패)!! 상품목록페이지로 이동합니다.";
			}
		}else {
			msg = "상품삭제실패!! 상품목록페이지로 이동합니다.";			
		}
		req.setAttribute("msg", msg);
		req.setAttribute("url", url);
		return "message.jsp";
	}

}

prod_delete.jsp 는 뷰가 없어서 파일을 삭제하고 정보를 커멘드에 옮겼다.

pnum과 pimage 값을 getParameter 로 받아온다.

ProductDAOImpl() 를 호출-> deleteProduct()실행

 

 


ProdListCommand.java

public class ProdListCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ProductDAO dao = new ProductDAOImpl();
		List<ProductDTO> list = dao.listProduct();
		req.setAttribute("listProduct", list);
		return "WEB-INF/shop/admin/prod_list.jsp";
	}

}

jsp파일은 달라진 부분이 없어서 커멘드 파일 코드만 올린다.

리스트를 불러오기 위해 ProductDAOImpl() 호출->listProduct() 실행, setAttribute()에 속성값 저장하여 jsp파일에 뿌려준다.

List<ProductDTO> plist = pdao.listProd();

-> List<ProductDTO> plist = (List)request.getAttribute("listProduct"); 

 

 


prod_view.jsp 모델1

<%
		String pnum = request.getParameter("pnum");
		if (pnum==null || pnum.trim().equals("")){
			response.sendRedirect("prod_list.jsp");
			return;
		}
		%>
<jsp:useBean id="pdao" class="my.shop.ProductBean" /> 
<jsp:useBean id="pool" class="my.db.ConnectionPoolBean" scope="application"/>
<jsp:setProperty property="pool" name="pdao" value="<%=pool%>"/>
<%	
		ProductDTO pdto = pdao.getProduct(Integer.parseInt(pnum));
		String upPath = request.getServletContext().getRealPath("/myshop/images");
		//application.getRealPath(), config.getServletContext().getRealPath()
		java.text.DecimalFormat df = new java.text.DecimalFormat("###,###");
%>

 

prod_view.jsp 모델2

<%	
		ProductDTO pdto = (ProductDTO)request.getAttribute("getProduct");
		String upPath = request.getServletContext().getRealPath("/images");
		DecimalFormat df = new DecimalFormat("###,###");
%>

유효성 검사와 useBean이 사라졌다. pool도 사용하지 않아 삭제했다. 

이전에 하던대로 .getAttribute()를 사용하여 dao의 정보를 받아왔다. 

 

 

ProdViewCommand.java

public class ProdViewCommand implements CommandIf {

	@Override
	public Object processCommand(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String pnum = req.getParameter("pnum");
		ProductDAO dao = new ProductDAOImpl();
		ProductDTO dto = dao.getProduct(Integer.parseInt(pnum));
		req.setAttribute("getProduct", dto);
		return "WEB-INF/shop/admin/prod_view.jsp";
	}

}

유효성 검사는 하지 않지만 pnum값은 필요하기 때문에 받아온다.

getProduct() 메소드 실행을 위해 dao를 호출하였다. 

해당 값을 dto에 받아 setAttribute()에 넣고 jsp에 뿌릴 준비를 한다.

 

이렇게 상품 등록 / 수정 / 삭제 / 목록 / 상세 기능도 변경을 완료하였다.

'Study > JSP' 카테고리의 다른 글

JSP 쇼핑몰 MVC 모델2로 변경하기-3  (0) 2022.05.21
JSP 쇼핑몰 MVC 모델2 로 변경하기  (0) 2022.05.21