* controller
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;
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;
}
package board.controller;
import board.model.service.BoardService;
public class ControllerCommandMapping {
public static Controller getController(String command){
Controller ctr = null;
if(command.equals("write")){
ctr = new WriteContentController();
}
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.dao.BoardDAO;
import board.model.service.BoardService;
import board.util.Utilities;
public class WriteContentController implements Controller{
@Override
public ForwardDTO execute(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("title");
String writer = request.getParameter("writer");
String content = request.getParameter("content");
BoardService boardService = BoardService.getInstance();
BoardDTO bto = new BoardDTO(title, writer, content);
ForwardDTO forwardDTO = null;
try {
boardService.writeContent(bto);
bto.setWritedate(Utilities.changeDayTimeFormat(Utilities.getNow()));
System.out.println(bto.getContent());
// bto.setContent(Utilities.changeContentForTextArea(bto.getContent()));
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;
}
}
* 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 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 ForwardDTO {
private String url;
private boolean redirect; //true - 리다이렉트, false - 요청디스패치
public ForwardDTO() {
super();
// TODO Auto-generated constructor stub
}
public ForwardDTO(String url, boolean redirect) {
super();
this.url = url;
this.redirect = redirect;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isRedirect() {
return redirect;
}
public void setRedirect(boolean redirect) {
this.redirect = redirect;
}
@Override
public String toString() {
return "ForwardDTO [url=" + url + ", redirect=" + redirect + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (redirect ? 1231 : 1237);
result = prime * result + ((url == null) ? 0 : url.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;
ForwardDTO other = (ForwardDTO) obj;
if (redirect != other.redirect)
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
}
}
* DAO
package board.model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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(?,?,?,?,?,?,?,?,?)";
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());
pstmt.setInt(6, bto.getViewcount());
pstmt.setInt(7, bto.getRefamily());
pstmt.setInt(8, bto.getRestep());
pstmt.setInt(9, bto.getRelevel());
int cnt = pstmt.executeUpdate();
System.out.println(cnt+"개의 행이 삽입되었습니다.");
}finally{
dbUtil.close(conn, pstmt);
}
}
}
* service
package board.model.service;
import java.sql.SQLException;
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{
int no = dao.selectBoardNo();
bto.setNo(no);
bto.setRefamily(no);
bto.setRelevel(0);
bto.setRestep(0);
bto.setViewcount(0);
bto.setContent(Utilities.changeContentForDB(bto.getContent()));
String writedate = Utilities.getNow();
bto.setWritedate(writedate);
dao.insertContent(bto);
}
}
* util
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;
import java.util.GregorianCalendar;
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 = null;
newContent = content.replaceAll(">", ">");
newContent = content.replaceAll("<","<");
newContent = content.replaceAll(" "," ");
newContent = content.replaceAll("\n", "<br>");
return newContent;
}
/**
* DB 에 저장된 content를 TextArea에 출력할 형식으로 변경
* 글수정 폼, 답글 폼 출력시 사용
* <br> - \n
* > ->
* < - <
* - 공백
*/
public static String changeContentForTextArea(String content){
String newContent = null;
newContent = content.replaceAll("<br>","\n");
newContent = content.replaceAll(">",">");
newContent = content.replaceAll("<","<");
newContent = content.replaceAll(" "," ");
return newContent;
}
}
<%@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>Insert title here</title>
</head>
<center><h1>글목록</h1><p></center>
<body>
<table border="1" cellspacing="0" cellpadding="8" align="center" width="500">
<tr>
<td>${requestScope.board.title }</td>
</tr>
<tr>
<td>작성자 : ${requestScope.board.writer } 조회수 :
${requestScope.board.viewcount } 작성일시 :
${requestScope.board.writedate }</td>
<tr valign="top" height="200">
<td><c:out value="${requestScope.board.content }" escapeXml="true"/></td>
</tr>
</table>
</body>
</html>
<%@ 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="/board_fc/boardController" method="post">
<input type="hidden" name="command" value="write">
<table>
<tr>
<td>제목</td>
<td><input type="text" name="title"></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>
* 결과보기
'프로그래밍 > JSP Programming' 카테고리의 다른 글
2012-5-17 게시판 글번호로 조회 (0) | 2012.05.17 |
---|---|
2012-5-17 전체 글목록 조회(no paging) (0) | 2012.05.17 |
2012-5-15 Oracle Sequence (0) | 2012.05.15 |
2012-5-15 MVC를 활용한 게시판만들기 (0) | 2012.05.15 |
2012-5-15 MVC를 활용한 회원관리 프로그램(FrontController 사용) (0) | 2012.05.15 |