ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 게시판 만들기 - 10. 이미지 업로드 구현하기
    JAVA/웹 프로그래밍 - JSP 2020. 12. 2. 19:27

    designatedroom87.tistory.com/331?category=901206

     

    게시판 만들기 - 9. 검색 리스트 구현하기

    아래의 내용에 이어서 계속 구현할 것이다. designatedroom87.tistory.com/329 게시판 만들기 - 8. 글 수정 & 글 삭제 구현하기 로그인을 한 상태에서 게시글을 하나 선택했을 시에, 아래와 같이 나타난다.

    designatedroom87.tistory.com

     

    WebContent폴더에 upload.jsp파일과 imgup.jsp파일을 만들자.

    그리고, 아래의 파일을 다운로드 하자.

    cos.jar
    0.05MB

    아래의 파일을 CTRL + C 해서 WebContent/WEB-INF/lib폴더에 CTRL + V로 붙여넣기를 하자.

    아래와 같이 파일이 추가 된다.

    현재 프로젝트 폴더의 하위에 Web App Libraries를 자세히 보자.

    위의 com.oreilly.servlet 패키지와 com.oreilly.servlet.multipart 패키지가 보일 것이다.

    이 부분의 내용을 사용할 것이다. 즉, 임포트를 할 것이다.

    upload.jsp

    더보기
    <%@ 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>
    	<!-- form의 형태로 전송 
    		용량이 큰 파일인 경우에 enctype="multipart/form-data" 부분이 반드시 필요하다.
    	-->
    	<form method="post" action="imgup.jsp" enctype="multipart/form-data">
    		<input type="file" name="filename" size=40>
    		<input type="submit" value="업로드">
    	</form>
    
    </body>
    </html>

     

    imgup.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <!-- import하자. -->
        <%@ page import="com.oreilly.servlet.*" %>
        <%@ page import="com.oreilly.servlet.multipart.*" %>
        <%@ page import="java.util.*" %>
        
    <%
    request.setCharacterEncoding("UTF-8");	//	한글이 깨질 수 있으므로 추가
    
    //		데이터를 저장할 경로 정보 확인
    //	real path를 알아내기 위해 선언
    ServletContext context = getServletContext();
    String realPath = context.getRealPath("img");
    //	String realPath = context.getRealPath("");
    System.out.println(realPath);
    
    //		파일을 업로드 할 때, 필요한 정보
    String filename = "";			//	파일 이름
    int maxSize = 1024 * 1024 * 5;	//	5MegaByte크기를 최대 사이즈로 설정
    String fullfilename = "";		//	전체 경로 포함 파일 이름
    MultipartRequest multi = null;
    
    try{
    	multi = new MultipartRequest(request,realPath,
    			maxSize,"UTF-8",
    			new DefaultFileRenamePolicy()	//	제약 사항(파일의 이름이 중복 시, 이름을 재정의 하거나) 등을 처리할 때, 필요
    			);
    //	Form에서 전송된 파일의 정보를 가져오는 작업
    Enumeration<?> files = multi.getFileNames();	//	파일이 여러 개 넘어올 수 있다.
    String imsifile = (String)files.nextElement();
    filename = multi.getFilesystemName(imsifile);
    
    System.out.println(filename);
    
    //	realPath + filename 결합하기
    fullfilename = realPath + "\\" +filename;
    System.out.println(fullfilename);
    
    }catch(Exception e){}
    %>    
    <%=filename%>
    <%=multi.getParameter("filename")%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    	<!-- 이미지를 선택하면, 전화 서비스가 가능해진다. -->
    	<a href="tel:010-1234-5678">
    		<img src="/img/<%=filename%>" width=300 height=200></img>
    	</a>
    </body>
    </html>

     

    upload.jsp파일을 실행하고 이미지 파일을 선택하고 업로드를 하면
    경로에 업로드가 되어있음을 볼 수  있다.

    그리고 자바 콘솔 창의 경로를 복사해서 웹 페이지에 적어보면 다음과 같다.

    그리고 윈도우 탐색기에서 주소를 적어보면 다음과 같다.

     

    그리고, 여러 이미지 파일들을 업로드해보자.

    multiupload.jsp 파일과 multiimgup.jsp 파일을 만든다.

     

    multiupload.jsp

    더보기
    <%@ 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>
    	<!-- form의 형태로 전송 
    		용량이 큰 파일인 경우에 enctype="multipart/form-data" 부분이 반드시 필요하다.
    	-->
    	<form method="post" action="multiimgup.jsp" enctype="multipart/form-data">
    		파일1 : <input type="file" name="filename1" size=40><p>
    		파일2 : <input type="file" name="filename2" size=40><p>
    		파일3 : <input type="file" name="filename3" size=40><p>
    		<input type="submit" value="업로드">
    	</form>
    
    </body>
    </html>

     

     

    multiimgup.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
        <!-- import하자. -->
        <%@ page import="com.oreilly.servlet.*" %>
        <%@ page import="com.oreilly.servlet.multipart.*" %>
        <%@ page import="java.util.*" %>
        
    <%
    request.setCharacterEncoding("UTF-8");	//	한글이 깨질 수 있으므로 추가
    
    //		데이터를 저장할 경로 정보 확인
    //	real path를 알아내기 위해 선언
    ServletContext context = getServletContext();
    String realPath = context.getRealPath("img");
    //	String realPath = context.getRealPath("");
    System.out.println(realPath);
    
    //		파일을 업로드 할 때, 필요한 정보
    String filename1 = "";			//	파일 이름
    String filename2 = "";			//	파일 이름
    String filename3 = "";			//	파일 이름
    
    int maxSize = 1024 * 1024 * 5;	//	5MegaByte크기를 최대 사이즈로 설정
    String fullfilename = "";		//	전체 경로 포함 파일 이름
    MultipartRequest multi;
    try{
    	multi = new MultipartRequest(request,realPath,
    			maxSize,"UTF-8",
    			new DefaultFileRenamePolicy()	//	제약 사항(파일의 이름이 중복 시, 이름을 재정의 하거나) 등을 처리할 때, 필요
    			);
    //	Form에서 전송된 파일의 정보를 가져오는 작업
    Enumeration<?> files = multi.getFileNames();	//	파일이 여러 개 넘어올 수 있다.
    filename1 = multi.getFilesystemName((String)files.nextElement());
    filename2 = multi.getFilesystemName((String)files.nextElement());
    filename3 = multi.getFilesystemName((String)files.nextElement());
    
    
    
    //	realPath + filename 결합하기
    fullfilename = realPath + "\\" +filename1;
    System.out.println(fullfilename);
    
    }catch(Exception e){}
    %>    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    	<img src="/img/<%=filename1%>" width=300 height=200></img>
    	<img src="/img/<%=filename2%>" width=300 height=200></img>
    	<img src="/img/<%=filename3%>" width=300 height=200></img>
    </body>
    </html>

     

    multiupload.jsp파일을 실행하자.

    웹 페이지에서의 경로는 다음과 같이 파일이 업로드 된다.

    아래는 윈도우 탐색기에서의 파일의 업로드 상태이다.

     

     

    이번에는 전화번호 목록이 뜨는 것처럼, 구현을 해보자.

    아래의 displayTest.html을 보자.

    displayTest.html은 WebContent폴더에 만든다.

    그리고 실행해보자.

    displayTest.html

    더보기
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Display Test</title>
    <style>
    	.out{
    		width:100%;
    		text-align:center;
    		border:1px black solid;
    		margin:10px;
    		padding:20px;
    	}
    	.in{
    		display:inline-block;
    		width:50%;
    		border:1px red solid;
    		height:100px;			//	높이는 픽셀 단위
    		vertical-align:middle;
    		line-height:100px;		//	라인에서의 높이를 의미
    	}
    </style>
    </head>
    <body>
    <div class="out">
    	<div class="in">
    		aaaaa
    	</div>
    </div>
    </body>
    </html>

     

    전화번호 이미지를 인터넷에서 다운받아 WebContent/img 폴더에 저장하고 이름은 tel.png 라 하자.

    telform.jsp 파일을 WebContent폴더에 만들자.

    telform.jsp는 입력 폼이다.

    이 입력폼의 데이터를 넘겨받아 처리하는 부분이 tel_proc.jsp에서 처리를 한다.

    tel_proc.jsp도 WebContent폴더에 만들자.

    telform.jsp

    더보기
    <%@ 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>
    
    <!-- enctype는 임호화 형식으로 받는 쪽에서 request.getParameter로 받을 수 없다. -->
    <form method="post" action="tel_proc.jsp" enctype="multipart/form-data">
    사진: <input type="file" name="filename" size=40><p>
    이름: <input type=text name=name><p>
    전화번호: <input type=tel name=tel><p>
    <input type="submit" value="업로드">
    </form>
    
    </body>
    </html>

     

    telform.jsp를 실행해보자.

    tel_proc.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ page import="com.oreilly.servlet.*" %>
    <%@ page import="com.oreilly.servlet.multipart.*" %>
    <%@ page import="java.util.*" %>
    
    <%
    //	데이터를 저장할 경로 정보 확인
    request.setCharacterEncoding("UTF-8");
    ServletContext context=getServletContext();
    String realPath=context.getRealPath("img");
    System.out.println(realPath);
    String name=null;
    String tel=null;
    
    //	파일을 업로드 할 때 필요한 정보
    String filename=""; 	//	파일이름
    int maxSize=1024*1024*5;
    MultipartRequest multi=null;
    String fullfilename="";	//	전체 경로포함 파일이름 
    
    try{
    	       multi=new MultipartRequest(
    			request,
    			realPath,
    			maxSize,
    			"UTF-8",
    			new DefaultFileRenamePolicy()
    			);
    	        
    	//	폼에서 전송된 파일의 정보를 가져오는 작업
    	Enumeration<?> files=multi.getFileNames();
    	String imsifile=(String)files.nextElement();
    	filename=multi.getFilesystemName(imsifile);
    	System.out.println(filename);
    	
    	//	realpath+filename결합하기
    	fullfilename=realPath+"\\"+filename;
    	System.out.println(fullfilename);
    	
    	//	parameter 전송 (request.getParameter가 아닌 아래의 함수를 쓴다.)
    	name=multi.getParameter("name");
       	tel=multi.getParameter("tel");
       	System.out.println("name"+name);
       	System.out.println("tel"+name);
    
    }catch(Exception e){}
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .box {
        width: 100px;
        height: 100px; 
        border-radius: 70%;
        overflow: hidden;
    }
    .profile {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    </style>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    <a href="tel:010-0000-0000">
    	<div class="box" style="background:#BDBDBD;">
    	    <img class="profile" src="/img/<%=filename%>"></img>
    	</div>
    </a>
    <!-- 이름과 전화번호를 출력 -->
    <%=name%>
    <%=tel%>
    <div class="box" style="background:#BDBDBD;">
     <img class="profile" src="/img/tel.png"></img>
     </div>
    </body>
    </html>

     

    tel_proc.jsp를 다음과 같이 수정해보자.

    tel_proc.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ page import="com.oreilly.servlet.*" %>
    <%@ page import="com.oreilly.servlet.multipart.*" %>
    <%@ page import="java.util.*" %>
    
    <%
    //	데이터를 저장할 경로 정보 확인
    request.setCharacterEncoding("UTF-8");
    ServletContext context=getServletContext();
    String realPath=context.getRealPath("img");
    System.out.println(realPath);
    String name=null;
    String tel=null;
    
    //	파일을 업로드 할 때 필요한 정보
    String filename=""; 	//	파일이름
    int maxSize=1024*1024*5;
    MultipartRequest multi=null;
    String fullfilename="";	//	전체 경로포함 파일이름 
    
    try{
    	       multi=new MultipartRequest(
    			request,
    			realPath,
    			maxSize,
    			"UTF-8",
    			new DefaultFileRenamePolicy()
    			);
    	        
    	//	폼에서 전송된 파일의 정보를 가져오는 작업
    	Enumeration<?> files=multi.getFileNames();
    	String imsifile=(String)files.nextElement();
    	filename=multi.getFilesystemName(imsifile);
    	System.out.println(filename);
    	
    	//	realpath+filename결합하기
    	fullfilename=realPath+"\\"+filename;
    	System.out.println(fullfilename);
    	
    	//	parameter 전송 (request.getParameter가 아닌 아래의 함수를 쓴다.)
    	name=multi.getParameter("name");
       	tel=multi.getParameter("tel");
       	System.out.println("name"+name);
       	System.out.println("tel"+name);
    
    }catch(Exception e){}
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .box {
        width: 100px;
        height: 100px; 
        border-radius: 70%;
        overflow: hidden;
    }
    .profile {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    </style>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    <a href="tel:010-0000-0000" style="border:1px red solid;">
    	<div class="box" style="border:1px green solid;">
    	    <img class="profile" src="/img/<%=filename%>"></img>
    	</div>
    
    	<!-- 이름과 전화번호를 출력 -->
    	<div style="border:1px black solid;">
    	<%=name%>
    	<%=tel%>
    	</div>
    
    	<div class="box" style="border:1px blue solid;">
    	 <img class="profile" src="/img/tel.png"></img>
    	 </div>
     </a>
     
    </body>
    </html>

     

    아래는 최종 내용이다.

    tel_proc.jsp

    더보기
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ page import="com.oreilly.servlet.*" %>
    <%@ page import="com.oreilly.servlet.multipart.*" %>
    <%@ page import="java.util.*" %>
    
    <%
    //	데이터를 저장할 경로 정보 확인
    request.setCharacterEncoding("UTF-8");
    ServletContext context=getServletContext();
    String realPath=context.getRealPath("img");
    System.out.println(realPath);
    String name=null;
    String tel=null;
    
    //	파일을 업로드 할 때 필요한 정보
    String filename=""; 	//	파일이름
    int maxSize=1024*1024*5;
    MultipartRequest multi=null;
    String fullfilename="";	//	전체 경로포함 파일이름 
    
    try{
    	       multi=new MultipartRequest(
    			request,
    			realPath,
    			maxSize,
    			"UTF-8",
    			new DefaultFileRenamePolicy()
    			);
    	        
    	//	폼에서 전송된 파일의 정보를 가져오는 작업
    	Enumeration<?> files=multi.getFileNames();
    	String imsifile=(String)files.nextElement();
    	filename=multi.getFilesystemName(imsifile);
    	System.out.println(filename);
    	
    	//	realpath+filename결합하기
    	fullfilename=realPath+"\\"+filename;
    	System.out.println(fullfilename);
    	
    	//	parameter 전송 (request.getParameter가 아닌 아래의 함수를 쓴다.)
    	name=multi.getParameter("name");
       	tel=multi.getParameter("tel");
       	System.out.println("name"+name);
       	System.out.println("tel"+name);
    
    }catch(Exception e){}
    %>
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .box {
        width: 100px;
        height: 100px; 
        border-radius: 70%;
        overflow: hidden;
    }
    .profile {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    </style>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    
    <%for (int i = 0; i < 10; i++){ %>
    <a href="tel:010-0000-0000" style="border:1px red solid; display:block; height:100%; vertical-align:middle ">
    	<div class="box" style="border:1px green solid; display:inline-block;">
    	    <img class="profile" src="/img/<%=filename%>"></img>
    	</div>
    
    	<!-- 이름과 전화번호를 출력 -->
    	<div style="border:1px black solid; display:inline-block; vertical-align:top; height:100px; line-height:100px; ">
    	<%=name%>
    	<%=tel%>
    	</div>
    
    	<div class="box" style="border:1px blue solid; display:inline-block;">
    	 <img class="profile" src="/img/tel.png"></img>
    	 </div>
     </a>
     <%} %>
     
    <!-- 아래의 내용은 지워도 상관 없다. ( a태그의 내용) -->
     <a href="tel:010-0000-0000" style="border:1px red solid; display:block; ">
    	<div class="box" style="border:1px green solid; display:inline-block;">
    	    <img class="profile" src="/img/<%=filename%>"></img>
    	</div>
    
    	<!-- 이름과 전화번호를 출력 -->
    	<div style="border:1px black solid; display:inline-block;">
    	<%=name%>
    	<%=tel%>
    	</div>
    
    	<div class="box" style="border:1px blue solid; display:inline-block;">
    	 <img class="profile" src="/img/tel.png"></img>
    	 </div>
     </a>
     
    </body>
    </html>

     

     

     

    그리고 책을 예로 들자. 책에는 책 제목, 책의 저자, 가격, 책 표지의 정보가 있다.
    즉, 대상물에 사진이 필요한 경우가 많다.
    WebContent에 book 폴더를 하나 만든다.

    bookform.jsp 파일을 하나 만들자.

    그리고 이 폴더에 파일을 하나 만들어서 이름을 book이라 짓자.

    이 파일의 내용에는 프로그램 소스 코드를 사용하는 것이 아닌, SQL명령문을 적는 용도로 만든 것이다.

    아래의 파일 내용을 이용해서 DB에 테이블을 만들고 정보를 입력하자.

    아래의 4개의 SQL문을 차례로 실행하자.

    create table book( 
    num int, 
    title varchar(30), 
    author varchar(30), 
    price int, 
    filename varchar(50) 
    ); 

    create sequence book_num_seq start with 1 increment by 1; 

    insert into book values(book_num_seq.nextval,'상실의 시대','미상',10000,'a.png'); 

    select * from book; 

     

    book 파일의 내용

    더보기

    create table book(
    num int,
    title varchar(30),
    author varchar(30),
    price int,
    filename varchar(50)
    );

    drop table book;

    create sequence book_num_seq start with 1 increment by 1;

    insert into book values(book_num_seq.nextval,'상실의 시대','미상',10000,'a.png');

    select * from book;

    update book set price=15000 where title='JSP';

    delete from book where title = 'JSP';

     

    bookform.jsp파일은 입력 폼의 역할을 하며, 이 입력 폼에서 입력 데이터(모델)를 받아서 DB에 접속한다.

    그러기 위해서는 입력 폼의 내용을 가지고 서블릿(컨트롤러)로 이동해야 한다.

    컨트롤러는 당연히 존재해야 하며, book.controller패키지에 만들고 이름을 Controller라 한다.

    이전에 구현한 board의 컨트롤러, member의 컨트롤러들은 모두 그 내용이 너무 많았다.

    여기서는 Controller의 기능을 줄이기로 하자.

    Controller에서는 url에 대한 분석을 하고, 해당 내용은 BookService로 보내 BookService에서 처리를 하도록 하자.

    기존의 내용은 service로 넘기자.

    bookform.jsp

    더보기
    <%@ 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>
    
    <!-- enctype는 임호화 형식으로 받는 쪽에서 request.getParameter로 받을 수 없다. -->
    <!-- <form method="post" action="/book/insert" enctype="multipart/form-data"> -->
    <form method="post" action="/book/insert">
    책제목 :<input type=text name=title><p>
    글쓴이 :<input type=tel name=author><p>
    가격 :<input type=text name=price><p>
    책표지 :<input type="file" name="filename" size=40><p>
    <input type="submit" value="업로드">
    </form>
    
    </body>
    </html>

     

     

    Controller.java

    더보기
    package book.controller;
    
    import java.io.IOException;
    import java.util.Enumeration;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletConfig;
    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;
    
    import book.service.BookService;
    
    @WebServlet("/book/insert")
    public class Controller extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
    	public void init(ServletConfig config) 
    			throws ServletException {}
    
    	protected void service(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException 
    	{
    		BookService service = BookService.getInstance();
    		
    		service.insert(request,response);
    		
    		RequestDispatcher dispatcher = 
    				request.getRequestDispatcher("/WEB-INF/home/index.jsp");
    		
    		//	페이지로 밀어주는 작업
    		dispatcher.forward(request, response);
    	}
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {}
    }

     

    book.model 패키지에 Book.java을 만든다. 이는 모델이다.

    Book.java

    더보기
    package book.model;
    
    public class Book 
    {
    	private int num;
    	private String title;
    	private String author;
    	private int price;
    	private String filename;
    	
    	public Book() {}
    	
    	public Book(int num, String title, String author, 
    			int price, String filename) 
    	{
    		this.num = num;
    		this.title = title;
    		this.author = author;
    		this.price = price;
    		this.filename = filename;
    	}
    
    	public int getNum() {return num;}
    	public void setNum(int num) {this.num = num;}
    	public String getTitle() {return title;}
    	public void setTitle(String title) {this.title = title;}
    	public String getAuthor() {return author;}
    	public void setAuthor(String author) {this.author = author;}
    	public int getPrice() {return price;}
    	public void setPrice(int price) {this.price = price;}
    	public String getFilename() {return filename;}
    	public void setFilename(String filename) {this.filename = filename;}
    }

     

     

     

    book.dao패키지에 BookDAO.java를 만든다. 이는 DB 접속 객체이다.

    BookDAO.java

    더보기
    package book.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import book.model.Book;
    
    public class BookDAO 
    {
    	private static BookDAO dao = new BookDAO();
    	
    	private BookDAO() {}
    	public static BookDAO getInstance() {return dao;}
    	
    	public Connection connect()
    	{
    		Connection conn = null;
    		
    		try {
    		Class.forName("oracle.jdbc.driver.OracleDriver");
    		conn=DriverManager.getConnection(
    		"jdbc:oracle:thin:@localhost:1521:xe","hr","1234");
    
    		if(conn==null) {System.out.println("DB접속에 실패");}
    		System.out.println("DB접속 성공");
    		
    		}catch(Exception e) {}
    		
    		return conn;
    	}
    	
    	public void close(Connection conn, PreparedStatement pstmt, ResultSet rs)
    	{
    		if (rs != null) 
    		{
    			try 
    			{
    				rs.close();
    			}
    			catch (SQLException e) {e.printStackTrace();}
    		}
    		this.close(conn,pstmt);
    	}
    	
    	public void close(Connection conn, PreparedStatement pstmt)
    	{
    		try {
    		pstmt.close();
    		conn.close();
    		}
    		catch (SQLException e) {e.printStackTrace();}
    	}
    	
    	//	DB에 책 정보를 저장
    	public int insert(Book book) 
    	{
    		String sql = null;
    		Connection conn = null;
    		PreparedStatement pstmt = null;
    		int result = 0;
    		
    		try 
    		{
    			System.out.printf("%s %s %d %s\n", book.getTitle(),
    					book.getAuthor(),book.getPrice(),book.getFilename());
    			
    			conn = this.connect();
    			conn.setAutoCommit(false);	//	DB 트랜잭션의 시작
    			
    			sql="insert into book values " + "(book_num_seq.nextval," + "?,?,?,?)";
    			
    			pstmt=conn.prepareStatement(sql);//위의 sql문을 처리하기 위해 객체 생성
    			
    			pstmt.setString(1, book.getTitle());
    			pstmt.setString(2, book.getAuthor());
    			pstmt.setInt(3, book.getPrice());
    			pstmt.setString(4, book.getFilename());
    			
    			result = pstmt.executeUpdate();
    			conn.commit();
    			
    			if (result > 0)	{
    				System.out.println("책 입력 성공");
    				conn.commit();
    			}
    			else{
    				System.out.println("책 입력 실패");
    				conn.rollback();
    			}
    			this.close(conn, pstmt);
    		}
    		catch(Exception e) 
    		{ 
    			try {conn.rollback();}
    			catch (SQLException e1) {e1.printStackTrace();}
    		}
    		return result;
    	}
    }

     

     

    book.service패키지에 BookService.java 파일을 만든다.

    아래의 BookService.java는 그대로 실행하면 되지 않는다 밑에 수정본이 있으니

    왜 안되는지 생각을 해보자.

    BookService.java

    더보기
    package book.service;
    
    import java.io.UnsupportedEncodingException;
    import java.util.Enumeration;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.oreilly.servlet.MultipartRequest;
    import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
    
    import book.dao.BookDAO;
    import book.model.Book;
    
    public class BookService 
    {	
    	private static BookService service = new BookService();
    	private BookDAO dao = BookDAO.getInstance();
    	
    	private BookService(){}
    	
    	public static BookService getInstance() {	return service; }
    	
    	public int insert(HttpServletRequest request, HttpServletResponse response) 
    	{
    		//	데이터를 저장할 경로 정보 확인
    		try {request.setCharacterEncoding("UTF-8");} 
    		catch (UnsupportedEncodingException e1) {e1.printStackTrace();}
    		
    		ServletContext context = request.getServletContext();
    		String realPath = context.getRealPath("img");
    		System.out.println(realPath);
    		
    		String title = null;
    		String author = null;
    		int price = 0;
    		String filename = ""; 			//	파일이름
    		
    		int result = 0;
    		int maxSize = 1024*1024*5;
    		MultipartRequest multi = null;
    		String fullfilename = "";		//	전체 경로포함 파일이름 
    
    		try{
    		       multi = new MultipartRequest(
    		    		   request,
    		    		   realPath,
    		    		   maxSize,
    		    		   "UTF-8",
    		    		   new DefaultFileRenamePolicy()
    				);
    			        
    			//	폼에서 전송된 파일의 정보를 가져오는 작업
    			Enumeration<?> files = multi.getFileNames();
    			String imsifile = (String)files.nextElement();
    			filename = multi.getFilesystemName(imsifile);
    			System.out.println(filename);
    			
    			//	realpath+filename결합하기
    			fullfilename=realPath+"\\"+filename;
    			System.out.println(fullfilename);
    			
    			//	parameter 전송 (request.getParameter가 아닌 아래의 함수를 쓴다.)
    			title =multi.getParameter("title");
    		   	author =multi.getParameter("author");
    		   	price = Integer.parseInt(multi.getParameter("price"));
    		   	
    		   	System.out.printf("%s %s %d %s\n", title,author,price,filename);
    		   	
    		   	Book book = new Book();
    		   	
    		   	book.setTitle(title);
    		   	book.setAuthor(author);
    		   	book.setPrice(price);
    		   	book.setFilename(filename);
    		   	
    		   	BookDAO dao = BookDAO.getInstance();
    		   	
    		   	result = dao.insert(book);
    		   	
    		}catch(Exception e){}
    		
    		return result;
    	}
    }

     

    위의 내용을 입력하면 동작하지 않는 이유는 bookform.jsp의 form 태그에 그 이유가 있다.

    위는 multipart가 아닌 일반 action태그를 이용하므로

    BookService에서 MultipartRequest가 아닌 HttpServletRequest로 데이터를 받으면 된다. 

    BookService.java 수정본

    더보기
    package book.service;
    
    import java.io.UnsupportedEncodingException;
    import java.util.Enumeration;
    
    import javax.servlet.ServletContext;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.oreilly.servlet.MultipartRequest;
    import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
    
    import book.dao.BookDAO;
    import book.model.Book;
    
    public class BookService 
    {	
    	private static BookService service = new BookService();
    	private BookDAO dao = BookDAO.getInstance();
    	
    	private BookService(){}
    	
    	public static BookService getInstance() {	return service; }
    	
    	public int insert(HttpServletRequest request, HttpServletResponse response) 
    	{
    		//	데이터를 저장할 경로 정보 확인
    		try {request.setCharacterEncoding("UTF-8");} 
    		catch (UnsupportedEncodingException e1) {e1.printStackTrace();}
    		
    		ServletContext context = request.getServletContext();
    		String realPath = context.getRealPath("img");
    		System.out.println("realPath : " +realPath);
    		
    		String title = null;
    		String author = null;
    		int price = 0;
    		String filename = ""; 			//	파일이름
    		
    		int result = 0;
    		int maxSize = 1024*1024*5;
    		MultipartRequest multi = null;
    		String fullfilename = "";		//	전체 경로포함 파일이름 
    		
    		title =request.getParameter("title");
    	   	author =request.getParameter("author");
    	   	price = Integer.parseInt(request.getParameter("price"));
    	   	filename = request.getParameter("filename");
    	   	
    	   	System.out.printf("%s %s %d %s\n", title,author,price,filename);
    	   	
    	   	Book book = new Book();
    	   	
    	   	book.setTitle(title);
    	   	book.setAuthor(author);
    	   	book.setPrice(price);
    	   	book.setFilename(filename);
    	   	
    	   	BookDAO dao = BookDAO.getInstance();
    	   	
    	   	result = dao.insert(book);
    	   	
    		/*
    		try{
    		       multi = new MultipartRequest(
    		    		   request,
    		    		   realPath,
    		    		   maxSize,
    		    		   "UTF-8",
    		    		   new DefaultFileRenamePolicy()
    				);
    			        
    			//	폼에서 전송된 파일의 정보를 가져오는 작업
    			Enumeration<?> files = multi.getFileNames();
    			String imsifile = (String)files.nextElement();
    			filename = multi.getFilesystemName(imsifile);
    			System.out.println(filename);
    			
    			//	realpath+filename결합하기
    			fullfilename=realPath+"\\"+filename;
    			System.out.println("fullfilename : " +fullfilename);
    			
    			//	parameter 전송 (request.getParameter가 아닌 아래의 함수를 쓴다.)
    			title =multi.getParameter("title");
    		   	author =multi.getParameter("author");
    		   	price = Integer.parseInt(multi.getParameter("price"));
    		   	
    		   	System.out.printf("%s %s %d %s\n", title,author,price,filename);
    		   	
    		   	Book book = new Book();
    		   	
    		   	book.setTitle(title);
    		   	book.setAuthor(author);
    		   	book.setPrice(price);
    		   	book.setFilename(filename);
    		   	
    		   	BookDAO dao = BookDAO.getInstance();
    		   	
    		   	result = dao.insert(book);
    		   	
    		}catch(Exception e){}
    		*/
    		return result;
    	}
    }

     

     

    bookform.jsp 파일을 실행하자.

    그리고 DB에 접속해서

    select * from book 

    명령어를 입력해서 데이터가 잘 저장 되었는지 확인해보자.

     

     

    아래의 내용은 부록과 같은 느낌이다.

    designatedroom87.tistory.com/333

     

    게시판 만들기 - 11. connectionPool 구현하기

    코드와 데이터를 분리한다는 의미는 데이터는 데이터 대로 코드는 코드 따로 분리 해서 명령으로 이들을 불러온다. 나중에 connectPool을 구현할 때, xml문서를 활용한다. 여기서의 xml은 WebConten

    designatedroom87.tistory.com

     

    댓글

Designed by Tistory.