본문 바로가기
CLASS/SERVLET

#7-3 / 첨부파일 기능 + database 저장

by eungSe__ 2024. 6. 19.

https://dev-eunse.tistory.com/155 예제의 html파일에 review 받는 input 추가

리뷰내용 : <input type="text" name="mreview">

 

 

🔽 

create table filelist(
fidx int(7) unsigned not null auto_increment,
f_img text null,
f_text varchar(200) not null,
f_indate timestamp not null default current_timestamp,
primary key(fidx)
);

 

🔽 

⚡ 리뷰등록 fileok2.java
@MultipartConfig (
	fileSizeThreshold = 1024*1024*2,
	maxFileSize = 1024*1024*10,
	maxRequestSize = 1024*1024*100
)
public class fileok2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	dbconfig db = new dbconfig();
	Connection con = null;
	Statement st = null; //이게 있어야 sql 작동시킬수 잇음
	PrintWriter pw = null;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String mreview = request.getParameter("mreview");
		Part mfile = request.getPart("mfile");
		String filename = mfile.getSubmittedFileName(); //파일명
		long filesize = mfile.getSize();
		try {
			this.con = this.db.info(); //database 연결
			this.pw = response.getWriter();
			String filesave = ""; //db에 저장되는 경로
			
			if(filename == "" || filesize <= 0) { //첨부파일이 없을 경우(리뷰글만)
				filesave = "";
			}else { //첨부파일이 있을 경우
				String url = request.getServletContext().getRealPath("/upload/");
				mfile.write(url+filename);
				
				filesave = "./upload/"+filename;
			}
			
			String sql = "insert into filelist(fidx,f_img,f_text,f_indate) "
					+ "values('0','"+ filesave +"','"+ mreview +"',now())";
			
			this.st = this.con.createStatement(); //sql 문법 실행시키는 라이브러리
			int result = this.st.executeUpdate(sql); //실행 및 결과값을 return(숫자로 return)
			
			if(result>0) { //정상 query 작동 1
				this.pw.write("<script>"
						+ "alert('리뷰등록이 완료되었습니다');"
						+ "location.href='./upload_list.do';"
						+ "</script>");
			}else {
				this.pw.write("<script>"
						+ "alert('올바른 파일이 아닙니다.');"
						+ "history.go(-1)"
						+ "</script>");
			}
			
		}catch(Exception e) {
			System.out.println("database 접속 오류 및 웹디렉토리 오류 발생");
		}finally {
			try {
				this.st.close();
				this.pw.close();
				this.con.close();
			}catch(Exception e) {
				System.out.println("database 접속해제 실패");
			}
		}
	}
}

 

 

🔽 

⚡ 리뷰내용 출력 및 이미지 data 로드
public class upload_list extends HttpServlet {
	private static final long serialVersionUID = 1L;
	dbconfig db = new dbconfig();
	Connection con = null;
	
	Statement st = null;
	ResultSet rs = null;
	
	RequestDispatcher rd = null; //외부에 있는 jsp파일을 로드할 때 사용
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			this.con = this.db.info();
			
			//제일 마지막에 입력된 하나의 data를 가지고오겟다
			String sql = "select * from filelist order by fidx desc limit 0,1"; 
			this.st = this.con.createStatement();
			this.rs = this.st.executeQuery(sql); //ResultSet으로 받음
			this.rs.next();
			
			int fidx = this.rs.getInt(1);
			String f_img = this.rs.getString("f_img");
			String f_text = this.rs.getString("f_text");
			Date f_indate = this.rs.getDate("f_indate");
			
			//sql에 대한 데이터를 배열에 저장
			ArrayList<Object> list = new ArrayList<Object>();
			list.add(fidx);
			list.add(f_img);
			list.add(f_text);
			list.add(f_indate);
			
			request.setAttribute("list", list); //배열 전체를 jsp로 전달
		}catch(Exception e) {
			System.out.println("db 오류!!");
		}finally {
			try {
				this.rs.close();
				this.st.close();
				this.con.close();
			}catch(Exception e2) {
				System.out.println("db 오류!!");
			}
		}
		
		//getRequestDispatcher (view 역할) : 무조건 맨 아래
		this.rd = request.getRequestDispatcher("./upload_list.jsp");
		this.rd.forward(request, response);
	}
}

 

🔽 

⚡ do에서 보낸 파일 => jsp로 받기 : upload_list.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
//do에서 만들어진 배열을 받아서 출력

//do에서 사용한 배열과 동일한 자료형으로 배열 생성
ArrayList<Object> list = new ArrayList<Object>(); 
list = (ArrayList)request.getAttribute("list"); //do에서 보낸 attribute를 받음
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    리뷰내용 : <%=list.get(2)%><br>
    상품이미지 : <img src="../<%=list.get(1)%>" width=100 height=100><br>
    등록일 : <%=list.get(3)%><br>
</body>
</html>

 

jsp 출력 완료

 

'CLASS > SERVLET' 카테고리의 다른 글

#8-2 / 게시판 insert 모듈화...  (0) 2024.06.21
#8-1 / 게시판  (0) 2024.06.21
#7-2 / 첨부파일 기능 - java + io  (0) 2024.06.19
#7-1 / 회원 가입 후 로그인,로그아웃  (0) 2024.06.19
#6-3 / storage  (0) 2024.06.18