본문 바로가기
Kosta DevOps 과정 280기/Java

세션을 이용한 상태유지

by 롯슈83 2024. 7. 16.


session : 상태를 유지하는 방법으로써 브라우저를 닫기 전까지 사용자의 상태를 서버에 기록하는 방식
상태 유지하기 위하여 JSP 내장 객체 session 을 이용한다.

  • request.setAttribute(속성명, 값); ==> 다음 연결된 문서 까지만 상태 유지
  • session.setAttribute(속성명, 값); ==> 브라우저를 닫기 전까지 상태 유지

 

  • http : 무상태 서버 => 사용자의 요청에 따른 응답을 하고 연결이 끊김
  • 그래서 우리는 사용자의 상태를 유지하는 기법을 고안할 필요가 있다. 이 사용자가 로그인을 했는지, 이 사용자가 투표를 했는지 여부

 

  • session.을 이용하여 데이터를 저장
    • session.setAttribute("속성명", 값);
  • session을 이용하여 데이터를 읽어오기
    • session.getAttribute("속성명");

 

  • session 에 저장할 수 있는 데이터의 형식 Object == 타입 캐스팅하여 써줘야 한다. 
  • jsp 에서 세션 이용하기
  • - session 내장 객체 바로 사용 가능
  • 서블릿에서 세션 이용하기
  • - doGet(HttpServletRequest request, HttpServeltResponse response){
  •     HttpSession session = request.getSession();
  • }
  • KostController ==> init 메소드 등록(처음 최초로 1번만 실행되는 메소드)
  • map 서비스명과 처리할 Action 

 

예제코드

  • kosta.properties
join.do=com.kosta.action.JoinAction
joinOK.do=com.kosta.action.JoinOKAction
login.do=com.kosta.action.LoginAction
loginOK.do=com.kosta.action.LoginOKAction

insertBoard.do=com.kosta.action.InsertBoardAction
insertBoardOK.do=com.kosta.action.InsertBoardOKAction

listBoard.do=com.kosta.action.ListBoardAction
detailBoard.do=com.kosta.action.DetailBoardAction

updateBoard.do=com.kosta.action.UpdateBoardAction
updateBoardOK.do=com.kosta.action.UpdateBoardOKAction

deleteBoard.do=com.kosta.action.DeleteBoardAction
deleteBoardOK.do=com.kosta.action.DeleteBoardOKAction​
  • view
<!-- start.html --> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="join.do">회원가입</a><br>
	<a href="login.do">로그인</a><br>
	<a href="insertBoard.do">게시물 등록</a><br>
	<a href="listBoard.do">게시물 목록</a><br>
</body>
</html>
<!-- join.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>
	<h2>회원가입</h2>
	<hr>
	<form action="joinOK.do" method="post">
		아이디 : <input type="text" name="id"><br>
		비밀번호 : <input type="password" name="pwd"><br>
		이름 : <input type="text" name="name"><br>
		<input type="submit" value="가입">
		<input type="reset" value="다시입력">
	</form>
</body>
</html>
<!-- joinOK.jsp -->
<%@ 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>Insert title here</title>
</head>
<body>
<c:if test="${re > 0 }">
	회원가입 성공
	<hr>
	<a href="login.do">로그인</a>
</c:if>

<c:if test="${re <= 0 }">
	회원가입 실패
</c:if>
</body>
</html>
<!-- login.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>
	<h2>로그인</h2>
	<hr>
	<form action="loginOK.do" method="post">
		아이디 : <input type="text" name="id"><br>		
		암호 : <input type="password" name="pwd"><br>
		<input type="submit" value="로그인">		
		<input type="reset" value="다시입력">		
	</form>
</body>
</html>
<!-- loginOK.jsp-->
<%@ 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>Insert title here</title>
</head>
<body>
	<c:if test="${re == 1 }">
		${userID }님, 로그인이 되었습니다.
	</c:if>
	<c:if test="${re == 0 }">
		암호가 잘못되었습니다.
	</c:if>
	<c:if test="${re == -1 }">
		존재하지 않는 아이디입니다.
	</c:if>
	
	<hr>
	<a href="insertBoard.do">게시물 등록</a><br>
	<a href="listBoard.do">게시물 목록</a><br>
</body>
</html>
<!-- insertBoard.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>
	<h2>게시물 등록</h2>
	<hr>
	<form action="insertBoardOK.do" method="post" enctype="multipart/form-data">
		글제목 : <input type="text" name="title"><br>
		작성자 : <input type="text" name="writer" value="${userID }"><br>
		글암호 : <input type="password" name="pwd"><br>
		글내용 : <br>
		<textarea rows="10" cols="60" name="content"></textarea><br>
		파일 : <input type="file" name="uploadFile">
		<input type="submit" value="등록">
		<input type="reset" value="다시입력">
	</form>
</body>
</html>
<!-- insertBoardOK.jsp --> 
<%@ 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>Insert title here</title>
</head>
<body>
	<c:if test="${re >0 }">
		게시물을 등록하였습니다.
	</c:if>
	<c:if test="${re <=0 }">
		게시물 등록에 실패하였습니다.
	</c:if>
	<hr>
	<a href="insertBoard.do">게시물 등록</a>
</body>
</html>
<!-- listBoard.jsp --> 
<%@ 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>Insert title here</title>
</head>
<body>
	<h2>게시물 목록</h2>
	<hr>
	<table border="1" width="80%">
		<tr>
			<th>글번호</th>
			<th>글제목</th>
			<th>작성자</th>			
			<th>등록일</th>			
			<th>첨부파일</th>			
		</tr>
		<c:forEach var="b" items="${list }">
			<tr>
				<td>${b.no }</td>
				<td>
					<a href="detailBoard.do?no=${b.no }">${b.title }</a>
				</td>
				<td>${b.writer }</td>
				<td>${b.regdate }</td>
				<td>${b.fname }(${b.fsize } bytes)</td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>
<!-- detailBoard.jsp --> 
<%@ 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>Insert title here</title>
</head>
<body>
	<h2>게시물 상세</h2>
	<hr>
	글번호 : ${b.no }<br>
	글제목 : ${b.title }<br>
	작성자 : ${b.writer }<br>
	글내용 :<br>
	<textarea readonly="readonly" rows="10" cols="80">${b.content }</textarea><br>
	등록일 : ${b.regdate }<br>
	조회수 : ${b.hit }<br>
	
	<c:if test="${isImg == 'yes' }">
		<img  src="upload/${b.fname }" width="200" height="200">
	</c:if>
	
	<c:if test="${isImg != 'yes' }">
		첨부파일 : <a href="upload/${b.fname }">${b.fname }(${b.fsize } bytes)</a><br>		
	</c:if>
	
	<hr>
	
	<c:if test="${userID == b.writer }">	
		<a href="updateBoard.do?no=${b.no }">수정</a>
		&nbsp;&nbsp;
		<a href="deleteBoard.do?no=${b.no }">삭제</a>
	</c:if>
	
</body>
</html>
<!-- updateBoard.jsp --> 
<%@ 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>Insert title here</title>
</head>
<body>
	<h2>게시물 수정</h2>
	<hr>
	<form action="updateBoardOK.do" method="post" enctype="multipart/form-data">
		<input type="hidden" name="no" value="${b.no }">
		글제목 : <input type="text" name="title" value="${b.title}"><br>
		작성자 : ${b.writer }<br>
		글암호 : <input type="password" name="pwd"><br>
		글내용 : <br>
		<textarea rows="10" cols="60" name="content">${b.content }</textarea><br>
		<c:if test="${isImg == 'yes' }">
			<img  src="upload/${b.fname }" width="50" height="50">
		</c:if>
		
		<c:if test="${isImg != 'yes' }">
			첨부파일 : ${b.fname }(${b.fsize } bytes)<br>		
		</c:if>
		
		<input type="hidden" name="fname" value="${b.fname }">
		<input type="hidden" name="fsize" value="${b.fsize }">
				
		첨부파일 : <input type="file" name="uploadFile">
		<input type="submit" value="수정">
		<input type="reset" value="다시입력">
	</form>
</body>
</html>
<!-- updateBoardOK.jsp --> 
<%@ 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>Insert title here</title>
</head>
<body>
	<c:if test="${re > 0 }">
		게시물 수정에 성공하였습니다.
	</c:if>
	
	<c:if test="${re <= 0 }">
		게시물 수정에 실패하였습니다.
	</c:if>
	
	<hr>
	<a href="listBoard.do">게시물 목록</a>
</body>
</html>
<!-- deleteBoard.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>
	<h2>게시물 삭제</h2>
	<form action="deleteBoardOK.do" method="post">
		<input type="hidden" name="no" value="${no }">
		글암호 : <input type="password" name="pwd">
		<input type="submit" value="삭제">
		<input type="reset" value="다시입력">
	</form>
</body>
</html>
<!-- error.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>
	죄송합니다. 서비스중에 다음과 같은 문제가 발생하였습니다.
	<hr>
	${msg }
</body>
</html>
  • Controller
package com.kosta.controller;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
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.kosta.action.JoinAction;
import com.kosta.action.JoinOKAction;
import com.kosta.action.KostaAction;
import com.kosta.action.LoginAction;
import com.kosta.action.LoginOKAction;


@WebServlet("*.do")
public class KostaController extends HttpServlet {
	
	HashMap<String, KostaAction> map;
			
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		//super.init(config);
		map= new HashMap<String, KostaAction>();
//		map.put("join.do", new JoinAction());
//		map.put("joinOK.do", new JoinOKAction());
//		map.put("login.do", new LoginAction());
//		map.put("loginOK.do", new LoginOKAction());
		
		//프로퍼티파일이 있는 실제경로를 알아 옵니다.
		String path = config.getServletContext().getRealPath("/WEB-INF");
		try {
			
			//프로퍼티파일을 문자단위로 읽어 들이기 위한 스트림을 생성합니다.
			Reader reader = new FileReader(path + "/kosta.properties");
			
			//프로퍼티 파일을 처리하기 위한 객체를 생성
			Properties prop = new Properties();
			
			//프로퍼티객체에 파일을 읽어들입니다.
			prop.load(reader);
			
			//프로퍼티 객체로 부터 키를 뽑아 옵니다.
			Set keys= prop.keySet();
			
			//key의 수 만큼 반복실행한다.
			//set의 요소만큼 반복 수행시키기 위하여 Iterator로 만들어 줍니다.
			Iterator iter = keys.iterator();
			
			//key들을 갖고 있는 set를 반복시키기 위한 iterator에 데이터가 있는 만큼 반복실행한다. 
			while(iter.hasNext()) {
				String key = (String)iter.next();    //iterator에 데이터를 꺼집어 내어 오면 key이다.
				String clsName = prop.getProperty(key);
				//프로퍼티객체로 부터 key에 해당하는 객체를 꺼집어 내어 오면 일처리를 위한 action클래스 이름이다.
				
				//clsName에는 클래스이름이 문자열로 저장되어 있어요.
				//com.kosta.action.JoinAction
				//우리는 이것을 객체를 생성해야 합니다.
				//new com.kosta.action.JoinAction()
				Object obj= Class.forName(clsName).newInstance();
				
				//생성된 객체와 key를 map에 등록합니다.
				map.put(key, (KostaAction)obj);
			}
			
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
	}

	public void pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
		String cmd = uri.substring( uri.lastIndexOf("/") + 1 ) ;
		
		KostaAction action = null;
		action = map.get(cmd);
		String viewPage = action.pro(request, response);
		
		//viewPage가 jsp가 아니고 .do의 패턴이라면 그 요청을 하도록 합니다.
		if(viewPage.endsWith(".do")) {
			response.sendRedirect(viewPage);
		}else {		
			RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
			dispatcher.forward(request, response);
		}
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		pro(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		pro(request,response);
	}

}
  • Model 
package com.kosta.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnectionProvider {	
	public static  Connection getConnection() {
		Connection conn = null;
		String driver = "oracle.jdbc.driver.OracleDriver";
		String url = "jdbc:oracle:thin:@localhost:1521:XE";
		String username = "c##madang";
		String password = "madang";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}	
		return conn;
	}
	
	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		try {
			if(rs != null) {
				rs.close();
			}
			if(stmt != null) {
				stmt.close();
			}
			if(conn != null) {
				conn.close();
			}
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
	}
	public static void close(Statement stmt, Connection conn) {
		try {		
			if(stmt != null) {
				stmt.close();
			}
			if(conn != null) {
				conn.close();
			}
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
	}
}
package com.kosta.vo;

public class MemberVO {
	private String id;
	private String pwd;
	private String name;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public MemberVO(String id, String pwd, String name) {
		super();
		this.id = id;
		this.pwd = pwd;
		this.name = name;
	}
	public MemberVO() {
		super();
		// TODO Auto-generated constructor stub
	}
}
package com.kosta.vo;

import java.util.Date;

public class BoardVO {
	private int no;
	private String title;
	private String writer;
	private String pwd;
	private String content;
	private Date regdate;
	private int hit;
	private String fname;
	private int fsize;
	public BoardVO(int no, String title, String writer, String pwd, String content, Date regdate, int hit, String fname,
			int fsize) {
		super();
		this.no = no;
		this.title = title;
		this.writer = writer;
		this.pwd = pwd;
		this.content = content;
		this.regdate = regdate;
		this.hit = hit;
		this.fname = fname;
		this.fsize = fsize;
	}
	public BoardVO() {
		super();
		// TODO Auto-generated constructor stub
	}
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getRegdate() {
		return regdate;
	}
	public void setRegdate(Date regdate) {
		this.regdate = regdate;
	}
	public int getHit() {
		return hit;
	}
	public void setHit(int hit) {
		this.hit = hit;
	}
	public String getFname() {
		return fname;
	}
	public void setFname(String fname) {
		this.fname = fname;
	}
	public int getFsize() {
		return fsize;
	}
	public void setFsize(int fsize) {
		this.fsize = fsize;
	}
}
package com.kosta.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.kosta.db.ConnectionProvider;
import com.kosta.vo.MemberVO;

public class MemberDAO {
	
	//로그인시 아이디와 암호를 매개변수로 전달받아 회원의 정보가 올바른지 판별하는 메소드
	//아이디도 맞고 암호도 맞으면 	1
	//아이디는 있는데 암호가 틀리면 	0
	//아이디도 없으면 				-1
	public int isMember(String id, String pwd) {
		int re = -1;
		String sql = "select pwd from member where id=?";
		try {
			Connection conn =  ConnectionProvider.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()) {
				String dbPwd = rs.getString(1);
				if(dbPwd.equals(pwd)) {
					re=1;
				}else {
					re=0;
				}
			}
			ConnectionProvider.close(rs, pstmt, conn);
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
		return re;
	}
	
	
	
	// id를 사용할 수 있는지 판별하는 메소드
	// 사용가능 : 1, 이미 존재하는 아이디 :  0
	public int idCheck(String id) {
		int re = 1;
		try {
			String sql = "select * from member where id=?";
			Connection conn = ConnectionProvider.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, id);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()) {
				re = 0;
			}
			ConnectionProvider.close(rs, pstmt, conn);
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
		return re;
	}
	
	
	public int insert(MemberVO m ) {
		int re = -1;
		String sql = "insert into member values(?,?,?)";
		try {
			Connection conn = ConnectionProvider.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, m.getId());
			pstmt.setString(2, m.getPwd());
			pstmt.setString(3, m.getName());
			re = pstmt.executeUpdate();
			
			ConnectionProvider.close(pstmt, conn);
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
		return re;
	}
}
package com.kosta.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import com.kosta.db.ConnectionProvider;
import com.kosta.vo.BoardVO;

public class BoardDAO {	
	public int delete(int no, String pwd) {
		int re = -1;
		String sql = "delete board where no=? and pwd=?";
		try {
			Connection conn = ConnectionProvider.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);			
			pstmt.setInt(1, no);
			pstmt.setString(2, pwd);
			re = pstmt.executeUpdate();
			ConnectionProvider.close(pstmt, conn);			
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
		return re;
	}
	
	public int update(BoardVO b) {
		int re = -1;
		String sql = "update board set title=?,content=?,fname=?,fsize=? where no=? and pwd=?";
		try {
			Connection conn = ConnectionProvider.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, b.getTitle());
			pstmt.setString(2, b.getContent());
			pstmt.setString(3, b.getFname());
			pstmt.setInt(4, b.getFsize());
			pstmt.setInt(5, b.getNo());
			pstmt.setString(6, b.getPwd());
			re = pstmt.executeUpdate();
			ConnectionProvider.close(pstmt, conn);
			
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
		return re;
	}
	
	
	public BoardVO findByNo(int no) {
		BoardVO b = null;
		String sql = "select * from board where no=?";
		try {
			Connection conn = ConnectionProvider.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, no);
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()) {
				b = new BoardVO(	no, 
									rs.getString(2), 
									rs.getString(3), 
									rs.getString(4), 
									rs.getString(5), 
									rs.getDate(6), 
									rs.getInt(7),
									rs.getString(8),
									rs.getInt(9)
						);
			}
			ConnectionProvider.close(rs, pstmt, conn);
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
		return b;
	}
	
	public ArrayList<BoardVO> findAll(){
		ArrayList<BoardVO> list = new ArrayList<BoardVO>();
		String sql = "select  * from board";
		try {
			Connection conn =  ConnectionProvider.getConnection();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()) {
				list.add(new BoardVO(	rs.getInt(1), 
										rs.getString(2), 
										rs.getString(3), 
										rs.getString(4), 
										rs.getString(5), 
										rs.getDate(6), 
										rs.getInt(7),
										rs.getString(8),
										rs.getInt(9)
						));
			}
			ConnectionProvider.close(rs, stmt, conn);
			
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
		return list;
	}
	
	
	
	//새로운 게시물 번호를 발행 하는 메소드
	public int getNextNo() {
		int no = 0;
		String sql = "select nvl(max(no),0)+1 from board";
		try {
			Connection conn = ConnectionProvider.getConnection();
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if(rs.next()) {
				no = rs.getInt(1);
			}
			ConnectionProvider.close(rs, stmt, conn);
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}		
		return no;
	}
	
	public int insert(BoardVO b) {
		int re = -1;
		int no = getNextNo();
		String sql = "insert into board values(?,?,?,?,?,sysdate,0,?,?)";
		try {
			Connection conn = ConnectionProvider.getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, no);
			pstmt.setString(2, b.getTitle());
			pstmt.setString(3, b.getWriter());
			pstmt.setString(4, b.getPwd());
			pstmt.setString(5, b.getContent());
			pstmt.setString(6, b.getFname());
			pstmt.setInt(7, b.getFsize());
			re = pstmt.executeUpdate();
			ConnectionProvider.close(pstmt, conn);			
		}catch (Exception e) {
			System.out.println("예외발생:"+e.getMessage());
		}
		return re;
	}
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface KostaAction {
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JoinAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		return "join.jsp";
	}
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kosta.dao.MemberDAO;
import com.kosta.vo.MemberVO;

public class JoinOKAction implements KostaAction {
	
	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MemberDAO dao = new MemberDAO();
		request.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		String pwd = request.getParameter("pwd");
		String name = request.getParameter("name");
		MemberVO m = new MemberVO(id, pwd, name);
		int re = dao.insert(m);
		request.setAttribute("re", re);
		return "joinOK.jsp";
	}
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		return "login.jsp";
	}
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kosta.dao.MemberDAO;

public class LoginOKAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		MemberDAO dao = new MemberDAO();
		request.setCharacterEncoding("UTF-8");
		String id = request.getParameter("id");
		String pwd = request.getParameter("pwd");
		int re = dao.isMember(id, pwd);
		if(re == 1) {
			// 로그인했다는 표시로 상태유지 합니다.
			// 이것을 위하여 session을 이용하여 상태유지 합니다.
			HttpSession session = request.getSession();
			session.setAttribute("userID", id);
		}
		
		request.setAttribute("re", re);		
		return "loginOK.jsp";
	}
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class InsertBoardAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		if(session.getAttribute("userID") == null) {
			return "login.do";
		}
		
		return "insertBoard.jsp";
	}
}
package com.kosta.action;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kosta.dao.BoardDAO;
import com.kosta.vo.BoardVO;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class InsertBoardOKAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BoardDAO dao = new BoardDAO();
		request.setCharacterEncoding("UTF-8");
		
		// 파일업로드도 하고 사용자가 요청한 데이터도 받아오기 위하여 cos.jar에 있는
		// MultipartRequest 객체를 이용합니다.
		// MultipartRequest 객체 생성시에 파일을 업로드할 경로를 지정해야 합니다.
			
		//업로드할 폴더(upload)의 실경로를 알아 옵니다.
		String path = request.getServletContext().getRealPath("upload");
		System.out.println("path:"+path);
		
		// MultipartRequst 객체를 생성하는 순간 파일은 서버의 지정한 경로가 업로드(복사)가 되고 
		// 나머지 사용자 입력한 정보를 multi 객체가 갖고 있습니다.
		MultipartRequest multi 
		= new MultipartRequest(request, 
				path, 
				1024*1024*1024*5, 
				"UTF-8", 
				new DefaultFileRenamePolicy());
		
		String fname = multi.getOriginalFileName("uploadFile");
		File file = new File(path + "/" +fname);
		int fsize = (int)file.length();
		String title = multi.getParameter("title");
		String writer = multi.getParameter("writer");
		String pwd = multi.getParameter("pwd");
		String content = multi.getParameter("content");
		BoardVO b = new BoardVO();
		b.setTitle(title);
		b.setWriter(writer);
		b.setPwd(pwd);
		b.setContent(content);
		b.setFname(fname);
		b.setFsize(fsize);
		int re = dao.insert(b);
		request.setAttribute("re", re);		
		return "insertBoardOK.jsp";
	}
}
package com.kosta.action;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kosta.dao.BoardDAO;
import com.kosta.vo.BoardVO;

public class ListBoardAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BoardDAO dao = new BoardDAO();		
		request.setAttribute("list", dao.findAll());
		return "listBoard.jsp";
	}
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kosta.dao.BoardDAO;
import com.kosta.vo.BoardVO;

public class DetailBoardAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BoardDAO dao = new BoardDAO();
		int no = Integer.parseInt(request.getParameter("no"));
		BoardVO b= dao.findByNo(no);
		//son.png
		
		String ext = b.getFname().split("\\.")[1];
		
		ext = ext.toLowerCase();
		String isImg = "no";
		if(ext.equals("png") || ext.equals("jpg") ||ext.equals("gif"))
		{
			isImg = "yes";
		}
		request.setAttribute("b", b);
		request.setAttribute("isImg", isImg);
		return "detailBoard.jsp";
	}
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kosta.dao.BoardDAO;
import com.kosta.vo.BoardVO;

public class UpdateBoardAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		BoardDAO dao = new BoardDAO();
		
		int no = Integer.parseInt(request.getParameter("no"));
		
		BoardVO b= dao.findByNo(no);
		//son.png
		
		String ext = b.getFname().split("\\.")[1];
		
		ext = ext.toLowerCase();
		String isImg = "no";
		if(ext.equals("png") || ext.equals("jpg") ||ext.equals("gif"))
		{
			isImg = "yes";
		}
		request.setAttribute("b", b);
		request.setAttribute("isImg", isImg);
		
		return "updateBoard.jsp";
	}
}
package com.kosta.action;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kosta.dao.BoardDAO;
import com.kosta.vo.BoardVO;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class UpdateBoardOKAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String path = request.getServletContext().getRealPath("upload");
		MultipartRequest multi = new MultipartRequest(
				request, 
				path, 
				1024*1024*1024*5, 
				"UTF-8", new DefaultFileRenamePolicy());
				
		BoardDAO dao = new BoardDAO();
		int no = Integer.parseInt(multi.getParameter("no"));
		String title = multi.getParameter("title");	
		String pwd = multi.getParameter("pwd");
		String content = multi.getParameter("content");
		
		String oldFname = multi.getParameter("fname");
		int oldFsize = Integer.parseInt(multi.getParameter("fsize"));
			
		
		BoardVO b = new BoardVO();
		b.setTitle(title);
		b.setNo(no);
		b.setPwd(pwd);
		b.setContent(content);
		b.setFname(oldFname);
		b.setFsize(oldFsize);
		
		String fname = multi.getOriginalFileName("uploadFile");
		
		//만약에 업로드한 파일이 있다면 (파일도 수정한다면 그 파일의 정보로 VO를 변경 해 준다.)
		if(fname != null) {
			File file = new File(path + "/"+ fname);
			int fsize = (int)file.length();
			b.setFname(fname);
			b.setFsize(fsize);
		}
		
		int re = dao.update(b);
		
		//게시물 수정에 성공했고 파일도 수정했다면 원래의 파일을 삭제 합니다.
		if(re > 0 && fname != null) {
			File file = new File(path + "/" + oldFname);
			file.delete();
		}
		
		request.setAttribute("re", re);		
		return "updateBoardOK.jsp";
	}
}
package com.kosta.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DeleteBoardAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int no = Integer.parseInt(request.getParameter("no"));
		request.setAttribute("no", no);
		return "deleteBoard.jsp";
	}
}
package com.kosta.action;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kosta.dao.BoardDAO;

public class DeleteBoardOKAction implements KostaAction {

	@Override
	public String pro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String path = request.getServletContext().getRealPath("upload");
		
		String viewPage = "";
		int no = Integer.parseInt(request.getParameter("no"));
		String pwd = request.getParameter("pwd");
		BoardDAO dao = new BoardDAO();
		
		//게시물 삭제시키기 전에 파일이름을 저장 해 둡니다.
		String fname = dao.findByNo(no).getFname();
				
		int re = dao.delete(no, pwd);
		
		//삭제를 성공했단
		if(re > 0) {
			viewPage = "listBoard.do";
			
			//원래 파일도 삭제 해 준다.
			File file = new File(path + "/" + fname);
			file.delete();
			
		}else {
			request.setAttribute("msg", "게시물 삭제에 실패하였습니다. 암호를 확인하세요!");
			viewPage = "error.jsp";
		}
		return viewPage;
	}
}

'Kosta DevOps 과정 280기 > Java' 카테고리의 다른 글

jquery와 Ajax  (0) 2024.07.22
Ajax 통신  (0) 2024.07.22
프론트 컨트롤러  (0) 2024.07.15
MVC 패턴  (0) 2024.07.15
jsp 문장 구성 요소  (0) 2024.07.15