ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JSTL] file upload
    WEB/JSTL 2022. 9. 10. 11:51

    프로그램 다운로드

    Servlets.com | com.oreilly.servlet

     

    Servlets.com | com.oreilly.servlet

     

    www.servlets.com


    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>01_upload.jsp</title>
    </head>
    <body>
    
    <form action="upload.do" method="post" 
    			enctype="multipart/form-data">
    	글쓴이: <input type="text" name="name"><br>
    	제 &nbsp; 목: <input type="text" name="title"><br>
    	파일 저장하기: <input type="file" name="uploadFile"><br>
    	<input type="submit" value="전송">
    </form>
    
    </body>
    </html>
    package com.file.upload;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.oreilly.servlet.MultipartRequest;
    import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
    
    @WebServlet("/upload.do")
    public class UploadServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        public UploadServlet() {
            super();
        }
    
    	protected void doGet(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");
    		
    // 1 파일이 업로드될 타켓폴더를 지정, String으로 저장해둠
    		String savePath="upload";
    		
    // 2. 업로드될 파일의 용량을 제한하기 위한 용량값을 int 변수에 저장해둠
    		int uploadFileSizeLimit=5*1024*1024; 
    		// 1 바이트 기준
    		// 1024byte=12Kbyte 1024kByte=1MB
    		
    // 3. 인코딩 방식을 String 변수에 저장해둠
    		String encType="UTF-8";
    		
    // 4. 업로드될 서버의 실제 저장장소를 설정하여 String 변수에 저장해 둠
    		ServletContext context=getServletContext();
    		String uploadFilePath=context.getRealPath(savePath);
    		// savePath: "upload"
    		
    		System.out.println(uploadFilePath);
    		
    		MultipartRequest multi=new MultipartRequest(
    			request, 
    			// jsp에서 전달된 request 객체를 MultipartRequest로 전달함
    			// enctype="multipart/form-date"로 보낸 파라미터들은 일반 request로 값을 얻을 수 없음
    			// MultipartRequest에 request를 넣어서 복합사용해야 담겨 있는 유효한 값을 얻을 수 있음
    			uploadFilePath, // 서버상의 실제 저장장소
    			uploadFileSizeLimit, // 최대업로드 용량 제한
    			encType, // 인코딩 방식
    			new DefaultFileRenamePolicy() 
    			// 저장장소에 업로드되는 파일이름 중복시 문제해결하는 객체
    		);
    		// MultipartRequest 객체가 생성되는 순간 
    		// 업로드 되는 파일은 해당 경로에 업로드 완료함
    		
    		System.out.println("request로 처리-title: "+request.getParameter("title"));
    		// 일반 request는 multipart/form-date로 전달된 파라미터가 
    		// 모두 null로 수신됨
    		System.out.println("multi로 처리-title: "
    				+multi.getParameter("title"));
    		
    		String name=multi.getParameter("name");
    		String title=multi.getParameter("title");
    		String fileName=multi.getFilesystemName("uploadFile"); 
    		// 전달된 파일 이름 추출
    		
    		request.setAttribute("name", name);
    		request.setAttribute("title", title);
    		request.setAttribute("fileName", fileName);
    		
    		RequestDispatcher dp=request.getRequestDispatcher("01_result.jsp");
    		dp.forward(request, response);
    	}
    	
    	protected void doPost(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>01_result.jsp</title>
    </head>
    <body>
    
    <h3>
    글쓴이: ${name }<br>
    제목: ${title }<br>
    이미지: <br><img src="upload/${fileName }" width="200"/>
    </h3>
    	
    </body>
    </html>

     

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>02_upload.jsp</title>
    </head>
    <body>
    
    <form action="upload2.do?" method="post" 
    			enctype="multipart/form-data">
    	1. 파일 지정하기: <input type="file" name="uploadFile01"><br>
    	2. 파일 지정하기: <input type="file" name="uploadFile02"><br>
    	3. 파일 지정하기: <input type="file" name="uploadFile03"><br>
    	<input type="submit" value="전송">
    </form>
    
    </body>
    </html>
    package com.file.upload;
    
    import java.io.IOException;
    import java.util.Enumeration;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.oreilly.servlet.MultipartRequest;
    import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
    
    @WebServlet("/upload2.do")
    public class MultiFileUpload extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        public MultiFileUpload() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	protected void doGet(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		ServletContext context=getServletContext();
    		String uploadFilePath=context.getRealPath("upload");
    		
    		MultipartRequest multi=new MultipartRequest(
    			request, uploadFilePath, 5*1024*1024, "UTF-8", 
    			new DefaultFileRenamePolicy() 
    		); // 폼안에 있던 <input type="file">의 파일들을 MultipartRequest 생성 시 한번에 업로드 됨
    		
    		// 한번에 전달된 "파일이름들"은 Enumeration을 사용하여 전달받고 하나씩 꺼내서 사용함
    		Enumeration files=multi.getFileNames();
    		// 파일(<input type="file" name="uploadFile01">)들을
    		// Enumerationn에 저장
    		
    		int i=1;
    		while(files.hasMoreElements()) { 
            // 파일 요소의 갯수만큼 반복 실행
    			
    			String file=(String) files.nextElement(); 
                // 하나의 파일요소 추출
    			
    			// 업로드된 파일이름 추출(업로드 전)
    			String file_name=multi.getFilesystemName(file);
    			// (업로드 후) DefaultFileRenamePolicy에 의해 구분된 실제 파일 이름 추출
    			String ori_file_name=multi.getOriginalFileName(file);
    			
    			// 증가하는 숫자를 이용하여 Attribute 이름 생성
    			request.setAttribute("file_system_name"+i, file_name);
    			request.setAttribute("ori_file_name"+i, ori_file_name);
    			i++;
    		}
    		RequestDispatcher dp=request.getRequestDispatcher("02_result.jsp");
    		dp.forward(request, response);
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>02_result.jsp</title>
    </head>
    <body>
    
    <h3>
    <img src="upload/${file_system_name1}" width="200"/><br>
    폴더에 저장된 파일이름: ${file_system_name1 }<br>
    업로드전 파일이름: ${ori_file_name1 }<br>
    <br>
    <img src="upload/${file_system_name2}" width="200"/><br>
    폴더에 저장된 파일이름: ${file_system_name2 }<br>
    업로드전 파일이름: ${ori_file_name2 }<br>
    <br>
    <img src="upload/${file_system_name3}" width="200"/><br>
    폴더에 저장된 파일이름: ${file_system_name3 }<br>
    업로드전 파일이름: ${ori_file_name3 }<br>
    <br>
    </h3>
    	
    </body>
    </html>


    file upload form

    sql

    create table bookproduct(
    	code number(5) primary key,
    	name varchar2(100),
    	price number(8),
    	pictureurl varchar2(50),
    	description varchar2(1000)
    );
    create sequence bookproduct_seq start with 1 increment by 1;
    insert into bookproduct 
    values(bookproduct_seq.nextval, 
    'JQuery and JQuery mobile : 이해하기 쉼게 풀어쓴', 25000, 
    'jquery.jpg',
    '소스하나로 데스크탑과 모바일까지 HTML5와 함께 사용...');
    insert into bookproduct 
    values(bookproduct_seq.nextval, '자바의 신',
    30000, 'java.gif',
    '자바프로그래밍의 정석, 기초부터 실무 에제까지...');
    insert into bookproduct 
    values(bookproduct_seq.nextval, '오라클 데이터 베이스', 25000, 
    null ,
    '오라클 데이터 베이스 활용의 정석, 기초부터 실무 에제까지...');

     

    처음 실행 창

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <% response.sendRedirect("product.do?command=index"); %>
    </body>
    </html>

     

    Main Servlet

    package com.file.product.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.file.product.controller.action.Action;
    
    @WebServlet("/product.do")
    public class ProductServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        public ProductServlet() {
        }
    
    	protected void doGet(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");
    		String command=request.getParameter("command");
    		
    		ActionFactory af=ActionFactory.getInstance();
    		Action ac=null;
    		ac=af.getAction(command);
    		
    		if(ac==null) System.out.println("ac=null");
    		else ac.execute(request,response);
    	}
    
    	protected void doPost(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");
    		doGet(request, response);
    	}
    }

     

    ActionFactory

    package com.file.product.controller;
    
    public class ActionFactory {
    	
    	private ActionFactory() {}
    	private static ActionFactory itc = new ActionFactory();
    	public static ActionFactory getInstance() { return itc; }
    	
    	// getAction 생성
    	public Action getAction(String command) {
    		Action ac = null;
    		// 여기에 실행될 command 코드 작성
            // 코드 배경 줄무늬
    		return ac;
    	}
    }

     

    Action interface

    package com.file.product.controller.action;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public interface Action {
    	public void execute(HttpServletRequest request, 
    			HttpServletResponse response)
    			throws ServletException, IOException;;
    }

     

    Dao

    package com.file.product.dao;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    
    import com.file.product.dto.ProductVO;
    import com.file.product.util.Dbman;
    
    public class ProductDao {
    	private ProductDao() {}
    	private static ProductDao itc = new ProductDao();
    	public static ProductDao getInstance() { return itc; }
    	
    	Connection con=null;
    	PreparedStatement pstmt=null;
    	ResultSet rs=null;
    }

     

    Dto

    package com.file.product.dto;
    
    public class ProductVO {
    	private int code;
    	private String name;
    	private int price;
    	private String description;
    	private String pictureurl;
    	
    	public int getCode() {
    		return code;
    	}
    	public void setCode(int code) {
    		this.code = code;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getPrice() {
    		return price;
    	}
    	public void setPrice(int price) {
    		this.price = price;
    	}
    	public String getDescription() {
    		return description;
    	}
    	public void setDescription(String description) {
    		this.description = description;
    	}
    	public String getPictureurl() {
    		return pictureurl;
    	}
    	public void setPictureurl(String pictureurl) {
    		this.pictureurl = pictureurl;
    	}
    }
     
     

     

    상품 목록 창

    if( command.equals("index") ) ac = new IndexAction();
    package com.file.product.controller.action;
    
    import java.io.IOException;
    import java.util.ArrayList;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.file.product.dao.ProductDao;
    import com.file.product.dto.ProductVO;
    
    public class IndexAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		
    		ProductDao pdao=ProductDao.getInstance();
    		ArrayList<ProductVO> list=pdao.selectAll();
    		request.setAttribute("productList", list);
    		
    		String url="product/productList.jsp";
    		RequestDispatcher rd=request.getRequestDispatcher(url);
    		rd.forward(request, response);
    	}
    }

     

    Dao에 ArrayList<ProductVO> selectAll() 추가

    public ArrayList<ProductVO> selectAll() {
    	ArrayList<ProductVO> list=new ArrayList<>();
    	String sql="select*from bookproduct order by code desc";
    // order by code desc: 마지막에 등록된 레코드 맨위에서 보이게 설정
    	con = Dbman.getConnection();
    	try {
    		pstmt = con.prepareStatement(sql);
    		rs = pstmt.executeQuery();
    		while(rs.next()) {
    			ProductVO pvo = new ProductVO();
    			pvo.setCode(  rs.getInt("code") ) ;
    			pvo.setName(  rs.getString("name") ) ;
    			pvo.setPrice(  rs.getInt("price") ) ;
    			pvo.setPictureurl(  rs.getString("pictureurl") ) ;
    			pvo.setDescription(  rs.getString("description") ) ;
    			list.add(pvo);
    		}
    	} catch (SQLException e) {  e.printStackTrace();
    	} finally {  Dbman.close(  con, pstmt, rs);    }
    	return list;
    }

     

    css 파일

    @charset "UTF-8";
    
    #wrap { width: 971px; 
    				margin: 0; margin-left:auto; margin-right:auto;}
    h1 {	color: green;}
    table {	width: 100%;	border-collapse: collapse;	
    			font-size: 12px; line-height: 24px; }
    table td, th {border: #d3d3d3 solid 1px;padding: 5px;}
    th {	background: yellowgreen; }
    img{width:220px;}
    a { text-decoration: none;	 color: black; }
    a:HOVER {	text-decoration: underline;  color: green; }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>productList.jsp</title>
    
    <link rel="stylesheet" type="text/css" href="css/product.css">
    
    </head>
    <body>
    
    <div id="wrap" align="center">
    
    	<h1>상품 리스트 - 관리자 페이지</h1>
    	
    	<table class="list">
    		<tr><td colspan="5" style="border:white; text-align:right">
    			<a href="product.do?command=productWriteForm">
    				상품 등록</a></td></tr>
    		<tr><th>번호</th><th>제목</th><th>가격</th>
    				<th>수정</th><th>삭제</th></tr>
    		
    		<c:forEach var="product" items="${productList}">
    			<tr class="record">
    				<td align="center">${product.code }</td>
    				<td>
    					<a href="product.do?command=productView&code=${product.code}">
    					${product.name }</a></td>
    				<td align="right">${product.price }원</td>
    				<td align="center">
    					<a href="product.do?command=updateForm&code=${product.code}">
    					상품 수정</a></td>
    				<td align="center">
    					<a href="product.do?command=delete&code=${product.code}">
    					상품 삭제</a></td>
    			</tr>
    		</c:forEach>
    		
    	</table>
    </div>
    
    </body>
    </html>
     
     
    등록된 상품을 상세하게 보기
    else if(command.equals("productView")) ac=new ProductViewAction();
    package com.file.product.controller.action;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.file.product.dao.ProductDao;
    import com.file.product.dto.ProductVO;
    
    public class ProductViewAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		int code=Integer.parseInt(request.getParameter("code"));
    		ProductDao pdao=ProductDao.getInstance();
    		ProductVO pvo=pdao.getProduct(code);
    		
    		request.setAttribute("product", pvo);
    		// productView.jsp로 이동
    		RequestDispatcher rd
    			=request.getRequestDispatcher("product/productView.jsp");
    		rd.forward(request, response);
    	}
    }

     

    Dao에 getProduct() 생성

    public ProductVO getProduct(int code) {
    	ProductVO pvo=null;
    	String sql="select*from bookproduct where code=?";
    	con = Dbman.getConnection();
    	try {
    		pstmt = con.prepareStatement(sql);
    		pstmt.setInt(1, code);
    		rs = pstmt.executeQuery();
    		while(rs.next()) {
    			pvo= new ProductVO();
    			pvo.setCode(  rs.getInt("code") ) ;
    			pvo.setName(  rs.getString("name") ) ;
    			pvo.setPrice(  rs.getInt("price") ) ;
    			pvo.setPictureurl(  rs.getString("pictureurl") ) ;
    			pvo.setDescription(  rs.getString("description") ) ;
    		}
    	} catch (SQLException e) {  e.printStackTrace();
    	} finally {  Dbman.close(  con, pstmt, rs);    }
    	return pvo;
    }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>productView.jsp</title>
    
    <link rel="stylesheet" type="text/css" href="css/product.css">
    
    </head>
    <body>
    
    <div id="wrap" align="center">
    
    	<h1>상품 상세 - 관리자 페이지</h1>
    	
    	<table>
    		<tr>
    			<td width="220">
    <!-- 1행짜리 테이블. 1열 이미지 위치 -->
    				<c:choose>
    					<c:when test="${empty product.pictureurl }">
    						<img src="upload/noname.jpg" width="200">
    					</c:when>
    					<c:otherwise>
    						<img src="upload/${product.pictureurl}"
    							width="200">
    					</c:otherwise>
    				</c:choose>
    			</td>
    			<td>
    <!-- 2열에는 상품 상세가 표시되는 또 하나의 테이블을 위치시킴 -->
    				<table>
    					<tr><th width="80">상 품 명</th>
    						<td>${product.name}</td></tr>
    					<tr><th>가 격</th>
                            <td>${product.price}원</td></tr>
    					<tr><th>설 명</th>
    						<td>
    						<div style="height:220px; width:100%">
    							<pre>${product.description}</pre>
    						</div></td></tr>
    				</table>
    			</td>
    			</tr>
    	</table><br>
    	
    	<input type="button" value="목록" 
    		onclick="location.href='product.do?command=index'">
    	
    </div>
    
    </body>
    </html>
    클릭
     
     
    상품 등록하기
    else if(command.equals("productWriteForm")) ac=
                                      new ProductWriteFormAction();
    package com.file.product.controller.action;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ProductWriteFormAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, 
    			HttpServletResponse response)
    			throws ServletException, IOException {
    
    		RequestDispatcher rd
    	=request.getRequestDispatcher("product/productWriteForm.jsp");
    		rd.forward(request, response);
    	}
    }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>productWriteForm.jsp</title>
    
    <link rel="stylesheet" type="text/css" href="css/product.css">
    
    </head>
    <body>
    
    <div id="wrap" align="center">
    
    	<h1>상품 등록 - 관리자 페이지</h1>
    	
    	<form method="post" enctype="multipart/form-data"
    		action="product.do?command=productWrite">
    		
    		<table>
    			<tr><th>상 품 명</th><td>
    				<input type="text" name="name" size="80"></td></tr>
    			<tr><th>가 격</th><td>
    				<input type="text" name="price">원</td></tr>
    			<tr><th>사 진</th><td>
    				<input type="file" name="pictureurl"></td></tr>
    			<tr><th>설 명</th><td>
    				<textarea cols="80" rows="10" name="description">
    				</textarea></td></tr>
    		</table>
    		
    		<input type="submit" value="등록">
    		<input type="reset" value="다시 작성">
    		<input type="button" value="목록" 
    			onclick="location.href='product.do?command=index'">
    	</form>
    	
    </div>
    
    </body>
    </html>
     
     
    상품 등록 실행하기
    else if(command.equals("productWrite")) ac=new ProductWriteAction();
    package com.file.product.controller.action;
    
    import java.io.IOException;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.file.product.dao.ProductDao;
    import com.file.product.dto.ProductVO;
    import com.oreilly.servlet.MultipartRequest;
    import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
    
    public class ProductWriteAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		
    		// 현재 작성 영역은 서블릿이 아니고 자바 클래스이면
    		// 서블릿에서 전달된 request를 전달 받아 진행되는 곳이므로
    		HttpSession session=request.getSession();
    		// request에서 세션을 추출한 후 
            // session.getServletContext()를 사용함
    		ServletContext context=session.getServletContext();
    		String path=context.getRealPath("upload");
    		
    		ProductVO pvo=new ProductVO();
    		
    		MultipartRequest multi=new MultipartRequest(
    			request, path, 5*1024*1024, "UTF-8",
    			new DefaultFileRenamePolicy()
    		);
    		
    		pvo.setName(multi.getParameter("name"));
    		pvo.setPrice(Integer.parseInt(multi.getParameter("price")));
    		pvo.setDescription(multi.getParameter("description"));
    		pvo.setPictureurl(multi.getFilesystemName("pictureurl"));
    		
    		ProductDao pdao=ProductDao.getInstance();
    		pdao.insertProduct( pvo );
    		response.sendRedirect("product.do?command=index");
    	}
    }
    

     

    Dao에 insertProduct 생성

    public void insertProduct(ProductVO pvo) {
    	String sql = "insert into bookproduct"
    			+ "(code, name, price, pictureurl, description ) "
    			+ " values(bookproduct_seq.nextVal, ?,?,?,?)";
    	con = Dbman.getConnection();
    	try {
    		pstmt = con.prepareStatement(sql);
    		pstmt.setString(1,  pvo.getName() );
    		pstmt.setInt(2,  pvo.getPrice() );
    		pstmt.setString(3,  pvo.getPictureurl() );
    		pstmt.setString(4,  pvo.getDescription() );
    		
    		pstmt.executeUpdate();
    		
    	} catch (SQLException e) {  e.printStackTrace();
    	} finally { Dbman.close(con, pstmt, rs);   }		
    }
     
     
    등록된 상품 수정하기
    else if(command.equals("updateForm")) ac=new UpdateFormAction();
    package com.file.product.controller.action;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.file.product.dao.ProductDao;
    import com.file.product.dto.ProductVO;
    
    public class UpdateFormAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		
    		int code=Integer.parseInt(request.getParameter("code"));
    		
    		// 조회
    		ProductDao pdao=ProductDao.getInstance();
    		ProductVO pvo=pdao.getProduct(code);
    		
    		// 저장
    		request.setAttribute("product", pvo);
    		
    		// 이동
    		RequestDispatcher rd
    		=request.getRequestDispatcher("product/updateForm.jsp");
    		rd.forward(request, response);
    	}
    }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>updateForm.jsp</title>
    
    <link rel="stylesheet" type="text/css" href="css/product.css">
    
    </head>
    <body>
    
    <div id="wrap" align="center">
    
    	<h1>상품 수정 - 관리자 페이지</h1>
    	
    	<form method="post" enctype="multipart/form-data"
    			action="product.do?command=update">
    		<input type="hidden" name="code" 
    			value="${product.code }">
    		<input type="hidden" name="oldPicture" 
    			value="${product.pictureurl }">
    	
    	<table>
    		<tr>
    		<td>
    			<c:choose>
    				<c:when test="${empty product.pictureurl }">
    					<img src="upload/noname.jpg" 
    						width="200" height="300">
    				</c:when>
    				<c:otherwise>
    					<img src="upload/${product.pictureurl}"
    						width="200" height="300">
    				</c:otherwise>
    			</c:choose></td>
    		<td>
    			<table>
    				<tr><th style="width:80px">상품명</th><td>
    					<input type="text" name="name" 
    							value="${product.name}" size="80">
    							</td></tr>
    				<tr><th>가 격</th><td>
    					<input type="text" name="price" 
    							value="${product.price}">원</td></tr>
    				<tr><th>사 진</th><td>
    					<input type="file" name="pictureurl"><br>
    					(주의사항: 이미지를 변경하고자 할 때만 선택)
    					</td></tr>
    				<tr><th>설 명</th><td>
    					<textarea cols="90" rows="10" 
    						name="description">
    					${product.description }</textarea></td></tr>
    			</table>
    		</td>
    		</tr>
    	</table><br>
    	
    	<input type="submit" value="수정" >
    	<input type="reset" value="다시작성">
    	<input type="button" value="목록" 
    		onclick="location.href='product.do?command=index'">
    		
    	</form>
    	
    </div>
    
    </body>
    </html>

     

    상품 수정 실행하기

    else if(command.equals("update")) ac=new UpdateAction();
    package com.file.product.controller.action;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import com.file.product.dao.ProductDao;
    import com.file.product.dto.ProductVO;
    import com.oreilly.servlet.MultipartRequest;
    import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
    
    public class UpdateAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, 
    			HttpServletResponse response)
    			throws ServletException, IOException {
    		
    		HttpSession session=request.getSession();
    		ServletContext context=session.getServletContext();
    		String path=context.getRealPath("upload");
    		String code="";
    		ProductVO pvo=new ProductVO();
    		try {
    			MultipartRequest multi=new MultipartRequest(
    				request, path, 20*1024*1024, "UTF-8",
    				new DefaultFileRenamePolicy()
    			);
    			// 전달된 모든 파라미터를 pvo에 저장해서 수정함
    			code=multi.getParameter("code");
    			pvo.setCode(Integer.parseInt(code));
    			pvo.setName(multi.getParameter("name"));
    			pvo.setPrice(Integer.parseInt(multi.getParameter("price")));
    			pvo.setDescription(multi.getParameter("description"));
    			if(multi.getFilesystemName("pictureurl")==null) 
    				// 수정할 이미지를 선택하지 않았다면
    				pvo.setPictureurl(multi.getParameter("oldPicture"));
    			else
    				// 수정할 이미지를 선택했다면
    				pvo.setPictureurl(multi.getFilesystemName("pictureurl"));
    			ProductDao pdao=ProductDao.getInstance();
    			pdao.updateProduct(pvo);
    		} catch(Exception e) {
    			System.out.println("파일업로드 실패: "+e);
    		}
    		System.out.println(code); 
    		String url="product.do?command=productView&code="
    							+code;
    		RequestDispatcher rd=request.getRequestDispatcher(url);
    		rd.forward(request, response);
    	}
    }

     

    Dao에 updateProduct 생성

    public void updateProduct(ProductVO pvo) {
    	String sql = "update bookproduct set "
    			+ "name=?, price=?, pictureurl=?, description=? "
    			+ "where code=?";
    	con = Dbman.getConnection();
    	try {
    		pstmt = con.prepareStatement(sql);
    		pstmt.setString(1,  pvo.getName() );
    		pstmt.setInt(2,  pvo.getPrice() );
    		pstmt.setString(3,  pvo.getPictureurl() );
    		pstmt.setString(4,  pvo.getDescription() );
    		pstmt.setInt(5,  pvo.getCode() );
    		
    		pstmt.executeUpdate();
    	} catch (SQLException e) { 	e.printStackTrace();
    	} finally {	Dbman.close(con, pstmt, rs); }
    }
     
     
    등록된 상품 삭제하기
    else if(command.equals("delete")) ac=new DeleteAction();
    package com.file.product.controller.action;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.file.product.dao.ProductDao;
    
    
    public class DeleteAction implements Action {
    
    	@Override
    	public void execute(HttpServletRequest request, 
    			HttpServletResponse response) 
    			throws ServletException, IOException {
    		int code=Integer.parseInt( request.getParameter("code")); 
    		
    		ProductDao pdao = ProductDao.getInstance();
    		pdao.deleteProduct( code );
    		
    		String url = "product.do?command=index";
    		
    		RequestDispatcher dp = request.getRequestDispatcher(url);
    		dp.forward(request, response);
    	}
    }

    Dao에 deleteProduct 생성

    public void deleteProduct(int code) {
    	String sql = "delete from bookproduct where code=?";
    	con = Dbman.getConnection();
    	try {
    		pstmt = con.prepareStatement(sql);
    		pstmt.setInt(1, code);
    		pstmt.executeUpdate();
    		
    	} catch (SQLException e) { e.printStackTrace();
    	} finally { Dbman.close(con, pstmt, rs);  }	
    }
     

    댓글

Designed by Tistory.