1. 게시판을 만들기 위해 테이블을 먼저 생성한다.
create table board(
no number,
title varchar2(150) not null,
writer varchar2(30) not null,
content varchar2(4000) not null,
writedate varchar2(14) not null,
viewcount number not null,
--답변과 관련된 속성
refamily number not null,
restep number not null,
relevel number not null,
constraint board_pk primary key(no)
)
2. 시퀀스(게시글번호)를 위해 시퀀스 번호를 생성한다.
select board_no_seq.nextval from dual;
3. 데이터 값을 담아둘 dto를 만든다.
board.dto
package board.dto;
public class BoardDTO {
private int no;
private String title;
private String writer;
private String content;
private String writedate;
private int viewcount;
private int refamily;
private int restep;
private int relevel;
public BoardDTO() {
super();
}
public BoardDTO(String title, String writer, String content) {
super();
this.title = title;
this.writer = writer;
this.content = content;
}
public BoardDTO(int no, String title, String writer, String content,
String writedate, int viewcount, int refamily, int restep,
int relevel) {
super();
this.no = no;
this.title = title;
this.writer = writer;
this.content = content;
this.writedate = writedate;
this.viewcount = viewcount;
this.refamily = refamily;
this.restep = restep;
this.relevel = relevel;
}
public BoardDTO(int no, String title, String writer, String content,
String writedate, int viewcount) {
super();
this.no = no;
this.title = title;
this.writer = writer;
this.content = content;
this.writedate = writedate;
this.viewcount = viewcount;
}
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getWritedate() {
return writedate;
}
public void setWritedate(String writedate) {
this.writedate = writedate;
}
public int getViewcount() {
return viewcount;
}
public void setViewcount(int viewcount) {
this.viewcount = viewcount;
}
public int getRefamily() {
return refamily;
}
public void setRefamily(int refamily) {
this.refamily = refamily;
}
public int getRestep() {
return restep;
}
public void setRestep(int restep) {
this.restep = restep;
}
public int getRelevel() {
return relevel;
}
public void setRelevel(int relevel) {
this.relevel = relevel;
}
@Override
public String toString() {
return "BoardDTO [no=" + no + ", title=" + title + ", writer=" + writer
+ ", content=" + content + ", writedate=" + writedate
+ ", viewcount=" + viewcount + ", refamily=" + refamily
+ ", restep=" + restep + ", relevel=" + relevel + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + no;
result = prime * result + refamily;
result = prime * result + relevel;
result = prime * result + restep;
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + viewcount;
result = prime * result
+ ((writedate == null) ? 0 : writedate.hashCode());
result = prime * result + ((writer == null) ? 0 : writer.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BoardDTO other = (BoardDTO) obj;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (no != other.no)
return false;
if (refamily != other.refamily)
return false;
if (relevel != other.relevel)
return false;
if (restep != other.restep)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (viewcount != other.viewcount)
return false;
if (writedate == null) {
if (other.writedate != null)
return false;
} else if (!writedate.equals(other.writedate))
return false;
if (writer == null) {
if (other.writer != null)
return false;
} else if (!writer.equals(other.writer))
return false;
return true;
}
}
package board.dto;
public class BoardDTO {
private int no;
private String title;
private String writer;
private String content;
private String writedate;
private int viewcount;
private int refamily;
private int restep;
private int relevel;
public BoardDTO() {
super();
}
public BoardDTO(String title, String writer, String content) {
super();
this.title = title;
this.writer = writer;
this.content = content;
}
public BoardDTO(int no, String title, String writer, String content,
String writedate, int viewcount, int refamily, int restep,
int relevel) {
super();
this.no = no;
this.title = title;
this.writer = writer;
this.content = content;
this.writedate = writedate;
this.viewcount = viewcount;
this.refamily = refamily;
this.restep = restep;
this.relevel = relevel;
}
public BoardDTO(int no, String title, String writer, String content,
String writedate, int viewcount) {
super();
this.no = no;
this.title = title;
this.writer = writer;
this.content = content;
this.writedate = writedate;
this.viewcount = viewcount;
}
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getWritedate() {
return writedate;
}
public void setWritedate(String writedate) {
this.writedate = writedate;
}
public int getViewcount() {
return viewcount;
}
public void setViewcount(int viewcount) {
this.viewcount = viewcount;
}
public int getRefamily() {
return refamily;
}
public void setRefamily(int refamily) {
this.refamily = refamily;
}
public int getRestep() {
return restep;
}
public void setRestep(int restep) {
this.restep = restep;
}
public int getRelevel() {
return relevel;
}
public void setRelevel(int relevel) {
this.relevel = relevel;
}
@Override
public String toString() {
return "BoardDTO [no=" + no + ", title=" + title + ", writer=" + writer
+ ", content=" + content + ", writedate=" + writedate
+ ", viewcount=" + viewcount + ", refamily=" + refamily
+ ", restep=" + restep + ", relevel=" + relevel + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((content == null) ? 0 : content.hashCode());
result = prime * result + no;
result = prime * result + refamily;
result = prime * result + relevel;
result = prime * result + restep;
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + viewcount;
result = prime * result
+ ((writedate == null) ? 0 : writedate.hashCode());
result = prime * result + ((writer == null) ? 0 : writer.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BoardDTO other = (BoardDTO) obj;
if (content == null) {
if (other.content != null)
return false;
} else if (!content.equals(other.content))
return false;
if (no != other.no)
return false;
if (refamily != other.refamily)
return false;
if (relevel != other.relevel)
return false;
if (restep != other.restep)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (viewcount != other.viewcount)
return false;
if (writedate == null) {
if (other.writedate != null)
return false;
} else if (!writedate.equals(other.writedate))
return false;
if (writer == null) {
if (other.writer != null)
return false;
} else if (!writer.equals(other.writer))
return false;
return true;
}
}
4. * utility 만들기
class
package : board.util
name : DBUtil
Utilities
package board.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
//싱글톤 패턴
public class DBUtil {
private BasicDataSource dataSource;//객체 생성 -> 생성자
private static DBUtil instance = new DBUtil();
private DBUtil(){
dataSource = new BasicDataSource();
//프라퍼티 설정
//1. 연결할 DB와 관련된 설정
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");//BasicDataSource를 사용하면 따로 드라이버 로딩을 해줄 필요가 없다. 바로 처리가능
dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:XE");
dataSource.setUsername("scott");
dataSource.setPassword("tiger");
}
public static DBUtil getInstance(){
return instance;
}
public BasicDataSource getDataSource(){
return dataSource;
}
public void close(Connection conn, PreparedStatement pstmt)throws SQLException{
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
}
public void close(Connection conn, PreparedStatement pstmt, ResultSet rset)throws SQLException{
if(rset!=null){
rset.close();
}
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
}
}
package board.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Utilities {
//글목록에서 한페이지에 보여질 게시물의 개수
public static final int CONTENT_PER_PAGE = 10;
//한 페이지 그룹으로 묶을 페이지의 개수
public static final int PAGE_PER_PAGEGROUP = 10;
//생성자( Utilities객체의 메소드가 전부 static이어서 객체를 생성할 필요가 없어서 생성자를 private로 막았다. )
private Utilities(){
}
/**
* 호출된 시점의 일시를 14자리 String 값으로 만들어 return
* 예) 20120512100524 (yyyyMMddHHmmss)
* @return
*/
public static String getNow(){
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
return simpleDateFormat.format(date);
}
/**
* 인수로 14자리 형태 일시를 받아 날짜만 yyyy.MM.dd 형태의 String으로 만들어 return
* - 목록에서 작성일시를 보여줄때 사용할 메소드
* 예) 20120512100524 -> 2012.05.12
* @param dateTime
* @return
*/
public static String changeDayFormat(String dateTime){
return dateTime.substring(0, 4)+"."+dateTime.substring(4, 6)+"."+dateTime.substring(6, 8);
// SimpleDateFormat sf = new SimpleDateFormat("yyyy.MM.dd");
// String changeDay = sf.format(dateTime); //이렇게 하면 넘어오는 dateTime이 String값이어서 실행시점에 에러가 난다. sf.format(dateTime)의 dateTime은 Date객체가 들어가야 한다.
//
// return changeDay;
}
/**
* 인수로 14자리 형태의 일시를 받아 yyyy.MM.dd HH:mm:ss 형태의 String으로 만들어 return
* - 글 상세보기에서 사용할 메소드
* 예)20120512100524 -> 2012.05.12 10:05:24
* @param dateTime
* @return
*/
public static String changeDayTimeFormat(String dateTime){
return dateTime.substring(0, 4)+"."+dateTime.substring(4, 6)+"."+dateTime.substring(6, 8)+" "+dateTime.substring(8, 10)+":"+dateTime.substring(10, 12)+":"+ dateTime.substring(12, 14);
}
/**
* TextArea에서 입력 받은 글 내용을 HTML로 출력 될 때에 맞는 형식으로 변경하는 메소드
* 새글등록, 답변글등록, 글 수정시 사용
* > - >
* < - <
* \n - <br>
* 공백 -
*/
public static String changeContentForDB(String content){
//변환 시 순서가 중요
String newContent = content.replaceAll(">", ">");
newContent = newContent.replaceAll("<","<");
newContent = newContent.replaceAll(" "," ");
newContent = newContent.replaceAll("\n","<br>");
return newContent;
}
/**
* DB 에 저장된 content를 TextArea에 출력할 형식으로 변경
* 글수정 폼, 답글 폼 출력시 사용
* <br> - \n
* > ->
* < - <
* - 공백
*/
public static String changeContentForTextArea(String content){
String newContent = content.replaceAll("<br>","\n");
newContent = newContent.replaceAll(">",">");
newContent = newContent.replaceAll("<","<");
newContent = newContent.replaceAll(" "," ");
return newContent;
}
}
5. service만들기
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
}
6. controller 만들기
interface
package : board.controller
name : Controller
package board.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.ForwardDTO;
public interface Controller {
public ForwardDTO execute(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException;
}
class : ControlerCommandMapping
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
return ctr;
}
}
servlet
package : board.controller
name : BoardFrontController : mapping - /boardController
package board.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 board.dto.ForwardDTO;
public class BoardFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardFrontController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 공통 사전 작업 - 한글처리
request.setCharacterEncoding("utf-8");
//2. Controller 로직 처리 - Controller객체.execute()호출
String command = request.getParameter("command");
Controller ctr = ControllerCommandMapping.getController(command);
ForwardDTO fdto = ctr.execute(request, response);
//3. 공통 사후 작업
if(fdto.isRedirect()){
response.sendRedirect(fdto.getUrl());
}else{
RequestDispatcher rdp = request.getRequestDispatcher(fdto.getUrl());
rdp.forward(request, response);
}
}
}
* 위와 같이 하면 기본적으로 DB연동할 준비를 하고 패턴을사용하고 기본 함수를 완성해 둔 것임
7. 새 글작성을 한다.
- ${initParam.context_root }를 사용하기 위해 web.xml에 아래와 같이 적어 넣는다.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>board_fc_test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>context_root</param-name>
<param-value>board_fc_test</param-value>
</context-param>
<servlet>
<description></description>
<display-name>BoardFrontController</display-name>
<servlet-name>BoardFrontController</servlet-name>
<servlet-class>board.controller.BoardFrontController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BoardFrontController</servlet-name>
<url-pattern>/boardController</url-pattern>
</servlet-mapping>
</web-app>
- write_form.jsp를 만든다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>write.jsp</h1>
<p>
<h3>글쓰기</h3>
<p>
<form action="/${initParam.context_root }/boardController" method="post">
<input type="hidden" name="command" value="write_content">
<table>
<tr>
<td width="100px">제목</td>
<td><input type="text" name="title" size="50"></td>
</tr>
<tr>
<td>작성자</td>
<td><input type="text" name="writer" size="10" maxlength="10"></td>
</tr>
<tr>
<td colspan="2"><textarea cols="50" rows="10" name="content"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="등록">
<input type="reset" value="초기화">
</td>
</tr>
</table>
</form>
</body>
</html>
- boardController 전송을 누르면 연결 시킨다.
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write_content")){
ctr = new WriteContentController();
}
return ctr;
}
}
4. 실제로 WriteContentController()를 만든다.
controller -> BoardController -> WriteContentController
package board.controller;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.BoardDTO;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class WriteContentController implements Controller{
//controller에서는 클라이언트가 보낸 값을 읽어서 비지니스 로직단에 넘겨주고, 비지니스 서비스 쪽에서 DB에서 값을 얻어오고 초기 값을 설정해 준다.
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//1, client가 보낸 요청 파라미터 조회
String title = request.getParameter("title");
String writer = request.getParameter("writer");
String content = request.getParameter("content");
BoardDTO bto = new BoardDTO(title, writer, content);
//2. 비지니스 로직 - Model(Business Service)로 요청
BoardService boardService = BoardService.getInstance();
ForwardDTO forwardDTO = null;
try {
boardService.writeContent(bto);
request.setAttribute("board",bto);
forwardDTO = new ForwardDTO("/show_content.jsp",false);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
- 서비스를 통해 DB와 연결하여 값을 얻어오게 한다.
BusinessService -> BoardService.writeContent(BoardDTO)
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
public void writeContent(BoardDTO bto)throws SQLException{
/*
* 1. bto에 property 설정 - no, writedate, content
* no - sequence의 값 - dao.selectBoardNO();
* writedate - Utilities.getNow();
* content를 DB에 넣는 용으로 변경 Utilities.changeContentForDB();
* bdto의 refamily에 no 값을 설정
* 2. dao.insertContent(bto);
* 3. 날짜 형태를 년.월.일 시:분:초 형태로 변경 - bto의 property 변경
* Utilities.changeDayTimeFormat();
*/
//1
int no = dao.selectBoardNo();
String writedate = Utilities.getNow();
bto.setNo(no);
bto.setWritedate(writedate);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
bto.setRefamily(no);
//2
dao.insertContent(bto);
//3
bto.setWritedate(Utilities.changeDayTimeFormat(writedate));
}
}
- DB에서값을 얻어온다. dao 작성
DAO -> BoardDAO.selectBoardNo : 글번호 조회
BoardDAO.insertContent(BoardDTO) - 새글, 답변글
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import board.dto.BoardDTO;
import board.util.DBUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private DBUtil dbUtil;
private BoardDAO() {
dbUtil = DBUtil.getInstance();
}
public static BoardDAO getInstance() {
return instance;
}
public int selectBoardNo() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select board_no_seq.nextval from dual";
int no = 0;
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
if (rset.next()) {
no = rset.getInt(1);
}
} finally {
dbUtil.close(conn, pstmt, rset);
}
return no;
}
public void insertContent(BoardDTO bto) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into board (no, title, writer, content, writedate, viewcount, refamily, restep, relevel) values(?,?,?,?,?,0,?,?,?)";
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bto.getNo());
pstmt.setString(2, bto.getTitle());
pstmt.setString(3, bto.getWriter());
pstmt.setString(4, bto.getContent());
pstmt.setString(5, bto.getWritedate());
//viewcount값은 처음 등록하면 무조건 0이라서 쿼리에서 부터 그냥 값을 넣어줬다
// pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(6, bto.getRefamily());
pstmt.setInt(7, bto.getRestep());
pstmt.setInt(8, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "개의 행이 삽입되었습니다.");
} finally {
dbUtil.close(conn, pstmt);
}
}
}
- 화면을 만든다.
응답 -> show_content.jsp : 정상처리
error.jsp : 오류 발생시
<%@page import="board.dto.BoardDTO"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글내용</title>
<style type="text/css">
div{
width:600px;
border:1px solid gray;
padding : 5px;
}
#title{
font-weight: bold;
background-color: yellow;
}
#info{
font-size:13px;
}
#content{
min-height:300px;
height:auto;
}
</style>
</head>
<body>
<h1>글목록</h1>
<p>
<div id="title">${requestScope.board.no}.${requestScope.board.title }</div>
<div id="info">작성자 : ${requestScope.board.writer } | 조회수 : ${requestScope.board.viewcount } 작성일시 : ${requestScope.board.writedate }</div>
<div id="content">${requestScope.board.content }</div>
<p>
<a href="/${initParam.context_root }/write_form.jsp">글쓰기</a>
<a href="/${initParam.context_root }/boardController?command=list_all">전체 글목록</a>
<a href="">글목록(페이징)</a>
<a href="/${initParam.context_root }/boardController?command=modify_form&no=${requestScope.board.no}">글수정</a>
<a href="/${initParam.context_root }/boardController?command=delete_content&no=${requestScope.board.no}">글삭제</a>
<a href="/${initParam.context_root }/boardController?command=reply_form&no=${requestScope.board.no}">답변</a>
</body>
</html>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:if test="${requestScope.error_message!=null }">
실행 도중 오류가 발생했습니다.<br>
오류 내용 ${error_message }
</c:if>
<a href='/${initParam.context_root }/show_content.jsp'>메인페이지로 이동</a>
</body>
</html>
* BoardService와 BoardDAO는 싱글턴패턴으로 만들어라.
* lib에 javax.servlet.jsp.jstl-1.2.1.jar, javax.servlet.jsp.jstl-api-1.2.1.jar 넣기
* 결과
* 전체 글목록 조회(no paging)
시작 : show_content.jsp - 링크(command=list_all)
Ctr : BoardAllListController.execute()
BoardService : getBoardAllList() : ArrayList<BoardDTO>
BoardDAO : selectBoardAllList() : ArrayList<BoardDTO
- 정렬 : refamily 내림차순(desc)
응답 : list_all.jsp
시작 : show_content.jsp - 링크(command=list_all)
<%@page import="board.dto.BoardDTO"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글내용</title>
<style type="text/css">
div{
width:600px;
border:1px solid gray;
padding : 5px;
}
#title{
font-weight: bold;
background-color: yellow;
}
#info{
font-size:13px;
}
#content{
min-height:300px;
height:auto;
}
</style>
</head>
<body>
<h1>글목록</h1>
<p>
<div id="title">${requestScope.board.no}.${requestScope.board.title }</div>
<div id="info">작성자 : ${requestScope.board.writer } | 조회수 : ${requestScope.board.viewcount } 작성일시 : ${requestScope.board.writedate }</div>
<div id="content">${requestScope.board.content }</div>
<p>
<a href="/${initParam.context_root }/write_form.jsp">글쓰기</a>
<a href="/${initParam.context_root }/boardController?command=list_all">전체 글목록</a>
<a href="">글목록(페이징)</a>
<a href="/${initParam.context_root }/boardController?command=modify_form&no=${requestScope.board.no}">글수정</a>
<a href="/${initParam.context_root }/boardController?command=delete_content&no=${requestScope.board.no}">글삭제</a>
<a href="/${initParam.context_root }/boardController?command=reply_form&no=${requestScope.board.no}">답변</a>
</body>
</html>
- Ctr : BoardAllListController.execute()
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write_content")){
ctr = new WriteContentController();
}else if(command.equals("list_all")){
ctr = new BoardAllListController();
}
return ctr;
}
}
package board.controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.BoardDTO;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class BoardAllListController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//1. 비지니스 로직 - Model(Business Service)로 요청
BoardService boardService = BoardService.getInstance();
ForwardDTO forwardDTO = null;
try {
ArrayList<BoardDTO> list_all = boardService.getBoardAllList();
request.setAttribute("list_all",list_all);
forwardDTO = new ForwardDTO("/list_all.jsp",false);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
- service
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
public void writeContent(BoardDTO bto)throws SQLException{
/*
* 1. bto에 property 설정 - no, writedate, content
* no - sequence의 값 - dao.selectBoardNO();
* writedate - Utilities.getNow();
* content를 DB에 넣는 용으로 변경 Utilities.changeContentForDB();
* bdto의 refamily에 no 값을 설정
* 2. dao.insertContent(bto);
* 3. 날짜 형태를 년.월.일 시:분:초 형태로 변경 - bto의 property 변경
* Utilities.changeDayTimeFormat();
*/
//1
int no = dao.selectBoardNo();
String writedate = Utilities.getNow();
bto.setNo(no);
bto.setWritedate(writedate);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
bto.setRefamily(no);
//2
dao.insertContent(bto);
//3
bto.setWritedate(Utilities.changeDayTimeFormat(writedate));
}
//글목록
public ArrayList<BoardDTO> getBoardAllList() throws SQLException{
//1. dao로 부터 전체 글내용을 ArrayList로 조회
ArrayList<BoardDTO> list_all = dao.selectBoardAllList();
//2. list내의 BoardDTO객체들의 wrtiedate를 변경
for(int i=0;i<list_all.size();i++){
list_all.get(i).setWritedate(Utilities.changeDayFormat(list_all.get(i).getWritedate()));
}
return list_all;
}
}
- dao
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import board.dto.BoardDTO;
import board.util.DBUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private DBUtil dbUtil;
private BoardDAO() {
dbUtil = DBUtil.getInstance();
}
public static BoardDAO getInstance() {
return instance;
}
public int selectBoardNo() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select board_no_seq.nextval from dual";
int no = 0;
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
if (rset.next()) {
no = rset.getInt(1);
}
} finally {
dbUtil.close(conn, pstmt, rset);
}
return no;
}
public void insertContent(BoardDTO bto) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into board (no, title, writer, content, writedate, viewcount, refamily, restep, relevel) values(?,?,?,?,?,0,?,?,?)";
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bto.getNo());
pstmt.setString(2, bto.getTitle());
pstmt.setString(3, bto.getWriter());
pstmt.setString(4, bto.getContent());
pstmt.setString(5, bto.getWritedate());
//viewcount값은 처음 등록하면 무조건 0이라서 쿼리에서 부터 그냥 값을 넣어줬다
// pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(6, bto.getRefamily());
pstmt.setInt(7, bto.getRestep());
pstmt.setInt(8, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "개의 행이 삽입되었습니다.");
} finally {
dbUtil.close(conn, pstmt);
}
}
public ArrayList<BoardDTO> selectBoardAllList() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board order by refamily desc, restep asc";
ArrayList<BoardDTO> list_all = new ArrayList<BoardDTO>();
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
list_all.add(new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9)));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return list_all;
}
}
- list_all.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>전체목록보기</title>
</head>
<style type="text/css">
table{
width : 650px;
border-collapse: collapse;
}
td{
padding: 5px;
}
</style>
<body>
<h2>글목록</h2>
<p>
<table border="1" width="800">
<tr align="center" style="font-weight: bold" bgcolor="yellow">
<td width="65px">글번호</td>
<td width="300">제목</td>
<td width="80px">작성자</td>
<td width="60">작성일</td>
<td width="60">조회수</td>
</tr>
<c:forEach items="${requestScope.list_all }" var="list_all">
<tr>
<td>${list_all.no }</td>
<td>
<c:if test="${list_all.relevel!=0 }">
<c:forEach begin="1" end="${list_all.relevel }" step="1">
</c:forEach>
ㄴ
</c:if>
<a href="/${initParam.context_root }/boardController?command=get_content&no=${list_all.no}">${list_all.title }</a></td>
<td>${list_all.writer }</td>
<td>${list_all.writedate }</td>
<td>${list_all.viewcount }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
* 결과
- 제목으로 검색하기
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>전체목록보기</title>
</head>
<style type="text/css">
table{
width : 650px;
border-collapse: collapse;
}
td{
padding: 5px;
}
</style>
<body>
<h2>글목록</h2>
<p>
<table border="1" width="800">
<tr align="center" style="font-weight: bold" bgcolor="yellow">
<td width="65px">글번호</td>
<td width="300">제목</td>
<td width="80px">작성자</td>
<td width="60">작성일</td>
<td width="60">조회수</td>
</tr>
<c:forEach items="${requestScope.list_all }" var="list_all">
<tr>
<td>${list_all.no }</td>
<td>
<c:if test="${list_all.relevel!=0 }">
<c:forEach begin="1" end="${list_all.relevel }" step="1">
</c:forEach>
ㄴ
</c:if>
<a href="/${initParam.context_root }/boardController?command=get_content&no=${list_all.no}">${list_all.title }</a></td>
<td>${list_all.writer }</td>
<td>${list_all.writedate }</td>
<td>${list_all.viewcount }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
package board.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 board.dto.ForwardDTO;
public class BoardFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardFrontController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 공통 사전 작업 - 한글처리
request.setCharacterEncoding("utf-8");
//2. Controller 로직 처리 - Controller객체.execute()호출
String command = request.getParameter("command");
Controller ctr = ControllerCommandMapping.getController(command);
ForwardDTO fdto = ctr.execute(request, response);
//3. 공통 사후 작업
if(fdto.isRedirect()){
response.sendRedirect(fdto.getUrl());
}else{
RequestDispatcher rdp = request.getRequestDispatcher(fdto.getUrl());
rdp.forward(request, response);
}
}
}
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write_content")){
ctr = new WriteContentController();
}else if(command.equals("list_all")){
ctr = new BoardAllListController();
}else if(command.equals("get_content")){
ctr = new GetContentController();
}
return ctr;
}
}
package board.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.BoardDTO;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class GetContentController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//글번로를 받아 글의 벙보를 조회하는 컨트롤러
BoardService boardService = BoardService.getInstance();
ForwardDTO forwardDTO = null;
int no = Integer.parseInt(request.getParameter("no"));
try{
BoardDTO get_content = boardService.getContentByNO(no);
request.setAttribute("board", get_content);
forwardDTO = new ForwardDTO("/show_content.jsp",false);
} catch(Exception e){
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
public void writeContent(BoardDTO bto)throws SQLException{
/*
* 1. bto에 property 설정 - no, writedate, content
* no - sequence의 값 - dao.selectBoardNO();
* writedate - Utilities.getNow();
* content를 DB에 넣는 용으로 변경 Utilities.changeContentForDB();
* bdto의 refamily에 no 값을 설정
* 2. dao.insertContent(bto);
* 3. 날짜 형태를 년.월.일 시:분:초 형태로 변경 - bto의 property 변경
* Utilities.changeDayTimeFormat();
*/
//1
int no = dao.selectBoardNo();
String writedate = Utilities.getNow();
bto.setNo(no);
bto.setWritedate(writedate);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
bto.setRefamily(no);
//2
dao.insertContent(bto);
//3
bto.setWritedate(Utilities.changeDayTimeFormat(writedate));
}
//글목록
public ArrayList<BoardDTO> getBoardAllList() throws SQLException{
//1. dao로 부터 전체 글내용을 ArrayList로 조회
ArrayList<BoardDTO> list_all = dao.selectBoardAllList();
//2. list내의 BoardDTO객체들의 wrtiedate를 변경
for(int i=0;i<list_all.size();i++){
list_all.get(i).setWritedate(Utilities.changeDayFormat(list_all.get(i).getWritedate()));
}
return list_all;
}
public BoardDTO getContentByNO(int no) throws SQLException{
//1.조회수 증가
dao.updateViewCount(no);
//2. no로 글 정보 조회
BoardDTO bto = dao.selectContentByNO(no);
//2-1 writedate를 yyy.MM.dd HH:mm:ss 형식으로 변경
bto.setWritedate(Utilities.changeDayTimeFormat(bto.getWritedate()));
return bto;
}
}
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import board.dto.BoardDTO;
import board.util.DBUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private DBUtil dbUtil;
private BoardDAO() {
dbUtil = DBUtil.getInstance();
}
public static BoardDAO getInstance() {
return instance;
}
public int selectBoardNo() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select board_no_seq.nextval from dual";
int no = 0;
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
if (rset.next()) {
no = rset.getInt(1);
}
} finally {
dbUtil.close(conn, pstmt, rset);
}
return no;
}
public void insertContent(BoardDTO bto) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into board (no, title, writer, content, writedate, viewcount, refamily, restep, relevel) values(?,?,?,?,?,0,?,?,?)";
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bto.getNo());
pstmt.setString(2, bto.getTitle());
pstmt.setString(3, bto.getWriter());
pstmt.setString(4, bto.getContent());
pstmt.setString(5, bto.getWritedate());
//viewcount값은 처음 등록하면 무조건 0이라서 쿼리에서 부터 그냥 값을 넣어줬다
// pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(6, bto.getRefamily());
pstmt.setInt(7, bto.getRestep());
pstmt.setInt(8, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "개의 행이 삽입되었습니다.");
} finally {
dbUtil.close(conn, pstmt);
}
}
public ArrayList<BoardDTO> selectBoardAllList() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board order by refamily desc, restep asc";
ArrayList<BoardDTO> list_all = new ArrayList<BoardDTO>();
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
list_all.add(new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9)));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return list_all;
}
public BoardDTO selectContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board where no=?";
BoardDTO bto = null;
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
rset = pstmt.executeQuery();
if(rset.next()){
bto = new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return bto;
}
}
<%@page import="board.dto.BoardDTO"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글내용</title>
<style type="text/css">
div{
width:600px;
border:1px solid gray;
padding : 5px;
}
#title{
font-weight: bold;
background-color: yellow;
}
#info{
font-size:13px;
}
#content{
min-height:300px;
height:auto;
}
</style>
</head>
<body>
<h1>글목록</h1>
<p>
<div id="title">${requestScope.board.no}.${requestScope.board.title }</div>
<div id="info">작성자 : ${requestScope.board.writer } | 조회수 : ${requestScope.board.viewcount } 작성일시 : ${requestScope.board.writedate }</div>
<div id="content">${requestScope.board.content }</div>
<p>
<a href="/${initParam.context_root }/write_form.jsp">글쓰기</a>
<a href="/${initParam.context_root }/boardController?command=list_all">전체 글목록</a>
<a href="">글목록(페이징)</a>
<a href="/${initParam.context_root }/boardController?command=modify_form&no=${requestScope.board.no}">글수정</a>
<a href="/${initParam.context_root }/boardController?command=delete_content&no=${requestScope.board.no}">글삭제</a>
<a href="/${initParam.context_root }/boardController?command=reply_form&no=${requestScope.board.no}">답변</a>
</body>
</html>
- 결과
-------------수정폼 조회하기------------
시작 : show_content.jsp에서 글수정 링크 클릭 command : modify_form
Ctr : ModifyFormController.execute();
BoardService : getContentByNOForForm(int no) : BoardDTO
BoardDAO : selectContentByNO(int no) : BoardDTO
응답 : modify_form.jsp
<%@page import="board.dto.BoardDTO"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글내용</title>
<style type="text/css">
div{
width:600px;
border:1px solid gray;
padding : 5px;
}
#title{
font-weight: bold;
background-color: yellow;
}
#info{
font-size:13px;
}
#content{
min-height:300px;
height:auto;
}
</style>
</head>
<body>
<h1>글목록</h1>
<p>
<div id="title">${requestScope.board.no}.${requestScope.board.title }</div>
<div id="info">작성자 : ${requestScope.board.writer } | 조회수 : ${requestScope.board.viewcount } 작성일시 : ${requestScope.board.writedate }</div>
<div id="content">${requestScope.board.content }</div>
<p>
<a href="/${initParam.context_root }/write_form.jsp">글쓰기</a>
<a href="/${initParam.context_root }/boardController?command=list_all">전체 글목록</a>
<a href="">글목록(페이징)</a>
<a href="/${initParam.context_root }/boardController?command=modify_form&no=${requestScope.board.no}">글수정</a>
<a href="/${initParam.context_root }/boardController?command=delete_content&no=${requestScope.board.no}">글삭제</a>
<a href="/${initParam.context_root }/boardController?command=reply_form&no=${requestScope.board.no}">답변</a>
</body>
</html>
Ctr : ModifyFormController.execute();
package board.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 board.dto.ForwardDTO;
public class BoardFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardFrontController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 공통 사전 작업 - 한글처리
request.setCharacterEncoding("utf-8");
//2. Controller 로직 처리 - Controller객체.execute()호출
String command = request.getParameter("command");
Controller ctr = ControllerCommandMapping.getController(command);
ForwardDTO fdto = ctr.execute(request, response);
//3. 공통 사후 작업
if(fdto.isRedirect()){
response.sendRedirect(fdto.getUrl());
}else{
RequestDispatcher rdp = request.getRequestDispatcher(fdto.getUrl());
rdp.forward(request, response);
}
}
}
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write_content")){
ctr = new WriteContentController();
}else if(command.equals("list_all")){
ctr = new BoardAllListController();
}else if(command.equals("get_content")){
ctr = new GetContentController();
}else if(command.equals("modify_form")){
ctr = new ModifyFormController();
}
return ctr;
}
}
package board.controller;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.BoardDTO;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class ModifyFormController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int no = Integer.parseInt(request.getParameter("no"));
BoardService boardService = BoardService.getInstance();
ForwardDTO forwardDTO = null;
try {
BoardDTO dto = boardService.getContentByNOForForm(no);
request.setAttribute("dto",dto);
forwardDTO = new ForwardDTO("/modify_form.jsp",false);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
BoardService : getContentByNOForForm(int no) : BoardDTO
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
public void writeContent(BoardDTO bto)throws SQLException{
/*
* 1. bto에 property 설정 - no, writedate, content
* no - sequence의 값 - dao.selectBoardNO();
* writedate - Utilities.getNow();
* content를 DB에 넣는 용으로 변경 Utilities.changeContentForDB();
* bdto의 refamily에 no 값을 설정
* 2. dao.insertContent(bto);
* 3. 날짜 형태를 년.월.일 시:분:초 형태로 변경 - bto의 property 변경
* Utilities.changeDayTimeFormat();
*/
//1
int no = dao.selectBoardNo();
String writedate = Utilities.getNow();
bto.setNo(no);
bto.setWritedate(writedate);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
bto.setRefamily(no);
//2
dao.insertContent(bto);
//3
bto.setWritedate(Utilities.changeDayTimeFormat(writedate));
}
//글목록
public ArrayList<BoardDTO> getBoardAllList() throws SQLException{
//1. dao로 부터 전체 글내용을 ArrayList로 조회
ArrayList<BoardDTO> list_all = dao.selectBoardAllList();
//2. list내의 BoardDTO객체들의 wrtiedate를 변경
for(int i=0;i<list_all.size();i++){
list_all.get(i).setWritedate(Utilities.changeDayFormat(list_all.get(i).getWritedate()));
}
return list_all;
}
public BoardDTO getContentByNO(int no) throws SQLException{
//1.조회수 증가
dao.updateViewCount(no);
//2. no로 글 정보 조회
BoardDTO bto = dao.selectContentByNO(no);
//2-1 writedate를 yyy.MM.dd HH:mm:ss 형식으로 변경
bto.setWritedate(Utilities.changeDayTimeFormat(bto.getWritedate()));
return bto;
}
public BoardDTO getContentByNOForForm(int no)throws SQLException{
//1. no값으로 글 조회
BoardDTO bto = dao.selectContentByNO(no);
//2. content를 textarea용으로 변경(DB용으로 바뀌어 있는 것을 HTML용으로 변경)
bto.setContent(Utilities.changeContentForTextArea(bto.getContent()));
System.out.println("가져올때-----------\n"+bto.getContent());
return bto;
}
}
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import board.dto.BoardDTO;
import board.util.DBUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private DBUtil dbUtil;
private BoardDAO() {
dbUtil = DBUtil.getInstance();
}
public static BoardDAO getInstance() {
return instance;
}
public int selectBoardNo() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select board_no_seq.nextval from dual";
int no = 0;
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
if (rset.next()) {
no = rset.getInt(1);
}
} finally {
dbUtil.close(conn, pstmt, rset);
}
return no;
}
public void insertContent(BoardDTO bto) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into board (no, title, writer, content, writedate, viewcount, refamily, restep, relevel) values(?,?,?,?,?,0,?,?,?)";
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bto.getNo());
pstmt.setString(2, bto.getTitle());
pstmt.setString(3, bto.getWriter());
pstmt.setString(4, bto.getContent());
pstmt.setString(5, bto.getWritedate());
//viewcount값은 처음 등록하면 무조건 0이라서 쿼리에서 부터 그냥 값을 넣어줬다
// pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(6, bto.getRefamily());
pstmt.setInt(7, bto.getRestep());
pstmt.setInt(8, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "개의 행이 삽입되었습니다.");
} finally {
dbUtil.close(conn, pstmt);
}
}
public ArrayList<BoardDTO> selectBoardAllList() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board order by refamily desc, restep asc";
ArrayList<BoardDTO> list_all = new ArrayList<BoardDTO>();
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
list_all.add(new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9)));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return list_all;
}
public BoardDTO selectContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board where no=?";
BoardDTO bto = null;
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
rset = pstmt.executeQuery();
if(rset.next()){
bto = new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return bto;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글 수정</title>
</head>
<body>
<h2>글 수정 폼</h2><p>
${requestScope.dto.no }번 글 수정
<form action="/${initParam.context_root }/boardController" method="post">
<input type="hidden" name="no" value="${requestScope.dto.no }">
<input type="hidden" name="viewcount" value="${requestScope.dto.viewcount }">
<input type="hidden" name="command" value="modify_content">
<table width="500px">
<tr>
<td width="100px">제목</td><td><input type="text" name="title" size="50" value="${requestScope.dto.title }"></td>
</tr>
<tr>
<td>작성자</td><td><input type="text" name="writer" size="10" maxlength="10" value="${requestScope.dto.writer }"></td>
</tr>
<tr>
<td colspan="2"><textarea cols="50" rows="10" name="content">
${requestScope.dto.content }</textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="수정">
<input type="reset" value="초기화">
</td>
</tr>
</table>
</form>
</body>
</html>
* 결과보기
-------------글 수정 처리---------------
시작 : modify_form.jsp에서 수정버튼 클릭 command : modify_content
Ctr : ModifyContentController.execute();
BoardService : modifyContent(BoardDTO bdto) : void
BoardDAO : updateContent(BoardDTO bdto)
- 제목, 작성자, 내용, 일시
응답 : show_content.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글 수정</title>
</head>
<body>
<h2>글 수정 폼</h2><p>
${requestScope.dto.no }번 글 수정
<form action="/${initParam.context_root }/boardController" method="post">
<input type="hidden" name="no" value="${requestScope.dto.no }">
<input type="hidden" name="viewcount" value="${requestScope.dto.viewcount }">
<input type="hidden" name="command" value="modify_content">
<table width="500px">
<tr>
<td width="100px">제목</td><td><input type="text" name="title" size="50" value="${requestScope.dto.title }"></td>
</tr>
<tr>
<td>작성자</td><td><input type="text" name="writer" size="10" maxlength="10" value="${requestScope.dto.writer }"></td>
</tr>
<tr>
<td colspan="2"><textarea cols="50" rows="10" name="content">
${requestScope.dto.content }</textarea></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="수정">
<input type="reset" value="초기화">
</td>
</tr>
</table>
</form>
</body>
</html>
package board.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 board.dto.ForwardDTO;
public class BoardFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardFrontController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 공통 사전 작업 - 한글처리
request.setCharacterEncoding("utf-8");
//2. Controller 로직 처리 - Controller객체.execute()호출
String command = request.getParameter("command");
Controller ctr = ControllerCommandMapping.getController(command);
ForwardDTO fdto = ctr.execute(request, response);
//3. 공통 사후 작업
if(fdto.isRedirect()){
response.sendRedirect(fdto.getUrl());
}else{
RequestDispatcher rdp = request.getRequestDispatcher(fdto.getUrl());
rdp.forward(request, response);
}
}
}
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write_content")){
ctr = new WriteContentController();
}else if(command.equals("list_all")){
ctr = new BoardAllListController();
}else if(command.equals("get_content")){
ctr = new GetContentController();
}else if(command.equals("modify_form")){
ctr = new ModifyFormController();
}else if(command.equals("modify_content")){
ctr = new ModifyContentController();
}
return ctr;
}
}
package board.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.BoardDTO;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class ModifyContentController implements Controller {
ForwardDTO forwardDTO = null;
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//요청파라미터 조회
try {
int no = Integer.parseInt(request.getParameter("no"));
String title = request.getParameter("title");
String writer = request.getParameter("writer");
String content = request.getParameter("content");
int viewcount = Integer.parseInt(request.getParameter("viewcount"));
//2.비지니스 로직 처리
BoardService boardService = BoardService.getInstance();
BoardDTO dto = new BoardDTO(no,title, writer, content,null,viewcount);
boardService.modifyContent(dto);
request.setAttribute("board",dto);
forwardDTO = new ForwardDTO("/show_content.jsp",false);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
public void writeContent(BoardDTO bto)throws SQLException{
/*
* 1. bto에 property 설정 - no, writedate, content
* no - sequence의 값 - dao.selectBoardNO();
* writedate - Utilities.getNow();
* content를 DB에 넣는 용으로 변경 Utilities.changeContentForDB();
* bdto의 refamily에 no 값을 설정
* 2. dao.insertContent(bto);
* 3. 날짜 형태를 년.월.일 시:분:초 형태로 변경 - bto의 property 변경
* Utilities.changeDayTimeFormat();
*/
//1
int no = dao.selectBoardNo();
String writedate = Utilities.getNow();
bto.setNo(no);
bto.setWritedate(writedate);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
bto.setRefamily(no);
//2
dao.insertContent(bto);
//3
bto.setWritedate(Utilities.changeDayTimeFormat(writedate));
}
//글목록
public ArrayList<BoardDTO> getBoardAllList() throws SQLException{
//1. dao로 부터 전체 글내용을 ArrayList로 조회
ArrayList<BoardDTO> list_all = dao.selectBoardAllList();
//2. list내의 BoardDTO객체들의 wrtiedate를 변경
for(int i=0;i<list_all.size();i++){
list_all.get(i).setWritedate(Utilities.changeDayFormat(list_all.get(i).getWritedate()));
}
return list_all;
}
public BoardDTO getContentByNO(int no) throws SQLException{
//1.조회수 증가
dao.updateViewCount(no);
//2. no로 글 정보 조회
BoardDTO bto = dao.selectContentByNO(no);
//2-1 writedate를 yyy.MM.dd HH:mm:ss 형식으로 변경
bto.setWritedate(Utilities.changeDayTimeFormat(bto.getWritedate()));
return bto;
}
public BoardDTO getContentByNOForForm(int no)throws SQLException{
//1. no값으로 글 조회
BoardDTO bto = dao.selectContentByNO(no);
//2. content를 textarea용으로 변경(DB용으로 바뀌어 있는 것을 HTML용으로 변경)
bto.setContent(Utilities.changeContentForTextArea(bto.getContent()));
System.out.println("가져올때-----------\n"+bto.getContent());
return bto;
}
public void modifyContent(BoardDTO bto)throws SQLException {
//1. property변경 - content, writedate
bto.setWritedate(Utilities.getNow());
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
//2. 수정처리
dao.updateContent(bto);
//3. 날짜 포멧 변경
bto.setWritedate(Utilities.changeDayTimeFormat(Utilities.getNow()));
}
}
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import board.dto.BoardDTO;
import board.util.DBUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private DBUtil dbUtil;
private BoardDAO() {
dbUtil = DBUtil.getInstance();
}
public static BoardDAO getInstance() {
return instance;
}
public int selectBoardNo() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select board_no_seq.nextval from dual";
int no = 0;
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
if (rset.next()) {
no = rset.getInt(1);
}
} finally {
dbUtil.close(conn, pstmt, rset);
}
return no;
}
public void insertContent(BoardDTO bto) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into board (no, title, writer, content, writedate, viewcount, refamily, restep, relevel) values(?,?,?,?,?,0,?,?,?)";
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bto.getNo());
pstmt.setString(2, bto.getTitle());
pstmt.setString(3, bto.getWriter());
pstmt.setString(4, bto.getContent());
pstmt.setString(5, bto.getWritedate());
//viewcount값은 처음 등록하면 무조건 0이라서 쿼리에서 부터 그냥 값을 넣어줬다
// pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(6, bto.getRefamily());
pstmt.setInt(7, bto.getRestep());
pstmt.setInt(8, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "개의 행이 삽입되었습니다.");
} finally {
dbUtil.close(conn, pstmt);
}
}
public ArrayList<BoardDTO> selectBoardAllList() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board order by refamily desc, restep asc";
ArrayList<BoardDTO> list_all = new ArrayList<BoardDTO>();
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
list_all.add(new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9)));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return list_all;
}
public BoardDTO selectContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board where no=?";
BoardDTO bto = null;
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
rset = pstmt.executeQuery();
if(rset.next()){
bto = new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return bto;
}
public void updateViewCount(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set viewcount=viewcount+1 where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void updateContent(BoardDTO dto) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set title=?, writer=?, content=?, writedate=? where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getTitle());
pstmt.setString(2, dto.getWriter());
pstmt.setString(3, dto.getContent());
pstmt.setString(4, dto.getWritedate());
pstmt.setInt(5, dto.getNo());
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
}
<%@page import="board.dto.BoardDTO"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글내용</title>
<style type="text/css">
div{
width:600px;
border:1px solid gray;
padding : 5px;
}
#title{
font-weight: bold;
background-color: yellow;
}
#info{
font-size:13px;
}
#content{
min-height:300px;
height:auto;
}
</style>
</head>
<body>
<h1>글목록</h1>
<p>
<div id="title">${requestScope.board.no}.${requestScope.board.title }</div>
<div id="info">작성자 : ${requestScope.board.writer } | 조회수 : ${requestScope.board.viewcount } 작성일시 : ${requestScope.board.writedate }</div>
<div id="content">${requestScope.board.content }</div>
<p>
<a href="/${initParam.context_root }/write_form.jsp">글쓰기</a>
<a href="/${initParam.context_root }/boardController?command=list_all">전체 글목록</a>
<a href="">글목록(페이징)</a>
<a href="/${initParam.context_root }/boardController?command=modify_form&no=${requestScope.board.no}">글수정</a>
<a href="/${initParam.context_root }/boardController?command=delete_content&no=${requestScope.board.no}">글삭제</a>
<a href="/${initParam.context_root }/boardController?command=reply_form&no=${requestScope.board.no}">답변</a>
</body>
</html>
* 결과보기
시작 : show_content.jsp 삭제링크 클릭. cmd : delete_content
Ctr : DeleteContentController.execute()
BoardService : deleteContentByNO(int no) : void
BoardDTO : deleteContentByNO(int no)
응답 : list_all.jsp
<%@page import="board.dto.BoardDTO"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글내용</title>
<style type="text/css">
div{
width:600px;
border:1px solid gray;
padding : 5px;
}
#title{
font-weight: bold;
background-color: yellow;
}
#info{
font-size:13px;
}
#content{
min-height:300px;
height:auto;
}
</style>
</head>
<body>
<h1>글목록</h1>
<p>
<div id="title">${requestScope.board.no}.${requestScope.board.title }</div>
<div id="info">작성자 : ${requestScope.board.writer } | 조회수 : ${requestScope.board.viewcount } 작성일시 : ${requestScope.board.writedate }</div>
<div id="content">${requestScope.board.content }</div>
<p>
<a href="/${initParam.context_root }/write_form.jsp">글쓰기</a>
<a href="/${initParam.context_root }/boardController?command=list_all">전체 글목록</a>
<a href="">글목록(페이징)</a>
<a href="/${initParam.context_root }/boardController?command=modify_form&no=${requestScope.board.no}">글수정</a>
<a href="/${initParam.context_root }/boardController?command=delete_content&no=${requestScope.board.no}">글삭제</a>
<a href="">글답변</a>
</body>
</html>
package board.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 board.dto.ForwardDTO;
public class BoardFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardFrontController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 공통 사전 작업 - 한글처리
request.setCharacterEncoding("utf-8");
//2. Controller 로직 처리 - Controller객체.execute()호출
String command = request.getParameter("command");
Controller ctr = ControllerCommandMapping.getController(command);
ForwardDTO fdto = ctr.execute(request, response);
//3. 공통 사후 작업
if(fdto.isRedirect()){
response.sendRedirect(fdto.getUrl());
}else{
RequestDispatcher rdp = request.getRequestDispatcher(fdto.getUrl());
rdp.forward(request, response);
}
}
}
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write_content")){
ctr = new WriteContentController();
}else if(command.equals("list_all")){
ctr = new BoardAllListController();
}else if(command.equals("get_content")){
ctr = new GetContentController();
}else if(command.equals("modify_form")){
ctr = new ModifyFormController();
}else if(command.equals("modify_content")){
ctr = new ModifyContentController();
}else if(command.equals("delete_content")){
ctr = new DeleteContentController();
}
return ctr;
}
}
package board.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class DeleteContentController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ForwardDTO forwardDTO = null;
try {
int no = Integer.parseInt(request.getParameter("no"));
BoardService boardService = BoardService.getInstance();
boardService.deleteContentByNO(no);
forwardDTO = new ForwardDTO("/boardController?command=list_all",false);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
public void writeContent(BoardDTO bto)throws SQLException{
/*
* 1. bto에 property 설정 - no, writedate, content
* no - sequence의 값 - dao.selectBoardNO();
* writedate - Utilities.getNow();
* content를 DB에 넣는 용으로 변경 Utilities.changeContentForDB();
* bdto의 refamily에 no 값을 설정
* 2. dao.insertContent(bto);
* 3. 날짜 형태를 년.월.일 시:분:초 형태로 변경 - bto의 property 변경
* Utilities.changeDayTimeFormat();
*/
//1
int no = dao.selectBoardNo();
String writedate = Utilities.getNow();
bto.setNo(no);
bto.setWritedate(writedate);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
bto.setRefamily(no);
//2
dao.insertContent(bto);
//3
bto.setWritedate(Utilities.changeDayTimeFormat(writedate));
}
//글목록
public ArrayList<BoardDTO> getBoardAllList() throws SQLException{
//1. dao로 부터 전체 글내용을 ArrayList로 조회
ArrayList<BoardDTO> list_all = dao.selectBoardAllList();
//2. list내의 BoardDTO객체들의 wrtiedate를 변경
for(int i=0;i<list_all.size();i++){
list_all.get(i).setWritedate(Utilities.changeDayFormat(list_all.get(i).getWritedate()));
}
return list_all;
}
public BoardDTO getContentByNO(int no) throws SQLException{
//1.조회수 증가
dao.updateViewCount(no);
//2. no로 글 정보 조회
BoardDTO bto = dao.selectContentByNO(no);
//2-1 writedate를 yyy.MM.dd HH:mm:ss 형식으로 변경
bto.setWritedate(Utilities.changeDayTimeFormat(bto.getWritedate()));
return bto;
}
public BoardDTO getContentByNOForForm(int no)throws SQLException{
//1. no값으로 글 조회
BoardDTO bto = dao.selectContentByNO(no);
//2. content를 textarea용으로 변경(DB용으로 바뀌어 있는 것을 HTML용으로 변경)
bto.setContent(Utilities.changeContentForTextArea(bto.getContent()));
System.out.println("가져올때-----------\n"+bto.getContent());
return bto;
}
public void modifyContent(BoardDTO bto)throws SQLException {
//1. property변경 - content, writedate
bto.setWritedate(Utilities.getNow());
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
//2. 수정처리
dao.updateContent(bto);
//3. 날짜 포멧 변경
bto.setWritedate(Utilities.changeDayTimeFormat(Utilities.getNow()));
}
public void deleteContentByNO(int no)throws SQLException{
dao.deleteContentByNO(no);
}
}
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import board.dto.BoardDTO;
import board.util.DBUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private DBUtil dbUtil;
private BoardDAO() {
dbUtil = DBUtil.getInstance();
}
public static BoardDAO getInstance() {
return instance;
}
public int selectBoardNo() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select board_no_seq.nextval from dual";
int no = 0;
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
if (rset.next()) {
no = rset.getInt(1);
}
} finally {
dbUtil.close(conn, pstmt, rset);
}
return no;
}
public void insertContent(BoardDTO bto) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into board (no, title, writer, content, writedate, viewcount, refamily, restep, relevel) values(?,?,?,?,?,0,?,?,?)";
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bto.getNo());
pstmt.setString(2, bto.getTitle());
pstmt.setString(3, bto.getWriter());
pstmt.setString(4, bto.getContent());
pstmt.setString(5, bto.getWritedate());
//viewcount값은 처음 등록하면 무조건 0이라서 쿼리에서 부터 그냥 값을 넣어줬다
// pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(6, bto.getRefamily());
pstmt.setInt(7, bto.getRestep());
pstmt.setInt(8, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "개의 행이 삽입되었습니다.");
} finally {
dbUtil.close(conn, pstmt);
}
}
public ArrayList<BoardDTO> selectBoardAllList() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board order by refamily desc";
ArrayList<BoardDTO> list_all = new ArrayList<BoardDTO>();
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
list_all.add(new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9)));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return list_all;
}
public BoardDTO selectContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board where no=?";
BoardDTO bto = null;
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
rset = pstmt.executeQuery();
if(rset.next()){
bto = new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return bto;
}
public void updateViewCount(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set viewcount=viewcount+1 where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void updateContent(BoardDTO dto) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set title=?, writer=?, content=?, writedate=? where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getTitle());
pstmt.setString(2, dto.getWriter());
pstmt.setString(3, dto.getContent());
pstmt.setString(4, dto.getWritedate());
pstmt.setInt(5, dto.getNo());
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void deleteContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "delete from board where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 삭제되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
}
package board.controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.BoardDTO;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class BoardAllListController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//1. 비지니스 로직 - Model(Business Service)로 요청
BoardService boardService = BoardService.getInstance();
ForwardDTO forwardDTO = null;
try {
ArrayList<BoardDTO> list_all = boardService.getBoardAllList();
request.setAttribute("list_all",list_all);
forwardDTO = new ForwardDTO("/list_all.jsp",false);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
* 결과보기
-------------------답변폼 조회----------------------
시작 : show_content.jsp 답변링크 클릭. command : reply_form
Ctr : ReplyFormController.execute()
BoardService : getContentByNOForForm(int no) : BoardDTO
BoardDAO : selectContentByNO(int no) : BoardDTO
응답 : reply_form.jsp
<%@page import="board.dto.BoardDTO"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글내용</title>
<style type="text/css">
div{
width:600px;
border:1px solid gray;
padding : 5px;
}
#title{
font-weight: bold;
background-color: yellow;
}
#info{
font-size:13px;
}
#content{
min-height:300px;
height:auto;
}
</style>
</head>
<body>
<h1>글목록</h1>
<p>
<div id="title">${requestScope.board.no}.${requestScope.board.title }</div>
<div id="info">작성자 : ${requestScope.board.writer } | 조회수 : ${requestScope.board.viewcount } 작성일시 : ${requestScope.board.writedate }</div>
<div id="content">${requestScope.board.content }</div>
<p>
<a href="/${initParam.context_root }/write_form.jsp">글쓰기</a>
<a href="/${initParam.context_root }/boardController?command=list_all">전체 글목록</a>
<a href="">글목록(페이징)</a>
<a href="/${initParam.context_root }/boardController?command=modify_form&no=${requestScope.board.no}">글수정</a>
<a href="/${initParam.context_root }/boardController?command=delete_content&no=${requestScope.board.no}">글삭제</a>
<a href="/${initParam.context_root }/boardController?command=reply_form&no=${requestScope.board.no}">답변</a>
</body>
</html>
package board.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 board.dto.ForwardDTO;
public class BoardFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardFrontController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 공통 사전 작업 - 한글처리
request.setCharacterEncoding("utf-8");
//2. Controller 로직 처리 - Controller객체.execute()호출
String command = request.getParameter("command");
Controller ctr = ControllerCommandMapping.getController(command);
ForwardDTO fdto = ctr.execute(request, response);
//3. 공통 사후 작업
if(fdto.isRedirect()){
response.sendRedirect(fdto.getUrl());
}else{
RequestDispatcher rdp = request.getRequestDispatcher(fdto.getUrl());
rdp.forward(request, response);
}
}
}
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write_content")){
ctr = new WriteContentController();
}else if(command.equals("list_all")){
ctr = new BoardAllListController();
}else if(command.equals("get_content")){
ctr = new GetContentController();
}else if(command.equals("modify_form")){
ctr = new ModifyFormController();
}else if(command.equals("modify_content")){
ctr = new ModifyContentController();
}else if(command.equals("delete_content")){
ctr = new DeleteContentController();
}else if(command.equals("reply_form")){
ctr = new ReplyFormController();
}
return ctr;
}
}
package board.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.BoardDTO;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class ReplyFormController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ForwardDTO forwardDTO = null;
try {
int no = Integer.parseInt(request.getParameter("no"));
BoardService boardService = BoardService.getInstance();
BoardDTO dto = boardService.getContentByNOForForm(no);
request.setAttribute("dto",dto);
forwardDTO = new ForwardDTO("/reply_form.jsp",false);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
public void writeContent(BoardDTO bto)throws SQLException{
/*
* 1. bto에 property 설정 - no, writedate, content
* no - sequence의 값 - dao.selectBoardNO();
* writedate - Utilities.getNow();
* content를 DB에 넣는 용으로 변경 Utilities.changeContentForDB();
* bdto의 refamily에 no 값을 설정
* 2. dao.insertContent(bto);
* 3. 날짜 형태를 년.월.일 시:분:초 형태로 변경 - bto의 property 변경
* Utilities.changeDayTimeFormat();
*/
//1
int no = dao.selectBoardNo();
String writedate = Utilities.getNow();
bto.setNo(no);
bto.setWritedate(writedate);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
bto.setRefamily(no);
//2
dao.insertContent(bto);
//3
bto.setWritedate(Utilities.changeDayTimeFormat(writedate));
}
//글목록
public ArrayList<BoardDTO> getBoardAllList() throws SQLException{
//1. dao로 부터 전체 글내용을 ArrayList로 조회
ArrayList<BoardDTO> list_all = dao.selectBoardAllList();
//2. list내의 BoardDTO객체들의 wrtiedate를 변경
for(int i=0;i<list_all.size();i++){
list_all.get(i).setWritedate(Utilities.changeDayFormat(list_all.get(i).getWritedate()));
}
return list_all;
}
public BoardDTO getContentByNO(int no) throws SQLException{
//1.조회수 증가
dao.updateViewCount(no);
//2. no로 글 정보 조회
BoardDTO bto = dao.selectContentByNO(no);
//2-1 writedate를 yyy.MM.dd HH:mm:ss 형식으로 변경
bto.setWritedate(Utilities.changeDayTimeFormat(bto.getWritedate()));
return bto;
}
public BoardDTO getContentByNOForForm(int no)throws SQLException{
//1. no값으로 글 조회
BoardDTO bto = dao.selectContentByNO(no);
//2. content를 textarea용으로 변경(DB용으로 바뀌어 있는 것을 HTML용으로 변경)
bto.setContent(Utilities.changeContentForTextArea(bto.getContent()));
System.out.println("가져올때-----------\n"+bto.getContent());
return bto;
}
public void modifyContent(BoardDTO bto)throws SQLException {
//1. property변경 - content, writedate
bto.setWritedate(Utilities.getNow());
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
//2. 수정처리
dao.updateContent(bto);
//3. 날짜 포멧 변경
bto.setWritedate(Utilities.changeDayTimeFormat(Utilities.getNow()));
}
public void deleteContentByNO(int no)throws SQLException{
dao.deleteContentByNO(no);
}
}
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import board.dto.BoardDTO;
import board.util.DBUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private DBUtil dbUtil;
private BoardDAO() {
dbUtil = DBUtil.getInstance();
}
public static BoardDAO getInstance() {
return instance;
}
public int selectBoardNo() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select board_no_seq.nextval from dual";
int no = 0;
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
if (rset.next()) {
no = rset.getInt(1);
}
} finally {
dbUtil.close(conn, pstmt, rset);
}
return no;
}
public void insertContent(BoardDTO bto) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into board (no, title, writer, content, writedate, viewcount, refamily, restep, relevel) values(?,?,?,?,?,0,?,?,?)";
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bto.getNo());
pstmt.setString(2, bto.getTitle());
pstmt.setString(3, bto.getWriter());
pstmt.setString(4, bto.getContent());
pstmt.setString(5, bto.getWritedate());
//viewcount값은 처음 등록하면 무조건 0이라서 쿼리에서 부터 그냥 값을 넣어줬다
// pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(6, bto.getRefamily());
pstmt.setInt(7, bto.getRestep());
pstmt.setInt(8, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "개의 행이 삽입되었습니다.");
} finally {
dbUtil.close(conn, pstmt);
}
}
public ArrayList<BoardDTO> selectBoardAllList() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board order by refamily desc, restep asc";
ArrayList<BoardDTO> list_all = new ArrayList<BoardDTO>();
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
list_all.add(new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9)));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return list_all;
}
public BoardDTO selectContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board where no=?";
BoardDTO bto = null;
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
rset = pstmt.executeQuery();
if(rset.next()){
bto = new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return bto;
}
public void updateViewCount(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set viewcount=viewcount+1 where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void updateContent(BoardDTO dto) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set title=?, writer=?, content=?, writedate=? where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getTitle());
pstmt.setString(2, dto.getWriter());
pstmt.setString(3, dto.getContent());
pstmt.setString(4, dto.getWritedate());
pstmt.setInt(5, dto.getNo());
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void deleteContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "delete from board where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 삭제되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void updateRestep(int refamily, int restep) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set restep=restep+1 where refamily=? and restep>?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, refamily);
pstmt.setInt(2, restep);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글 수정</title>
</head>
<body>
<h2>글 답변 폼</h2><p>
${requestScope.dto.no }번 답변글
<form action="/${initParam.context_root }/boardController" method="post">
<input type="hidden" name="refamily" value="${requestScope.dto.refamily }">
<input type="hidden" name="restep" value="${requestScope.dto.restep }">
<input type="hidden" name="relevel" value="${requestScope.dto.relevel }">
<input type="hidden" name="command" value="reply_content">
<table width="500px">
<tr>
<td width="100px">제목</td><td><input type="text" name="title" size="50" value="RE : ${requestScope.dto.title }"></td>
</tr>
<tr>
<td>작성자</td><td><input type="text" name="writer" size="10" maxlength="10" value="${requestScope.dto.writer }"></td>
</tr>
<tr>
<td colspan="2"><textarea cols="50" rows="10" name="content">
${requestScope.dto.content }
----------------답변-----------------
</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="답변">
<input type="reset" value="초기화">
</td>
</tr>
</table>
</form>
</body>
</html>
* 결과보기
---------------------------답변처리-----------------
시작 : reply_form.jsp 답변버튼 클릭. command : reply_content
Ctr : ReplyContentController.execute()
BoardService : replyContent(BoardDTO)
BoardDAO : updateRestep(int refamily, int restep)
selectBoardNO()
insertContent()
응답 : show_content.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글 수정</title>
</head>
<body>
<h2>글 답변 폼</h2><p>
${requestScope.dto.no }번 답변글
<form action="/${initParam.context_root }/boardController" method="post">
<input type="hidden" name="refamily" value="${requestScope.dto.refamily }">
<input type="hidden" name="restep" value="${requestScope.dto.restep }">
<input type="hidden" name="relevel" value="${requestScope.dto.relevel }">
<input type="hidden" name="command" value="reply_content">
<table width="500px">
<tr>
<td width="100px">제목</td><td><input type="text" name="title" size="50" value="RE : ${requestScope.dto.title }"></td>
</tr>
<tr>
<td>작성자</td><td><input type="text" name="writer" size="10" maxlength="10" value="${requestScope.dto.writer }"></td>
</tr>
<tr>
<td colspan="2"><textarea cols="50" rows="10" name="content">
${requestScope.dto.content }
----------------답변-----------------
</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="답변">
<input type="reset" value="초기화">
</td>
</tr>
</table>
</form>
</body>
</html>
package board.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 board.dto.ForwardDTO;
public class BoardFrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
public BoardFrontController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 공통 사전 작업 - 한글처리
request.setCharacterEncoding("utf-8");
//2. Controller 로직 처리 - Controller객체.execute()호출
String command = request.getParameter("command");
Controller ctr = ControllerCommandMapping.getController(command);
ForwardDTO fdto = ctr.execute(request, response);
//3. 공통 사후 작업
if(fdto.isRedirect()){
response.sendRedirect(fdto.getUrl());
}else{
RequestDispatcher rdp = request.getRequestDispatcher(fdto.getUrl());
rdp.forward(request, response);
}
}
}
package board.controller;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write_content")){
ctr = new WriteContentController();
}else if(command.equals("list_all")){
ctr = new BoardAllListController();
}else if(command.equals("get_content")){
ctr = new GetContentController();
}else if(command.equals("modify_form")){
ctr = new ModifyFormController();
}else if(command.equals("modify_content")){
ctr = new ModifyContentController();
}else if(command.equals("delete_content")){
ctr = new DeleteContentController();
}else if(command.equals("reply_form")){
ctr = new ReplyFormController();
}else if(command.equals("reply_content")){
ctr = new ReplyContentController();
}
return ctr;
}
}
package board.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import board.dto.BoardDTO;
import board.dto.ForwardDTO;
import board.model.service.BoardService;
public class ReplyContentController implements Controller {
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ForwardDTO forwardDTO = null;
try {
//1, client가 보낸 요청 파라미터 조회
String title = request.getParameter("title");
String writer = request.getParameter("writer");
String content = request.getParameter("content");
int refamily = Integer.parseInt(request.getParameter("refamily"));
int restep = Integer.parseInt(request.getParameter("restep"));
int relevel = Integer.parseInt(request.getParameter("relevel"));
//글쓴일자하고 no,와 viewcount는 서비스에서 다시 생성할것이기 때문에 디폴트 값을 넣었다.
BoardDTO bto = new BoardDTO(0,title, writer, content,null,0,refamily,restep,relevel);
//2. 비지니스 로직 - Model(Business Service)로 요청
BoardService boardService = BoardService.getInstance();
boardService.replyContent(bto);
request.setAttribute("board",bto);
forwardDTO = new ForwardDTO("/show_content.jsp",false);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("error_message", e.getMessage());
forwardDTO = new ForwardDTO("/error.jsp",false);
}
return forwardDTO;
}
}
package board.model.service;
import java.sql.SQLException;
import java.util.ArrayList;
import board.dto.BoardDTO;
import board.model.dao.BoardDAO;
import board.util.Utilities;
public class BoardService {
private static BoardService instance = new BoardService();
private BoardDAO dao;
private BoardService(){
dao = BoardDAO.getInstance();
}
public static BoardService getInstance(){
return instance;
}
public void writeContent(BoardDTO bto)throws SQLException{
/*
* 1. bto에 property 설정 - no, writedate, content
* no - sequence의 값 - dao.selectBoardNO();
* writedate - Utilities.getNow();
* content를 DB에 넣는 용으로 변경 Utilities.changeContentForDB();
* bdto의 refamily에 no 값을 설정
* 2. dao.insertContent(bto);
* 3. 날짜 형태를 년.월.일 시:분:초 형태로 변경 - bto의 property 변경
* Utilities.changeDayTimeFormat();
*/
//1
int no = dao.selectBoardNo();
String writedate = Utilities.getNow();
bto.setNo(no);
bto.setWritedate(writedate);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
bto.setRefamily(no);
//2
dao.insertContent(bto);
//3
bto.setWritedate(Utilities.changeDayTimeFormat(writedate));
}
//글목록
public ArrayList<BoardDTO> getBoardAllList() throws SQLException{
//1. dao로 부터 전체 글내용을 ArrayList로 조회
ArrayList<BoardDTO> list_all = dao.selectBoardAllList();
//2. list내의 BoardDTO객체들의 wrtiedate를 변경
for(int i=0;i<list_all.size();i++){
list_all.get(i).setWritedate(Utilities.changeDayFormat(list_all.get(i).getWritedate()));
}
return list_all;
}
public BoardDTO getContentByNO(int no) throws SQLException{
//1.조회수 증가
dao.updateViewCount(no);
//2. no로 글 정보 조회
BoardDTO bto = dao.selectContentByNO(no);
//2-1 writedate를 yyy.MM.dd HH:mm:ss 형식으로 변경
bto.setWritedate(Utilities.changeDayTimeFormat(bto.getWritedate()));
return bto;
}
public BoardDTO getContentByNOForForm(int no)throws SQLException{
//1. no값으로 글 조회
BoardDTO bto = dao.selectContentByNO(no);
//2. content를 textarea용으로 변경(DB용으로 바뀌어 있는 것을 HTML용으로 변경)
bto.setContent(Utilities.changeContentForTextArea(bto.getContent()));
System.out.println("가져올때-----------\n"+bto.getContent());
return bto;
}
public void modifyContent(BoardDTO bto)throws SQLException {
//1. property변경 - content, writedate
bto.setWritedate(Utilities.getNow());
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
//2. 수정처리
dao.updateContent(bto);
//3. 날짜 포멧 변경
bto.setWritedate(Utilities.changeDayTimeFormat(Utilities.getNow()));
}
public void deleteContentByNO(int no)throws SQLException{
dao.deleteContentByNO(no);
}
public void replyContent(BoardDTO bto)throws SQLException {
//1. DB에 같은 refamily의 restep들을 1씩 증가 시킨다.
dao.updateRestep(bto.getRefamily(),bto.getRestep());
//2. bdto의 restep, relevel을 1 증가 시킨다.
bto.setRestep(bto.getRestep()+1);
bto.setRelevel(bto.getRelevel()+1);
//3. insert할 글 번호를 가져온뒤 bto에 넣는다.
int no = dao.selectBoardNo();
//4. BoardDTO에 no, writeDate와 content는 DB 저장용으로 변경한다.
bto.setNo(no);
bto.setWritedate(Utilities.getNow());
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
//5. 새글 등록 - dao.insertContent()이용
dao.insertContent(bto);
//6. 날짜 형태 show_content.jsp에서 보여주도록 년.월.일 시:분:초 로 변경
bto.setWritedate(Utilities.changeDayTimeFormat(Utilities.getNow()));
}
}
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import board.dto.BoardDTO;
import board.util.DBUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private DBUtil dbUtil;
private BoardDAO() {
dbUtil = DBUtil.getInstance();
}
public static BoardDAO getInstance() {
return instance;
}
public int selectBoardNo() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select board_no_seq.nextval from dual";
int no = 0;
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
if (rset.next()) {
no = rset.getInt(1);
}
} finally {
dbUtil.close(conn, pstmt, rset);
}
return no;
}
public void insertContent(BoardDTO bto) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "insert into board (no, title, writer, content, writedate, viewcount, refamily, restep, relevel) values(?,?,?,?,?,0,?,?,?)";
try {
BasicDataSource ds = dbUtil.getDataSource();
conn = ds.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bto.getNo());
pstmt.setString(2, bto.getTitle());
pstmt.setString(3, bto.getWriter());
pstmt.setString(4, bto.getContent());
pstmt.setString(5, bto.getWritedate());
//viewcount값은 처음 등록하면 무조건 0이라서 쿼리에서 부터 그냥 값을 넣어줬다
// pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(6, bto.getRefamily());
pstmt.setInt(7, bto.getRestep());
pstmt.setInt(8, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "개의 행이 삽입되었습니다.");
} finally {
dbUtil.close(conn, pstmt);
}
}
public ArrayList<BoardDTO> selectBoardAllList() throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board order by refamily desc, restep asc";
ArrayList<BoardDTO> list_all = new ArrayList<BoardDTO>();
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
rset = pstmt.executeQuery();
while(rset.next()){
list_all.add(new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9)));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return list_all;
}
public BoardDTO selectContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = "select no, title, writer, content, writedate, viewcount, refamily, restep, relevel from board where no=?";
BoardDTO bto = null;
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
rset = pstmt.executeQuery();
if(rset.next()){
bto = new BoardDTO(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getInt(6), rset.getInt(7), rset.getInt(8), rset.getInt(9));
}
}finally{
dbUtil.close(conn, pstmt, rset);
}
return bto;
}
public void updateViewCount(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set viewcount=viewcount+1 where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void updateContent(BoardDTO dto) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set title=?, writer=?, content=?, writedate=? where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, dto.getTitle());
pstmt.setString(2, dto.getWriter());
pstmt.setString(3, dto.getContent());
pstmt.setString(4, dto.getWritedate());
pstmt.setInt(5, dto.getNo());
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void deleteContentByNO(int no) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "delete from board where no=?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, no);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 삭제되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
public void updateRestep(int refamily, int restep) throws SQLException{
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "update board set restep=restep+1 where refamily=? and restep>?";
try{
BasicDataSource dataSource = dbUtil.getDataSource();
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, refamily);
pstmt.setInt(2, restep);
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 수정되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
}
<%@page import="board.dto.BoardDTO"%>
<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글내용</title>
<style type="text/css">
div{
width:600px;
border:1px solid gray;
padding : 5px;
}
#title{
font-weight: bold;
background-color: yellow;
}
#info{
font-size:13px;
}
#content{
min-height:300px;
height:auto;
}
</style>
</head>
<body>
<h1>글목록</h1>
<p>
<div id="title">${requestScope.board.no}.${requestScope.board.title }</div>
<div id="info">작성자 : ${requestScope.board.writer } | 조회수 : ${requestScope.board.viewcount } 작성일시 : ${requestScope.board.writedate }</div>
<div id="content">${requestScope.board.content }</div>
<p>
<a href="/${initParam.context_root }/write_form.jsp">글쓰기</a>
<a href="/${initParam.context_root }/boardController?command=list_all">전체 글목록</a>
<a href="">글목록(페이징)</a>
<a href="/${initParam.context_root }/boardController?command=modify_form&no=${requestScope.board.no}">글수정</a>
<a href="/${initParam.context_root }/boardController?command=delete_content&no=${requestScope.board.no}">글삭제</a>
<a href="/${initParam.context_root }/boardController?command=reply_form&no=${requestScope.board.no}">답변</a>
</body>
</html>
* 결과보기
'프로그래밍 > JSP Programming' 카테고리의 다른 글
2012-5-21 게시판 페이징 처리하기(rownum, 서브쿼리)[실습] (0) | 2012.05.21 |
---|---|
2012-5-21 게시판 페이징 처리하기(rownum, 서브쿼리) (0) | 2012.05.21 |
게시판 소스 (0) | 2012.05.18 |
2012-5-18 답변폼 조회 (0) | 2012.05.18 |
2012-5-18 MVC패턴을 활용한 게시판 글삭제하기 (0) | 2012.05.18 |