JSP/day39 / 23.10.26(목) / (핀테크) Spring 및 Ai 기반 핀테크 프로젝트 구축

허니몬·2023년 10월 26일
0
post-thumbnail

java/

BoardDTO.java

package board.dto;
/*
-- board 테이블( 게시판 )
CREATE TABLE board(
seq NUMBER NOT NULL,             -- 글번호
id VARCHAR2(30) NOT NULL,        -- 아이디
name VARCHAR2(30) NOT NULL,      -- 작성자
subject VARCHAR2(50) NOT NULL,   -- 제목
content VARCHAR2(1000) NOT NULL, -- 내용
hit NUMBER DEFAULT 0,            -- 조회수
logtime DATE DEFAULT SYSDATE     -- 작성일자
);

-- seq 컬럼에 적용하는 board_seq 시퀀스 객체 생성
CREATE SEQUENCE board_seq NOCACHE NOCYCLE;

*/
public class BoardDTO {
	private int seq;
	private String id;
	private String name;
	private String subject;
	private String content;
	private int hit;
	private String logtime;
	
	public BoardDTO() {
		super();
	}
	public int getSeq() {
		return seq;
	}
	public void setSeq(int seq) {
		this.seq = seq;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public int getHit() {
		return hit;
	}
	public void setHit(int hit) {
		this.hit = hit;
	}
	public String getLogtime() {
		return logtime;
	}
	public void setLogtime(String logtime) {
		this.logtime = logtime;
	}
	
}

BoardDAO.java

package board.dao;

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

import board.dto.BoardDTO;

public class BoardDAO {
	// 연결 정보
	private String driver = "oracle.jdbc.OracleDriver";
	private String url = "jdbc:oracle:thin:@localhost:1521:xe";
	private String id = "dbtest";
	private String pwd = "a1234";

	private Connection con = null;
	private PreparedStatement pstmt = null;
	private ResultSet res = null;

	public BoardDAO() {
		try {
			Class.forName(driver);
			// System.out.println("로딩 성공");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Connection getConnection() {
		try {
			// DB 연결 객체 생성
			con = DriverManager.getConnection(url, id, pwd);
			// System.out.println("연결 성공!!");
		} catch (Exception e) {
			// System.out.println("연결 실패~");
			e.printStackTrace();
		}
		return con;
	}// getConnection() end

	// 글쓰기
	public int write(BoardDTO dto) {
		int su = 0;
		try {
			String sql = "INSERT INTO board VALUES(board_seq.NEXTVAL,?,?,?,?,0,SYSDATE)";
			con = this.getConnection();
			pstmt = con.prepareStatement(sql);
			String[] arr = {dto.getId(), dto.getName(), dto.getSubject(), dto.getContent()};
			for (int i = 1; i <= 4; i++) {
				pstmt.setString(i, arr[i - 1]);
			}
//			pstmt.setString(1, dto.getId());
//			pstmt.setString(2, dto.getName());
//			pstmt.setString(3, dto.getSubject());
//			pstmt.setString(4, dto.getContent());
			su = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (con != null)
					con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return su;
	}

	// db 통로
	public void streamClose(ResultSet res, PreparedStatement pstmt, Connection con) {
		try {
			if (res != null)
				res.close();
			if (pstmt != null)
				pstmt.close();
			if (con != null)
				con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	// streamClase end

}

MemberDAO.java

package member.dao;

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

import member.dto.MemberDTO;
import oracle.jdbc.proxy.annotation.Pre;

public class MemberDAO {

	// 연결 정보
	private String driver = "oracle.jdbc.OracleDriver";
	private String url = "jdbc:oracle:thin:@localhost:1521:xe";
	private String id = "dbtest";
	private String pwd = "a1234";
	
	private Connection con = null;
	private PreparedStatement pstmt = null;
	private ResultSet res = null;
	
	public MemberDAO() {
		try {
			Class.forName(driver);
			//System.out.println("로딩 성공");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Connection getConnection() {
		try {
			// DB 연결 객체 생성
			con = DriverManager.getConnection(url, id, pwd);
			//System.out.println("연결 성공!!");
		} catch (Exception e) {
			//System.out.println("연결 실패~");
			e.printStackTrace();
		}
		return con;
	}// getConnection() end
	
	
	public int write(MemberDTO dto) {
		int res = 0;
		try {
			String sql ="INSERT INTO MEMBER VALUES(?,?,?,?,?,?,?,?,SYSDATE)";
			con = this.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, dto.getName());
			pstmt.setString(2, dto.getId());
			pstmt.setString(3, dto.getPwd());
			pstmt.setString(4, dto.getGender());
			pstmt.setString(5, dto.getEmail());
			pstmt.setString(6, dto.getDomain());
			pstmt.setString(7, dto.getTel());
			pstmt.setString(8, dto.getAddr());
			res = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(con!=null) con.close();
				if(pstmt!=null) pstmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return res;
	}// write() end
	
	public boolean isExistId(String id) {
		
		boolean ex = false;
		try {
			String sql = "SELECT * FROM member WHERE ID=?";
			con = this.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			res = pstmt.executeQuery();
			if(res.next()) {
				ex = true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(res!=null) res.close();
				if(pstmt!=null) pstmt.close();
				if(con!=null) con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ex;
	}
	
	// 로그인
	public String login(String id, String pwd) {
		
		String name ="";
		try {
			String sql = "SELECT*FROM member WHERE id=? and pwd=?";
			con = this.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);
			res = pstmt.executeQuery();
			if(res.next()) {
				name = res.getString("name");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(res!= null) res.close();
				if(pstmt!= null) pstmt.close();
				if(con!= null) con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return name;
	}
	
	// 회원정보 가져오기
	public MemberDTO bring(String id) {
		MemberDTO data = null;
		try {
			data = new MemberDTO();
			String sql = "SELECT*FROM member WHERE id=?";
			con = this.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			res = pstmt.executeQuery();
			if(res.next()) {
				data.setName(res.getString("name"));
				data.setId(res.getString("id"));
				data.setPwd(res.getString("pwd"));
				data.setGender(res.getString("gender"));
				data.setEmail(res.getString("email"));
				data.setDomain(res.getString("domain"));
				data.setTel(res.getString("tel"));
				data.setAddr(res.getString("addr"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(res!=null)res.close();
				if(pstmt!=null)pstmt.close();
				if(con!=null)con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return data;
	}
	
	public int update(MemberDTO dto) {	
		int res = 0;
		try {
			String sql ="UPDATE member SET name=?,pwd=?,gender=?,email=?,domain=?,tel=?,addr=? where id=?";
			con = this.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, dto.getName());
			pstmt.setString(2, dto.getPwd());
			pstmt.setString(3, dto.getGender());
			pstmt.setString(4, dto.getEmail());
			pstmt.setString(5, dto.getDomain());
			pstmt.setString(6, dto.getTel());
			pstmt.setString(7, dto.getAddr());
			pstmt.setString(8, dto.getId());
			res = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(con!=null) con.close();
				if(pstmt!=null) pstmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return res;
	}
	// 수정T
	public void modify() {
		
	}
}


index.jsp

<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
String id = (String)session.getAttribute("memberId");
String name = (String)session.getAttribute("memberName");
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
	<h1>index</h1>
	<br>
	<%if(id==null||id==""){ %>
		<a href="member/writeForm.jsp"> 회원가입 </a>
		<br><br>
		<a href="member/loginForm.jsp"> 로그인 </a>
	<%}else { %>
		<a href="member/logout.jsp">로그아웃</a>
		<br><br>
		<a href="member/modifyForm.jsp"> 회원정보 수정</a>
		<br><br>
		<a href="board/boardWriteForm.jsp"> 글쓰기 </a>
	<%} %>
</body>
</html>

script

boardScrips.js

function checkBoardWrite(){
	if(document.boardWriteForm.subject.value ==""){
		alert("제목 입력");
		document.boardWriteForm.subject.focus();
	}else if(document.boardWriteForm.content.value ==""){
		alert("내용 입력");
		document.boardWriteForm.content.focus();
	} else {
		document.boardWriteForm.submit();
	}
}

webapp/board

boardWriteForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>boardWriteForm.jsp</title>
<style type="text/css">
table, th, td {
	border: 1px solid black;
	border-collapse: collapse;
}
th, td {
	padding: 4px;
}
textarea {
	resize: none;
}
</style>
<script type="text/javascript" src="../script/boardScript.js?after"></script>
</head>
<body>
	<h1>글쓰기</h1>
	<br>
	<form name="boardWriteForm" action="boardWrite.jsp" method="post">
      <table>
         <tr>
            <th> 제 목 </th>
            <td><input type="text" name="subject" size="50"/></td>
         </tr>
         <tr>
            <th> 내 용 </th>
            <td>
               <textarea rows="20" cols="52" name="content"></textarea>
            </td>
         </tr>
         <tr>
            <td colspan="2" align="center">
               <input type="button" value="완료" onclick="checkBoardWrite()"/>
            </td>
         </tr>
      </table>
   </form>
</body>
</html>

boardWrite.jsp

<%@page import="board.dao.BoardDAO"%>
<%@page import="board.dto.BoardDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String id = (String)session.getAttribute("memberId");
String name = (String)session.getAttribute("memberName");

BoardDTO dto = new BoardDTO();
dto.setName(name);
dto.setId(id);
dto.setSubject(subject);
dto.setContent(content);

BoardDAO dao = new BoardDAO();
int write = dao.write(dto);
String msg = "";
if(write==1) {
	msg = "올리기 성공";
}else {
	msg = "글쓰기 실패";
}


%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>boardWrite.jsp</title>
</head>
<body>
	<h1>글쓰기 확인</h1>
	<br>
	<p><strong><%=msg %></strong></p>
	<table>
		<tr>
			<th><%=dto.getSubject() %></th>
		</tr>
		<tr>
			<td><%=dto.getContent() %></td>
		</tr>
	</table>
</body>
</html>



11_ConnectionPool


WEB-INF/lib/에 tomcat-dbcp.jar 넣기

ConnectionPool.txt

< ConnectionPool.txt >

Connection Pool

  • 데이터베이스에 연결하기 위한 Connection 은 객체이다
    Connection 객체를 생성하고 해제하는 동안 시스템 자원이 소모됨
    이 문제를 해결하기 위해 Connection pools 에 Connection 객체를 만들어 놓은 후,
    Connection 객체가 필요한 경우 객체를 할당해 주고, 사용이 끝나면 다시 ConnectionPool 로 회수하는 방법

JNDI ( Java Naming and Directory Interface )

  • Java 소프트웨어에서 객체나 데이터를 전체 경로를 몰라도 '이름'만으로 찾아서 사용하는 디렉토리 서비스

JNDI 를 통해 사용하는 순서

    1. server.xml 과 context.xml 에 설정한 대로 ConnectionPool 을 생성
    2. JSP 코드에서 JNDI 서버로부터 데이터소스 객체 받기
    3. 데이터소스로부터 Connection 객체 가져오기
    4. DB 작업 수행
    5. DB 작업 종료시 Connection 객체를 ConnectionPool 로 반환

jar 파일 추가

  • tomcat server 설치 폴더안에 기본 제공

    tomcat-dbcp.jar

DBCP 정보 설정

  • META-INF 폴더

    context.xml : connection pool 설정 파일


META-INF

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--  
auth            : 자원관리자
name            : 설정 구별하는 이름(생성하는 풀 이름)
type            : 데이터소스로 사용하는 클래스 이름. 웹에서 리소스 사용할 때 DataSource 로 반환
driverClassName : JDBC 드라이버
url             : DB 경로
username        : 접속 계정
password        : 접속 비밀번호
maxActive       : 최대 연결 갯수
maxIdle         : 풀에 저장될 수 있는 컨넥션 수
maxWait         : 사용 가능한 컨넥션이 없을 때 대기 시간( 1/1000 초, -(마이너스) 값이면 무한 대기 )
-->
<Context>
	<Resource auth="Container"
	          name="jdbc/oracle"
	          type="javax.sql.DataSource"
	          driverClassName="oracle.jdbc.OracleDriver"
	          url="jdbc:oracle:thin:@localhost:1521:xe"
	          username="dbtest"
	          password="a1234"
	          maxActive="20"
	          maxIdle="3"
	          maxWait="-1"
	          >
	</Resource>
</Context>

MemberDAO.java

package member.dao;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import member.dto.MemberDTO;
import oracle.jdbc.proxy.annotation.Pre;

public class MemberDAO {

	// 연결 정보
	private Connection con;
	private PreparedStatement pstmt;
	private ResultSet res;
	private DataSource ds;
	
	public MemberDAO() {
		try {
			// InitalContect 객체 생성해서 설정된 정보 가져오기 : JNDI
			Context context = new InitialContext();
			
			// Context 클래스의 lookup() 메서드는 'java:comp/env/jdbc/oracle' 을 가지고 DataSource 객체를 구합니다
			// - lookup() 메서드를 사용해서 naming 서비스에서 자원을 찾습니다
			// - JNDI 의 이름은 'java:comp/env/' 에 등록되어 있습니다
			ds = (DataSource)context.lookup("java:comp/env/jdbc/oracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public int write(MemberDTO dto) {
		int res = 0;
		try {
			String sql ="INSERT INTO MEMBER VALUES(?,?,?,?,?,?,?,?,SYSDATE)";
			con = ds.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, dto.getName());
			pstmt.setString(2, dto.getId());
			pstmt.setString(3, dto.getPwd());
			pstmt.setString(4, dto.getGender());
			pstmt.setString(5, dto.getEmail());
			pstmt.setString(6, dto.getDomain());
			pstmt.setString(7, dto.getTel());
			pstmt.setString(8, dto.getAddr());
			res = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(con!=null) con.close();
				if(pstmt!=null) pstmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return res;
	}// write() end
	
	public boolean isExistId(String id) {
		
		boolean ex = false;
		try {
			String sql = "SELECT * FROM member WHERE ID=?";
			con = ds.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			res = pstmt.executeQuery();
			if(res.next()) {
				ex = true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(res!=null) res.close();
				if(pstmt!=null) pstmt.close();
				if(con!=null) con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ex;
	}
	
	// 로그인
	public String login(String id, String pwd) {
		
		String name ="";
		try {
			String sql = "SELECT*FROM member WHERE id=? and pwd=?";
			con = ds.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);
			res = pstmt.executeQuery();
			if(res.next()) {
				name = res.getString("name");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(res!= null) res.close();
				if(pstmt!= null) pstmt.close();
				if(con!= null) con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return name;
	}
	
	// 회원정보 가져오기
	public MemberDTO bring(String id) {
		MemberDTO data = null;
		try {
			data = new MemberDTO();
			String sql = "SELECT*FROM member WHERE id=?";
			con = ds.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			res = pstmt.executeQuery();
			if(res.next()) {
				data.setName(res.getString("name"));
				data.setId(res.getString("id"));
				data.setPwd(res.getString("pwd"));
				data.setGender(res.getString("gender"));
				data.setEmail(res.getString("email"));
				data.setDomain(res.getString("domain"));
				data.setTel(res.getString("tel"));
				data.setAddr(res.getString("addr"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(res!=null)res.close();
				if(pstmt!=null)pstmt.close();
				if(con!=null)con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return data;
	}
	
	public int update(MemberDTO dto) {	
		int res = 0;
		try {
			String sql ="UPDATE member SET name=?,pwd=?,gender=?,email=?,domain=?,tel=?,addr=? where id=?";
			con = ds.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, dto.getName());
			pstmt.setString(2, dto.getPwd());
			pstmt.setString(3, dto.getGender());
			pstmt.setString(4, dto.getEmail());
			pstmt.setString(5, dto.getDomain());
			pstmt.setString(6, dto.getTel());
			pstmt.setString(7, dto.getAddr());
			pstmt.setString(8, dto.getId());
			res = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(con!=null) con.close();
				if(pstmt!=null) pstmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return res;
	}
}

BoardDAO.java

package board.dao;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import board.dto.BoardDTO;

public class BoardDAO {
	private Connection con;
	private PreparedStatement pstmt;
	private ResultSet res;
	private DataSource ds;

	public BoardDAO() {
		try {
			// InitalContect 객체 생성해서 설정된 정보 가져오기 : JNDI
			Context context = new InitialContext();
			
			// Context 클래스의 lookup() 메서드는 'java:comp/env/jdbc/oracle' 을 가지고 DataSource 객체를 구합니다
			// - lookup() 메서드를 사용해서 naming 서비스에서 자원을 찾습니다
			// - JNDI 의 이름은 'java:comp/env/' 에 등록되어 있습니다
			ds = (DataSource)context.lookup("java:comp/env/jdbc/oracle");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 글쓰기
	public int write(BoardDTO dto) {
		int su = 0;
		try {
			String sql = "INSERT INTO board VALUES(board_seq.NEXTVAL,?,?,?,?,0,SYSDATE)";
			con = ds.getConnection();
			pstmt = con.prepareStatement(sql);
			String[] arr = {dto.getId(), dto.getName(), dto.getSubject(), dto.getContent()};
			for (int i = 1; i <= 4; i++) {
				pstmt.setString(i, arr[i - 1]);
			}
//			pstmt.setString(1, dto.getId());
//			pstmt.setString(2, dto.getName());
//			pstmt.setString(3, dto.getSubject());
//			pstmt.setString(4, dto.getContent());
			su = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (con != null)
					con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return su;
	}

	// db 통로
	public void streamClose(ResultSet res, PreparedStatement pstmt, Connection con) {
		try {
			if (res != null)
				res.close();
			if (pstmt != null)
				pstmt.close();
			if (con != null)
				con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}// streamClase end
	
	public ArrayList<BoardDTO> boardList(int startNum, int lastNum) {
		ArrayList<BoardDTO> list = new ArrayList<>();
		BoardDTO dto = null;
		try {
			String sql ="SELECT seq,id,name,subject,content,hit,TO_CHAR(logtime,'YYYY.MM.DD') AS logtime FROM " 
					   + "(SELECT rownum rn, tt. * FROM "
					   + "(SELECT * FROM board ORDER BY SEQ DESC) tt) "
					   + "WHERE rn>=? and rn<=?";
			con = ds.getConnection();
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, startNum);
			pstmt.setInt(2, lastNum);
			res = pstmt.executeQuery();
			while(res.next()) {
				dto = new BoardDTO();
				dto.setSeq(res.getInt("seq"));
				dto.setId(res.getString("id"));
				dto.setName(res.getString("name"));
				dto.setSubject(res.getString("subject"));
				dto.setContent(res.getString("content"));
				dto.setHit(res.getInt("hit"));
				dto.setLogtime(res.getString("logtime"));
				list.add(dto);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			streamClose(res, pstmt, con);
		}
		return list;
	}// boardList() end
	
	
	public int getTotalArticle() {
		int total =0;
		
		try {
			String sql = "SELECT COUNT(*) FROM board";
			con = ds.getConnection();
			pstmt = con.prepareStatement(sql);
			res = pstmt.executeQuery();
			if(res.next()) {
				total =res.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			streamClose(res, pstmt, con);
		}
		return total;
	}// getTotalArticle() end
}


index.jsp

<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
String id = (String)session.getAttribute("memberId");
String name = (String)session.getAttribute("memberName");
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
	<h1>index</h1>
	<br>
	<%if(id==null||id==""){ %>
		<a href="member/writeForm.jsp"> 회원가입 </a>
		<br><br>
		<a href="member/loginForm.jsp"> 로그인 </a>
	<%}else { %>
		<a href="member/logout.jsp">로그아웃</a>
		<br><br>
		<a href="member/modifyForm.jsp"> 회원정보 수정</a>
		<br><br>
		<a href="board/boardWriteForm.jsp"> 글쓰기 </a>
	<%} %>
	<br><br>
	<a href="board/boardList.jsp?pg=1"> 글목록 </a>
</body>
</html>

boardWrite.jsp

<%@page import="board.dao.BoardDAO"%>
<%@page import="board.dto.BoardDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String id = (String)session.getAttribute("memberId");
String name = (String)session.getAttribute("memberName");

BoardDTO dto = new BoardDTO();
dto.setName(name);
dto.setId(id);
dto.setSubject(subject);
dto.setContent(content);

BoardDAO dao = new BoardDAO();
int write = dao.write(dto);
String msg = "";
if(write==1) {
	msg = "올리기 성공";
}else {
	msg = "글쓰기 실패";
}


%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>boardWrite.jsp</title>
</head>
<body>
	<h1>글쓰기 확인</h1>
	<br>
	<p><strong><%=msg %></strong></p>
	<table>
		<tr>
			<th><%=dto.getSubject() %></th>
		</tr>
		<tr>
			<td><%=dto.getContent() %></td>
		</tr>
	</table><br>
	<input type="button" value="main" onclick="location.href='../index.jsp'"/>
</body>
</html>

boardList.jsp

<%@page import="java.util.ArrayList"%>
<%@page import="board.dto.BoardDTO"%>
<%@page import="board.dao.BoardDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
int pg = Integer.parseInt(request.getParameter("pg"));

int article = 3;			// 한 페이지 글 목록 수
int currentPage = pg;	// 현재 페이지
int startNum = (currentPage -1) * article + 1;	// 시작 글번호
int lastNum = startNum + article - 1;		// 마지막 글 번호
BoardDAO dao = new BoardDAO();
ArrayList<BoardDTO> list = dao.boardList(startNum, lastNum);

// 페이징
int totalArticle = dao.getTotalArticle(); // 전체 글 수
int totalPage = (totalArticle-1) / article +1; //전체 페이지 수

int block = 3; // 페이지 블록
int startPage = (currentPage-1)/block * block + 1;
int endPage = startPage + block -1;
if(endPage > totalPage) endPage = totalPage;
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>boardList.jsp</title>
<style type="text/css">
table, th, td {
	border: 1px solid black;
	border-collapse: collapse;
}
td {
	text-align: center;
}
#paging_block {
	width: 1000px;
	text-align: center;
}
#paging {
	color: black;
	text-decoration: none;
}
#currnetPaging {
	color: red;
	text-decoration: underline;
}


</style>
</head>
<body>
	<h1>글목록</h1>
	<br>
	<table>
		<tr>
			<th width="100px"> 글번호 </th>
			<th width="500px"> 제목 </th>
			<th width="150px">작성자 </th>
			<th width="150px"> 작성일 </th>
			<th width="100px"> 조회수 </th>
		</tr>
		<%for(BoardDTO dto : list) {%>
		<tr>
			<td><%=dto.getSeq() %></td>			
			<td>
				<a href="#" onclick="isLogin(<%=dto.getSeq()%>)"><%=dto.getSubject() %></a> 
			</td>			
			<td><%=dto.getName() %></td>			
			<td><%=dto.getLogtime() %></td>			
			<td><%=dto.getHit() %></td>			
		</tr>
		<%} %>
	</table>
	<br><br>
	<!-- 페이징 -->
	<div id="paging_block">
		<%if(startPage > block){ %>
			[ <a href="boardList.jsp?pg=<%=startPage-1%>" id="paging"> 이전 </a>]
		<%} %>
		<%for(int i=startPage ;i<=endPage;i++) {%>
			<%if(i==pg){ %>
				[ <a href="boardList.jsp?pg=<%=i%>" id="currentPaging"><%=i %> </a>]
			<%} else {%>
				[ <a href="boardList.jsp?pg=<%=i%>" id="paging"><%=i %> </a>]
			<%} %>
		<%} %>
		<%if(endPage < totalPage){ %>
			[ <a href="boardList.jsp?pg=<%=endPage+1%>" id="paging"> 다음 </a>]
		<%} %>
	</div>
	<br><br>
	<input type="button" value="main" onclick="location.href='../index.jsp'"/>
	<!-- script -->
	<script type="text/javascript">
		function isLogin(seq) {
			<%if(session.getAttribute("memberId")==null) {%>
				alert("로그인 ㄱ");
				location.href="../member/loginForm.jsp";
			<%}else {%>
				location.href="boardView.jsp?seq="+seq+"&pg="+<%=pg%>;
			<%}%>
		}
	</script>
</body>
</html>
profile
Fintech

0개의 댓글