뷰(view) 확인
list.jsp
<%@page import="kr.gov.mvc.model.BoardDTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String sessionId = (String)session.getAttribute("sessionId");
ArrayList<BoardDTO> boardList = (ArrayList<BoardDTO>)request.getAttribute("boardList");
int totalRecord = ((Integer)request.getAttribute("totalRecord")).intValue();
int totalPage = ((Integer)request.getAttribute("totalPage")).intValue();
int pageNum = ((Integer)request.getAttribute("pageNum")).intValue();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css">
</head>
<body>
<jsp:include page="../menu.jsp"/>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">게시판</h1>
</div>
</div>
<div class="container">
<form action='<c:url value="./boardListAction.do" />' method="post">
<div>
<div class="text-right">
<h2><span class="badge badge-danger">전체 건수 : <%=totalRecord %></span></h2>
</div>
</div>
<div style="padding-top:50px"> <!-- 게시글 표시 -->
<table class="table table-hover">
<tr>
<th>번호</th>
<th>제목</th>
<th>작성일</th>
<th>조회</th>
<th>글쓴이</th>
</tr>
<%
for(int i=0; i<boardList.size(); i++) {
BoardDTO notice = boardList.get(i);
%>
<tr>
<td><%=notice.getNum() %></td>
<!-- 게시글 제목클릭하면 해당 게시글이 보일수 있도록 a태그 이용 -->
<td><a href="./boardViewAction.do?num=<%=notice.getNum() %>"><%=notice.getSubject() %></a></td>
<td><%=notice.getRegistDay() %></td>
<td><%=notice.getHit() %></td>
<td><%=notice.getName() %></td>
</tr>
<%
}
%>
</table>
</div>
<div align="center"> <!-- 페이지 수 표시 -->
<c:set var="pageNum" value="<%=pageNum %>" /> <!-- 페이지수를 jstl로 표시 -->
<c:forEach var="i" begin="1" end="<%=totalPage %>" >
<a href=' <c:url value="./boardListAction.do?pageNum=${i }" />'>
<c:choose>
<c:when test="${pageNum==i }">
<font color="4C5317"><b>[${i }]</b></font>
</c:when>
<c:otherwise>
<font color="4C5317">[${i }]</font>
</c:otherwise>
</c:choose>
</a>
</c:forEach>
</div>
<div align="left"> <!-- 검색 -->
<table>
<tr>
<td width="100%" align="left">
<select name="items" class="txt">
<option value="subject">제목</option>
<option value="content">본문</option>
<option value="name">글쓴이</option>
</select>
<input name="text" type="text" />
<input type="submit" id="btnAdd" class="btn btn-primary btn-sm" value="검색">
</td>
<td width="100%" align="right">
<!-- 로그인 된 회원들만 글쓰기 가능하도록 하기위해서 checkForm()함수추가 -->
<h3><a href="#" onclick="checkForm()" class="badge badge-primary">글쓰기</a></h3>
</td>
</tr>
</table>
</div>
</form>
<hr/>
</div>
<jsp:include page="../footer.jsp" />
<script type="text/javascript">
function checkForm() {
if(${sessionId == null}) { /* 로그인여부 판단 */
alert("로그인해야 작성할수 있습니다");
return false;
}
//로그인되었다면
location.href = "./boardWriteForm.do?id=<%=sessionId %>"
}
</script>
</body>
</html>
게시글의 5건수가 넘어가면 페이징 처리가 된다.
선택한 글 내용보기(상세보기) 추가
프론트 컨트롤러 수정
BoardController.java
package kr.gov.mvc.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.command.BCommand;
import kr.gov.mvc.command.BListCommand;
import kr.gov.mvc.command.BWriteCommand;
import kr.gov.mvc.command.BWriteFormCommand;
/*@WebServlet("/BoardController")*/
public class BoardController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardController() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
actionDo(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
actionDo(request, response);
}
private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("actionDo");
String uri = request.getRequestURI();
System.out.println("URI : " + uri);
String contextPath = request.getContextPath();
System.out.println("contextPath : " + contextPath);
String command = uri.substring(contextPath.length());
System.out.println("command : " + command);
response.setContentType("text/html; charse=utf-8");
request.setCharacterEncoding("UTF-8");
BCommand com = null;
String viewPage = null;
//command 패턴에 따라서 분기함
if(command.equals("/boardListAction.do")) { //DB에 저장되어 있는 모든 게시글 출력
System.out.println("--------------------------------");
System.out.println("/boardListAction.do 페이지 호출");
System.out.println("--------------------------------");
//다시 위임 한것
com = new BListCommand();
com.execute(request, response);
viewPage = "./board/list.jsp";
}
else if(command.equals("/boardWriteForm.do")) { //회원의 로그인 정보 가져오는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteForm.do 페이지 호출");
System.out.println("--------------------------------");
com = new BWriteFormCommand();
com.execute(request, response);
viewPage = "./board/writeForm.jsp";
}
else if(command.equals("/boardWriteAction.do")) { //게시글을 쓰고 DB에 저장하는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteAction.do 페이지 호출");
System.out.println("--------------------------------");
com = new BWriteCommand();
com.execute(request, response);
viewPage = "/boardListAction.do";
}
else if(command.equals("/boardViewAction.do")) { //게시판에 있는 게시물 제목 클릭하여 상세내용보는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteAction.do 페이지 호출");
System.out.println("--------------------------------");
//com = new BViewCommand(); 생성하기
}
//위의 분기문에서 설정된 view(.jsp)파일로 페이지 이동
RequestDispatcher rDispatcher = request.getRequestDispatcher(viewPage);
rDispatcher.forward(request, response);
}
}
커맨드 객체 추가
DB에 저장되어 있는 게시글을 보고자할때 실행하는 커맨드 객체
DAO를 호출해야해서 DAO를 만들어줘야한다..
BViewCommand.jsva
package kr.gov.mvc.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BViewCommand implements BCommand { //DB에 저장되어 있는 게시글을 보고자할때 실행하는 커맨드 객체
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
}
}
DAO 내용추가
BViewCommand.jsva에 사용하기위한 내용 추가
getBoardByNum 메서드 추가
updateHit 조회수 증가시키는 메서드 추가
BoardDAO.java
package kr.gov.mvc.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import kr.gov.mvc.database.DBConnection;
public class BoardDAO {
private Connection conn = null; //DB접속시 필요한 객체
private PreparedStatement pstmt= null;
private ResultSet rs = null;
private ArrayList<BoardDTO> dtos = null;
private static BoardDAO instance;
public BoardDAO() {
// TODO Auto-generated constructor stub
}
public static BoardDAO getInstance() { //싱글톤 패턴으로 BoardDAO객체 하나만 만들어서 리턴.
if(instance == null) {
instance = new BoardDAO();
}
return instance;
}
//board 테이블에 레코드 가져오는 메서드
//page : 게시물 페이지 숫자, limit : 페이지당 게시물 수, items : 제목, 본문, 글쓴이, text : 검색어
public ArrayList<BoardDTO> getBoardList(int page, int limit, String items, String text) {
int totalRecord = getListCount(items, text); //board테이블의 전체 레코드 개수
int start = (page - 1) * limit; //선택 page이전까지의 레코드 개수
int index = start + 1; //선택 page 시작 레코드(게시물)
String sql = "";
dtos = new ArrayList<BoardDTO>();
if(items == null && text == null) { //파라미터로 넘어오는 검색기능이 두군데 모두 아무값이 없는 경우
sql = "select * from board order by num desc";
}
else {
sql = "select * from board where " +items+ " like '%"+text+"%' order by num desc"; //매개변수가 파라미터로 넘어오는 값으로 검색
}
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
while(rs.absolute(index)) { //가령 6페이지를 보고있다가 1페이지를 클릭하게되면 -> 마이너스값이 되면안됨.
BoardDTO board = new BoardDTO();
board.setNum(rs.getInt("num"));
board.setId(rs.getString("id"));
board.setName(rs.getString("name"));
board.setSubject(rs.getString("subject"));
board.setContent(rs.getString("content"));
board.setRegistDay(rs.getString("registDay"));
board.setHit(rs.getInt("hit"));
board.setIp(rs.getString("ip"));
dtos.add(board);
//인덱스가 가져올 데이터건수 보다 작다면
if(index < (start + limit) && index <= totalRecord) {
index ++;
}
else {
break;
}
}
}catch (SQLException e){
System.out.println("getBoardList() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("getBoardList()의 close() 호출 예외" + e2.getMessage());
e2.printStackTrace();
}
}
return dtos;
}
//board 테이블에 레코드 개수를 가져오는 메서드
public int getListCount(String items, String text) {
int count = 0;
String sql = "";
//파라미터로 넘어오는 검색기능 두군데 모두 아무값도 없는 경우
if(items == null && text == null) {
sql = "select count(*) from board";
}
else {
sql = "select count(*) from board where " +items+ "like '%"+text+"%' "; //파라미터로 넘어오는 값으로 검색
}
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()) {
count = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println("getListCount() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("getListCount()의 close() 호출 예외" + e2.getMessage());
e2.printStackTrace();
}
}
return count;
}
//member테이블에서 인증된 id의 사용자명 가져오기
public String getLoginName(String id) {
String name = null;
String sql = "select * from member where id = ?";
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
name = rs.getString("name");
}
} catch (Exception e) {
System.out.println("getLoginName() 예외발생 : " + e.getMessage());
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("getLoginName()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
return name;
}
//board 테이블에 새로운 글 저장하는 메서드
public void insertBoard(BoardDTO boardDTO) {
/*
num int not null auto_increment, -- 게시글 순번
id varchar(10) not null, -- 회원 아이디
name varchar(20) not null, -- 회원 이름
subject varchar(100) not null, -- 게시글 제목
content text not null, -- 게시글 내용
registDay varchar(30), -- 게시글 등록 일자
hit int, -- 게시글 조회수
ip varchar(20), -- 게시글 등록 시 IP
*/
try {
String sql = "insert into board values(?, ?, ?, ?, ?, ?, ?, ?)";
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, boardDTO.getNum());
pstmt.setString(2, boardDTO.getId());
pstmt.setString(3, boardDTO.getName());
pstmt.setString(4, boardDTO.getSubject());
pstmt.setString(5, boardDTO.getContent());
pstmt.setString(6, boardDTO.getRegistDay());
pstmt.setInt(7, boardDTO.getHit());
pstmt.setString(8, boardDTO.getIp());
pstmt.executeUpdate();
} catch (Exception e) {
System.out.println("insertBoard() 예외발생 : " + e.getMessage());
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("insertBoard()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
}
public BoardDTO getBoardByNum(int boardNum, int pageNum) { //선택된 게시글의 상세 내용을 가져오는 메서드
BoardDTO boardDTO = null;
String sql = "select * from board where num = ?";
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, boardNum);
rs = pstmt.executeQuery();
if(rs.next()) {
boardDTO = new BoardDTO();
boardDTO.setNum(rs.getInt("num"));
boardDTO.setId(rs.getString("id"));
boardDTO.setName(rs.getString("name"));
boardDTO.setSubject(rs.getString("subject"));
boardDTO.setContent(rs.getNString("content"));
boardDTO.setRegistDay(rs.getString("registDay"));
boardDTO.setHit(rs.getInt("hit"));
boardDTO.setIp(rs.getString("ip"));
}
System.out.println("getBoardByNum 수행완료");
} catch (Exception e) {
System.out.println("getBoardByNum() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("getBoardByNum()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
updateHit(boardNum); //조회수 증가시키는 메서드
return boardDTO;
}
public void updateHit(int boardNum) { //조회수 증가시키는 메서드
String sql = "select hit from board where num = ?";
int hit = 0;
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, boardNum);
rs = pstmt.executeQuery();
if(rs.next()) {
hit = rs.getInt("hit") + 1;
}
sql = "update board set hit = ? where num = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, hit);
pstmt.setInt(2, boardNum);
pstmt.executeUpdate();
System.out.println("updateHit 수행완료");
} catch (Exception e) {
System.out.println("updateHit() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("updateHit()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
}
}
커맨드 객체 수정
DAO 호출하기 DTO로 받음.
BViewCommand.java
package kr.gov.mvc.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.model.BoardDAO;
import kr.gov.mvc.model.BoardDTO;
public class BViewCommand implements BCommand { //DB에 저장되어 있는 게시글을 보고자할때 실행하는 커맨드 객체
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
BoardDAO bDao = BoardDAO.getInstance();
int num = Integer.parseInt(request.getParameter("num")); //보고자하는 게시글의 번호
int pageNum = Integer.parseInt(request.getParameter("pageNum")); //보고자하는 게시글이 있는 페이지수
BoardDTO boardDTO = new BoardDTO();
boardDTO = bDao.getBoardByNum(num, pageNum);
request.setAttribute("num", num);
request.setAttribute("pageNum", pageNum);
request.setAttribute("boardDTO", boardDTO);
}
}
프론트 컨트롤러 수정
com.execute(request, response); 추가함
뷰페이지 추가함
BoardController.java
package kr.gov.mvc.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.command.BCommand;
import kr.gov.mvc.command.BListCommand;
import kr.gov.mvc.command.BViewCommand;
import kr.gov.mvc.command.BWriteCommand;
import kr.gov.mvc.command.BWriteFormCommand;
/*@WebServlet("/BoardController")*/
public class BoardController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardController() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
actionDo(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
actionDo(request, response);
}
private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("actionDo");
String uri = request.getRequestURI();
System.out.println("URI : " + uri);
String contextPath = request.getContextPath();
System.out.println("contextPath : " + contextPath);
String command = uri.substring(contextPath.length());
System.out.println("command : " + command);
response.setContentType("text/html; charse=utf-8");
request.setCharacterEncoding("UTF-8");
BCommand com = null;
String viewPage = null;
//command 패턴에 따라서 분기함
if(command.equals("/boardListAction.do")) { //DB에 저장되어 있는 모든 게시글 출력
System.out.println("--------------------------------");
System.out.println("/boardListAction.do 페이지 호출");
System.out.println("--------------------------------");
//다시 위임 한것
com = new BListCommand();
com.execute(request, response);
viewPage = "./board/list.jsp";
}
else if(command.equals("/boardWriteForm.do")) { //회원의 로그인 정보 가져오는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteForm.do 페이지 호출");
System.out.println("--------------------------------");
com = new BWriteFormCommand();
com.execute(request, response);
viewPage = "./board/writeForm.jsp";
}
else if(command.equals("/boardWriteAction.do")) { //게시글을 쓰고 DB에 저장하는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteAction.do 페이지 호출");
System.out.println("--------------------------------");
com = new BWriteCommand();
com.execute(request, response);
viewPage = "/boardListAction.do";
}
else if(command.equals("/boardViewAction.do")) { //게시판에 있는 게시물 제목 클릭하여 상세내용보는 부분
System.out.println("--------------------------------");
System.out.println("/boardViewAction.do 페이지 호출");
System.out.println("--------------------------------");
com = new BViewCommand();
com.execute(request, response);
System.out.println("boardViewAction의 execute()실행 완료");
viewPage = "./board/view.jsp";
}
//위의 분기문에서 설정된 view(.jsp)파일로 페이지 이동
RequestDispatcher rDispatcher = request.getRequestDispatcher(viewPage);
rDispatcher.forward(request, response);
}
}
뷰 생성 작성하기 - 글 상세정보
BViewCommand에서 값을 받아온다 getAgetAttribute
session 사용 sessionId값을 받아온다. DB의 userId를 받아 서로 비교해서 같으면 글수정 되게끔 만든다.
수정, 삭제, 목록 버튼추가
글쓴이와 읽는이가 다르다면 제목과 내용이 수정이 불가하게 처리
게시글 작성자가 맞다면 => 수정이 가능하도록 함
view.jsp
<%@page import="kr.gov.mvc.model.BoardDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
BoardDTO notice = (BoardDTO)request.getAttribute("boardDTO");
int num = (Integer)request.getAttribute("num");
int nowPage = (Integer)request.getAttribute("pageNum");
/* System.out.println(notice.getName());
System.out.println(num);
System.out.println(nowPage); */
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>글 상세보기 - WebStore</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css">
</head>
<body>
<jsp:include page="../menu.jsp"/>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">게시판</h1>
</div>
</div>
<div class="container">
<form action="boardUpdateAction.do?num=<%=notice.getNum() %>&pageNum=<%=nowPage %>" name="newUpdate" class="form-horizontal" method="post">
<div class="form-group row">
<label class="col-sm-2 control-label">이름</label>
<div class="col-sm-3">
<input name="name" class="form-control" value="<%=notice.getName() %>" readonly> <!-- DB에 저장되어 있는 이름값 출력 -->
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">제목</label>
<div class="col-sm-3">
<input name="subject" class="form-control" value="<%=notice.getSubject() %>"> <!-- DB에 저장되어 있는 제목 출력 -->
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 control-label">내용</label>
<div class="col-sm-8" style="word-break:break-all">
<textarea rows="5" cols="50" name="content" class="form-control"><%=notice.getContent() %></textarea>
</div>
</div>
</form>
</div>
</body>
</html>
메인 시작점 만들기
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebStore</title>
</head>
<body>
<c:redirect url="welcome.jsp"/>
</body>
</html>
프론트 컨트롤러에 게시글 수정 .do 추가 - 게시글 수정하기
커맨드 객체이 위임 BUpdateCommand.java
BoardController.java
package kr.gov.mvc.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.command.BCommand;
import kr.gov.mvc.command.BListCommand;
import kr.gov.mvc.command.BViewCommand;
import kr.gov.mvc.command.BWriteCommand;
import kr.gov.mvc.command.BWriteFormCommand;
/*@WebServlet("/BoardController")*/
public class BoardController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardController() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
actionDo(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
actionDo(request, response);
}
private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("actionDo");
String uri = request.getRequestURI();
System.out.println("URI : " + uri);
String contextPath = request.getContextPath();
System.out.println("contextPath : " + contextPath);
String command = uri.substring(contextPath.length());
System.out.println("command : " + command);
response.setContentType("text/html; charse=utf-8");
request.setCharacterEncoding("UTF-8");
BCommand com = null;
String viewPage = null;
//command 패턴에 따라서 분기함
if(command.equals("/boardListAction.do")) { //DB에 저장되어 있는 모든 게시글 출력
System.out.println("--------------------------------");
System.out.println("/boardListAction.do 페이지 호출");
System.out.println("--------------------------------");
//다시 위임 한것
com = new BListCommand();
com.execute(request, response);
viewPage = "./board/list.jsp";
}
else if(command.equals("/boardWriteForm.do")) { //회원의 로그인 정보 가져오는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteForm.do 페이지 호출");
System.out.println("--------------------------------");
com = new BWriteFormCommand();
com.execute(request, response);
viewPage = "./board/writeForm.jsp";
}
else if(command.equals("/boardWriteAction.do")) { //게시글을 쓰고 DB에 저장하는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteAction.do 페이지 호출");
System.out.println("--------------------------------");
com = new BWriteCommand();
com.execute(request, response);
viewPage = "/boardListAction.do";
}
else if(command.equals("/boardViewAction.do")) { //게시판에 있는 게시물 제목 클릭하여 상세내용보는 부분
System.out.println("--------------------------------");
System.out.println("/boardViewAction.do 페이지 호출");
System.out.println("--------------------------------");
com = new BViewCommand();
com.execute(request, response);
System.out.println("boardViewAction의 execute()실행 완료");
viewPage = "./board/view.jsp";
}
else if(command.equals("boardUpdateAction.do")) { //게시글 수정
System.out.println("--------------------------------");
System.out.println("/boardUpdateAction.do 페이지 호출");
System.out.println("--------------------------------");
//com = new BUpdateCommand(); 생성후 import
}
//위의 분기문에서 설정된 view(.jsp)파일로 페이지 이동
RequestDispatcher rDispatcher = request.getRequestDispatcher(viewPage);
rDispatcher.forward(request, response);
}
}
커맨드 객체 생성 -
view.jsp에 있는 num 파라미터 값을 받아옴.
dao가 가지고 있는 메서드 호출(화면단에서 게시물의 글과 제목을 바꾸기 위해)
dto 객체 생성
get파라미터의 name속성(입력했던 값)을 이용해서 DTO에 set
BUpdateCommand.java
package kr.gov.mvc.command;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.model.BoardDAO;
import kr.gov.mvc.model.BoardDTO;
public class BUpdateCommand implements BCommand{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
int num = Integer.parseInt(request.getParameter("num"));
BoardDAO bDao = BoardDAO.getInstance();
BoardDTO boardDTO = new BoardDTO();
boardDTO.setNum(num);
boardDTO.setSubject(request.getParameter("subject"));
boardDTO.setContent(request.getParameter("content"));
SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String registDay = sFormat.format(new Date());
boardDTO.setRegistDay(registDay);
boardDTO.setIp(request.getRemoteAddr());
}
}
DAO 수정
업데이트 내용 추가
BoardDAO.java
package kr.gov.mvc.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import kr.gov.mvc.database.DBConnection;
public class BoardDAO {
private Connection conn = null; //DB접속시 필요한 객체
private PreparedStatement pstmt= null;
private ResultSet rs = null;
private ArrayList<BoardDTO> dtos = null;
private static BoardDAO instance;
public BoardDAO() {
// TODO Auto-generated constructor stub
}
public static BoardDAO getInstance() { //싱글톤 패턴으로 BoardDAO객체 하나만 만들어서 리턴.
if(instance == null) {
instance = new BoardDAO();
}
return instance;
}
//board 테이블에 레코드 가져오는 메서드
//page : 게시물 페이지 숫자, limit : 페이지당 게시물 수, items : 제목, 본문, 글쓴이, text : 검색어
public ArrayList<BoardDTO> getBoardList(int page, int limit, String items, String text) {
int totalRecord = getListCount(items, text); //board테이블의 전체 레코드 개수
int start = (page - 1) * limit; //선택 page이전까지의 레코드 개수
int index = start + 1; //선택 page 시작 레코드(게시물)
String sql = "";
dtos = new ArrayList<BoardDTO>();
if(items == null && text == null) { //파라미터로 넘어오는 검색기능이 두군데 모두 아무값이 없는 경우
sql = "select * from board order by num desc";
}
else {
sql = "select * from board where " +items+ " like '%"+text+"%' order by num desc"; //매개변수가 파라미터로 넘어오는 값으로 검색
}
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
while(rs.absolute(index)) { //가령 6페이지를 보고있다가 1페이지를 클릭하게되면 -> 마이너스값이 되면안됨.
BoardDTO board = new BoardDTO();
board.setNum(rs.getInt("num"));
board.setId(rs.getString("id"));
board.setName(rs.getString("name"));
board.setSubject(rs.getString("subject"));
board.setContent(rs.getString("content"));
board.setRegistDay(rs.getString("registDay"));
board.setHit(rs.getInt("hit"));
board.setIp(rs.getString("ip"));
dtos.add(board);
//인덱스가 가져올 데이터건수 보다 작다면
if(index < (start + limit) && index <= totalRecord) {
index ++;
}
else {
break;
}
}
}catch (SQLException e){
System.out.println("getBoardList() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("getBoardList()의 close() 호출 예외" + e2.getMessage());
e2.printStackTrace();
}
}
return dtos;
}
//board 테이블에 레코드 개수를 가져오는 메서드
public int getListCount(String items, String text) {
int count = 0;
String sql = "";
//파라미터로 넘어오는 검색기능 두군데 모두 아무값도 없는 경우
if(items == null && text == null) {
sql = "select count(*) from board";
}
else {
sql = "select count(*) from board where " +items+ "like '%"+text+"%' "; //파라미터로 넘어오는 값으로 검색
}
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()) {
count = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println("getListCount() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("getListCount()의 close() 호출 예외" + e2.getMessage());
e2.printStackTrace();
}
}
return count;
}
//member테이블에서 인증된 id의 사용자명 가져오기
public String getLoginName(String id) {
String name = null;
String sql = "select * from member where id = ?";
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
name = rs.getString("name");
}
} catch (Exception e) {
System.out.println("getLoginName() 예외발생 : " + e.getMessage());
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("getLoginName()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
return name;
}
//board 테이블에 새로운 글 저장하는 메서드
public void insertBoard(BoardDTO boardDTO) {
/*
num int not null auto_increment, -- 게시글 순번
id varchar(10) not null, -- 회원 아이디
name varchar(20) not null, -- 회원 이름
subject varchar(100) not null, -- 게시글 제목
content text not null, -- 게시글 내용
registDay varchar(30), -- 게시글 등록 일자
hit int, -- 게시글 조회수
ip varchar(20), -- 게시글 등록 시 IP
*/
try {
String sql = "insert into board values(?, ?, ?, ?, ?, ?, ?, ?)";
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, boardDTO.getNum());
pstmt.setString(2, boardDTO.getId());
pstmt.setString(3, boardDTO.getName());
pstmt.setString(4, boardDTO.getSubject());
pstmt.setString(5, boardDTO.getContent());
pstmt.setString(6, boardDTO.getRegistDay());
pstmt.setInt(7, boardDTO.getHit());
pstmt.setString(8, boardDTO.getIp());
pstmt.executeUpdate();
} catch (Exception e) {
System.out.println("insertBoard() 예외발생 : " + e.getMessage());
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("insertBoard()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
}
public BoardDTO getBoardByNum(int boardNum, int pageNum) { //선택된 게시글의 상세 내용을 가져오는 메서드
BoardDTO boardDTO = null;
String sql = "select * from board where num = ?";
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, boardNum);
rs = pstmt.executeQuery();
if(rs.next()) {
boardDTO = new BoardDTO();
boardDTO.setNum(rs.getInt("num"));
boardDTO.setId(rs.getString("id"));
boardDTO.setName(rs.getString("name"));
boardDTO.setSubject(rs.getString("subject"));
boardDTO.setContent(rs.getNString("content"));
boardDTO.setRegistDay(rs.getString("registDay"));
boardDTO.setHit(rs.getInt("hit"));
boardDTO.setIp(rs.getString("ip"));
}
System.out.println("getBoardByNum 수행완료");
} catch (Exception e) {
System.out.println("getBoardByNum() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("getBoardByNum()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
updateHit(boardNum); //조회수 증가시키는 메서드
return boardDTO;
}
public void updateHit(int boardNum) { //조회수 증가시키는 메서드
String sql = "select hit from board where num = ?";
int hit = 0;
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, boardNum);
rs = pstmt.executeQuery();
if(rs.next()) {
hit = rs.getInt("hit") + 1;
}
sql = "update board set hit = ? where num = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, hit);
pstmt.setInt(2, boardNum);
pstmt.executeUpdate();
System.out.println("updateHit 수행완료");
} catch (Exception e) {
System.out.println("updateHit() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("updateHit()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
}
public void updateBoard(BoardDTO boardDTO) { //게시글을 수정한 내용 DB에 저장하는 메서드
String sql = "update board set subject = ?, content = ?, registDay = ?, ip = ? where num = ?";
try {
conn = DBConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, boardDTO.getSubject());
pstmt.setString(2, boardDTO.getContent());
pstmt.setString(3, boardDTO.getRegistDay());
pstmt.setString(4, boardDTO.getIp());
pstmt.setInt(5, boardDTO.getNum());
pstmt.executeUpdate();
System.out.println("updateBoard() 수행 완료");
} catch (Exception e) {
System.out.println("updateBoard() 예외발생 : " + e.getMessage());
e.printStackTrace();
}finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("updateBoard()의 close() 호출 예외 : " + e2.getMessage());
e2.printStackTrace();
}
}
}
}
커맨드 객체 수정 - DAO 호출 리턴
BUpdateCommand.java
package kr.gov.mvc.command;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.model.BoardDAO;
import kr.gov.mvc.model.BoardDTO;
public class BUpdateCommand implements BCommand{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
int num = Integer.parseInt(request.getParameter("num"));
BoardDAO bDao = BoardDAO.getInstance();
BoardDTO boardDTO = new BoardDTO();
boardDTO.setNum(num);
boardDTO.setSubject(request.getParameter("subject"));
boardDTO.setContent(request.getParameter("content"));
SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String registDay = sFormat.format(new Date());
boardDTO.setRegistDay(registDay);
boardDTO.setIp(request.getRemoteAddr());
bDao.updateBoard(boardDTO);
}
}
프론트 컨테이너 수정
커맨드 객체 메서드 호출
BoardController.java
package kr.gov.mvc.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.command.BCommand;
import kr.gov.mvc.command.BListCommand;
import kr.gov.mvc.command.BUpdateCommand;
import kr.gov.mvc.command.BViewCommand;
import kr.gov.mvc.command.BWriteCommand;
import kr.gov.mvc.command.BWriteFormCommand;
/*@WebServlet("/BoardController")*/
public class BoardController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardController() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
actionDo(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
actionDo(request, response);
}
private void actionDo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("actionDo");
String uri = request.getRequestURI();
System.out.println("URI : " + uri);
String contextPath = request.getContextPath();
System.out.println("contextPath : " + contextPath);
String command = uri.substring(contextPath.length());
System.out.println("command : " + command);
response.setContentType("text/html; charse=utf-8");
request.setCharacterEncoding("UTF-8");
BCommand com = null;
String viewPage = null;
//command 패턴에 따라서 분기함
if(command.equals("/boardListAction.do")) { //DB에 저장되어 있는 모든 게시글 출력
System.out.println("--------------------------------");
System.out.println("/boardListAction.do 페이지 호출");
System.out.println("--------------------------------");
//다시 위임 한것
com = new BListCommand();
com.execute(request, response);
viewPage = "./board/list.jsp";
}
else if(command.equals("/boardWriteForm.do")) { //회원의 로그인 정보 가져오는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteForm.do 페이지 호출");
System.out.println("--------------------------------");
com = new BWriteFormCommand();
com.execute(request, response);
viewPage = "./board/writeForm.jsp";
}
else if(command.equals("/boardWriteAction.do")) { //게시글을 쓰고 DB에 저장하는 부분
System.out.println("--------------------------------");
System.out.println("/boardWriteAction.do 페이지 호출");
System.out.println("--------------------------------");
com = new BWriteCommand();
com.execute(request, response);
viewPage = "/boardListAction.do";
}
else if(command.equals("/boardViewAction.do")) { //게시판에 있는 게시물 제목 클릭하여 상세내용보는 부분
System.out.println("--------------------------------");
System.out.println("/boardViewAction.do 페이지 호출");
System.out.println("--------------------------------");
com = new BViewCommand();
com.execute(request, response);
System.out.println("boardViewAction의 execute()실행 완료");
viewPage = "./board/view.jsp";
}
else if(command.equals("boardUpdateAction.do")) { //게시글 수정
System.out.println("--------------------------------");
System.out.println("/boardUpdateAction.do 페이지 호출");
System.out.println("--------------------------------");
com = new BUpdateCommand();
com.execute(request, response);
System.out.println("boardUpdateAction의 execute()실행 완료");
viewPage = "/boardListAction.do";
}
//위의 분기문에서 설정된 view(.jsp)파일로 페이지 이동
RequestDispatcher rDispatcher = request.getRequestDispatcher(viewPage);
rDispatcher.forward(request, response);
}
}
view 실행 - index.jsp 수정기능 확인하기