list.jsp (view) 수정
form action boardListAction.do 추가 list.jsp 다시 불러옴
게시글 표시
페이지 표시
검색 기능 표시
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" 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>
프런트 컨트롤러(controller) 수정, 커맨드 객체 추가
로그인 정보 가져오는 boardWriteForm.do
글쓰기 클릭 후 로그인한 사람만 쓸 수 있게 함.
boardWriteForm.do 받는다.
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.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();
}
//위의 분기문에서 설정된 view(.jsp)파일로 페이지 이동
RequestDispatcher rDispatcher = request.getRequestDispatcher(viewPage);
rDispatcher.forward(request, response);
}
}
게시판의 게시글 작성 위해서 사용자명을 가져오는 커맨드 객체 BWriteFormCommand.java 생성
BWriteFormCommand.java
package kr.gov.mvc.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.model.BoardDAO;
// 게시판의 게시글 작성위해서 사용자명을 가져오는 커맨드 객체
public class BWriteFormCommand implements BCommand{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
BoardDAO bDao = BoardDAO.getInstance();
String id = request.getParameter("id");
}
}
DAO (model) 수정
로그인 정보에서 사용자명 가져오는 메서드 getLoginName() 추가
e.printStackTrace() 끝나고 주석처리해줘야 한다.
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;
}
}
커맨드 객체(model) 에서 DAO 호출하기
dao의 getLoginName() 메서드를 호출함
BWriteFormCommand.java
package kr.gov.mvc.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.gov.mvc.model.BoardDAO;
// 게시판의 게시글 작성위해서 사용자명을 가져오는 커맨드 객체
public class BWriteFormCommand implements BCommand{
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
System.out.println("BWriteFormCommand 클래스 들어옴");
BoardDAO bDao = BoardDAO.getInstance();
String id = request.getParameter("id");
String name = bDao.getLoginName(id);
request.setAttribute("name", name);
System.out.println("BWriteFormCommand 클래스 실행후 나감");
}
}
프런트 컨트롤러(controller) 수정 - 화면 처리하기 위해서
커맨드 객체의 excute 추가
뷰 페이지에 포워딩 writeForm, jsp 추가
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.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";
}
//위의 분기문에서 설정된 view(.jsp)파일로 페이지 이동
RequestDispatcher rDispatcher = request.getRequestDispatcher(viewPage);
rDispatcher.forward(request, response);
}
}
뷰(view) 작성하기
게시글을 작성하는 jsp 페이지
writeForm,jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
String name = (String)request.getAttribute("name");
System.out.println("writeForm.jsp진입");
%>
<!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="./boardWriteAction.do" name="newWrite" class="form-horizontal" method="get"
onsubmit="return checkForm()" >
<input name="id" type="hidden" class="form-control" value="${sessionId }">
<div class="form-group row">
<label class="col-sm-2 control-label">이름</label> <!-- 게시글 작성자 이름 표시 -->
<div class="col-sm-3">
<input name="name" type="text" class="form-control" value="${name }" readonly>
</div>
</div>
<div class="form-group row"> <!-- 게시글의 제목 표시 -->
<label class="col-sm-2 control-label">제목</label>
<div class="col-sm-5">
<input name="subject" type="text" class="form-control" placeholder="제목을 입력하세요.">
</div>
</div>
<div class="form-group row"> <!-- 게시글의 내용 표시 -->
<label class="col-sm-2 control-label">내용</label>
<div class="col-sm-8">
<textarea rows="5" cols="50" name="content" class="form-control"
placeholder="내용을 입력하세요."></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="등록" >
<input type="reset" class="btn btn-danger" value="취소">
</div>
</div>
</form>
<hr/>
</div>
<jsp:include page="../footer.jsp"/>
<script type="text/javascript">
function checkForm() {
if(!document.newWrite.subject.vlaue) {
alert("제목을 입력하세요.");
return false;
}
if(!document.newWrite.content.vlaue) {
alert("내용을 입력하세요.");
return false;
}
}
</script>
</body>
</html>
프런트 컨트롤러(controller)에 boardWriteAction.do 게시글 쓰고 DB 저장하는 호출 부분 추가
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);
//미작성
}
//위의 분기문에서 설정된 view(.jsp)파일로 페이지 이동
RequestDispatcher rDispatcher = request.getRequestDispatcher(viewPage);
rDispatcher.forward(request, response);
}
}
DAO (model) 수정
board 테이블에 새로운 글 저장하는 메서드 추가 (처리 리턴 값이 void)
사용자에게 입력된 값 파라미터로 넘겼다. DAO insertBoard 메서드에서 boardDTO파라미터로 사용
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();
}
}
}
}
커맨드 객체 작성 (model) -> 게시글을 작성하고 그 게시글을 DB에 저장해주는 커맨드 객체
DAO insertBoard() 메서드 받아서 구현
getRemoteAddr => ip가 찍히는 메서드
insertBoard() 메서드를 사욯해서DAO에 값을 다시 넘겨준다.
BWriteCommand.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 BWriteCommand implements BCommand{ //게시글을 작성하고 그 게시글을 DB에 저장해주는 커맨드 객체
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
System.out.println("BWriteCommand클래스 들어옴");
BoardDAO bDAO = BoardDAO.getInstance();
BoardDTO boardDTO = new BoardDTO();
boardDTO.setId(request.getParameter("id"));
boardDTO.setName(request.getParameter("name"));
boardDTO.setSubject(request.getParameter("subject"));
boardDTO.setContent(request.getParameter("content"));
/*
registDay varchar(30), -- 게시글 등록 일자
hit int, -- 게시글 조회수
ip varchar(20), -- 게시글 등록 시 IP
*/
SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
String registDay = sFormat.format(new Date());
boardDTO.setRegistDay(registDay);
boardDTO.setHit(0);
boardDTO.setIp(request.getRemoteAddr());
bDAO.insertBoard(boardDTO); //DB에 저장하는 메서드 호출
System.out.println("BWriteCommand클래스 실행후 나감");
}
}
프런트 컨트롤러(controller) 결괏값 처리, 화면단 처리 추가
글쓰기가 완료되면 어떤 화면으로 보일지 정의 -> boardListAction.do로 지정함
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";
}
//위의 분기문에서 설정된 view(.jsp)파일로 페이지 이동
RequestDispatcher rDispatcher = request.getRequestDispatcher(viewPage);
rDispatcher.forward(request, response);
}
}
뷰 (view) 실행 - 게시글 입력 후 등록, 목록에 추가
writeForm,jsp
게시글 추가가 정상적으로 진행되는 것을 확인