본문 바로가기

teamPJ

게시판 만들기 - 관리자용

펜션 관리자만 글쓰기가 가능하고 일반 방문자는 읽기전용만 가능한 게시판입니다. 

 

NoticeVO.java

package notice1;

import cmn.DTO;

public class NoticeVO extends DTO {
	  /**게시글번호*/
	   private String seq;
	   /**게시글제목*/
	   private String title;
	   /**게시글조회수*/
	   private String read_cnt;
	   /**게시글내용*/
	   private String contents;
	   /**게시글작성자*/
	   private String reg_id;
	   /**게시글작성일*/
	   private String reg_dt;
	   /**ip주소*/
	   private String ip;
	   
	public NoticeVO(){
		
	}


	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((contents == null) ? 0 : contents.hashCode());
		result = prime * result + ((ip == null) ? 0 : ip.hashCode());
		result = prime * result + ((read_cnt == null) ? 0 : read_cnt.hashCode());
		result = prime * result + ((reg_dt == null) ? 0 : reg_dt.hashCode());
		result = prime * result + ((reg_id == null) ? 0 : reg_id.hashCode());
		result = prime * result + ((seq == null) ? 0 : seq.hashCode());
		result = prime * result + ((title == null) ? 0 : title.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;
		NoticeVO other = (NoticeVO) obj;
		if (contents == null) {
			if (other.contents != null)
				return false;
		} else if (!contents.equals(other.contents))
			return false;
		if (ip == null) {
			if (other.ip != null)
				return false;
		} else if (!ip.equals(other.ip))
			return false;
		if (read_cnt == null) {
			if (other.read_cnt != null)
				return false;
		} else if (!read_cnt.equals(other.read_cnt))
			return false;
		if (reg_dt == null) {
			if (other.reg_dt != null)
				return false;
		} else if (!reg_dt.equals(other.reg_dt))
			return false;
		if (reg_id == null) {
			if (other.reg_id != null)
				return false;
		} else if (!reg_id.equals(other.reg_id))
			return false;
		if (seq == null) {
			if (other.seq != null)
				return false;
		} else if (!seq.equals(other.seq))
			return false;
		if (title == null) {
			if (other.title != null)
				return false;
		} else if (!title.equals(other.title))
			return false;
		return true;
	}


	public NoticeVO(String seq, String title, String read_cnt, String contents, String reg_id, String reg_dt,
			String ip) {
		super();
		this.seq = seq;
		this.title = title;
		this.read_cnt = read_cnt;
		this.contents = contents;
		this.reg_id = reg_id;
		this.reg_dt = reg_dt;
		this.ip = ip;
	}


	

	@Override
	public String toString() {
		return "NoticeVO [seq=" + seq + ", title=" + title + ", read_cnt=" + read_cnt + ", contents=" + contents
				+ ", reg_id=" + reg_id + ", reg_dt=" + reg_dt + ", ip=" + ip + "]";
	}


	public String getIp() {
		return ip;
	}


	public void setIp(String ip) {
		this.ip = ip;
	}


	public String getSeq() {
		return seq;
	}

	public void setSeq(String seq) {
		this.seq = seq;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getRead_cnt() {
		return read_cnt;
	}

	public void setRead_cnt(String read_cnt) {
		this.read_cnt = read_cnt;
	}

	public String getContents() {
		return contents;
	}

	public void setContents(String contents) {
		this.contents = contents;
	}

	public String getReg_id() {
		return reg_id;
	}

	public void setReg_id(String reg_id) {
		this.reg_id = reg_id;
	}

	public String getReg_dt() {
		return reg_dt;
	}

	public void setReg_dt(String reg_dt) {
		this.reg_dt = reg_dt;
	}
	   
			
}

 

NoticeDao.java

- 삭제, 수정, 등록, 단건조회, 목록조회 기능

- ip 1개당 1번씩만 readcount가 되도록 설정하는 기능을 추가하였습니다

package notice1;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import cmn.ConnectionMaker;
import cmn.DTO;
import cmn.JDBCReturnReso;
import cmn.SearchVO;
import cmn.WorkDiv;
import read_cnt.ReadCntVO;

public class NoticeDao implements WorkDiv {
	private final Logger LOG= Logger.getLogger(NoticeDao.class);
	private ConnectionMaker connectionMaker;
	
	public NoticeDao() {
		connectionMaker = new ConnectionMaker();
	}
	//ip등록
	public int do_retInsert(DTO dto) {
		ReadCntVO vo =(ReadCntVO)dto;
		int flag=0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		try{
			StringBuilder sb = new StringBuilder();
			sb.append(" INSERT INTO read_cnt (  \n");
			sb.append("     seq,                \n");
			sb.append("     ip,                 \n");
			sb.append("     red_dt              \n");
			sb.append(" ) VALUES (              \n");
			sb.append("     ?,				    \n");
			sb.append("     ?,                  \n");
			sb.append("     SYSDATE             \n");
			sb.append(" )                       \n");
			
			//오류나면 꺼낼 수 있도록 로그 만들기
			LOG.debug("1.=========================");
			LOG.debug("1.query\n:"+sb.toString());
			LOG.debug("1.=========================");
			
			//커넥션 만들기
			conn = connectionMaker.getConnection();
			pstmt= conn.prepareStatement(sb.toString());
			//파람 3개설정(물음표 2개임)
			pstmt.setString(1, vo.getSeq());
			pstmt.setString(2, vo.getIp());
			LOG.debug("2.=========================");
			LOG.debug("2.param\n:"+vo.toString());
			LOG.debug("2.=========================");
			
			//쿼리날리기
			flag = pstmt.executeUpdate();
			LOG.debug("3.=========================");
			LOG.debug("3.flag\n:"+flag);
			LOG.debug("3.=========================");
				
		}catch(SQLException e){
			LOG.debug("=========================");
			LOG.debug("SQLException"+e.toString());
			LOG.debug("=========================");
			
		}finally{
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);	
		}
		
		return flag;
	}
	
	//클릭한 횟수
	public int do_retSelectCnt(DTO dto){
		ReadCntVO vo =(ReadCntVO) dto;
		int flag = 0;
		Connection conn = null;
		PreparedStatement pstmt= null;
		ResultSet rs = null;
		try{
			StringBuilder sb=new StringBuilder();
			sb.append(" SELECT COUNT(*) cnt \n");
			sb.append(" FROM read_cnt      \n");
			sb.append(" WHERE  seq = ?      \n");
			conn = connectionMaker.getConnection();
			LOG.debug("1.============================");
			LOG.debug("1.query: \n"+sb.toString());
			LOG.debug("1.============================");
			
			pstmt = conn.prepareStatement(sb.toString());
			//query param
			pstmt.setString(1, vo.getSeq());
			LOG.debug("2.============================");
			LOG.debug("2.param seq="+vo.getSeq());
			LOG.debug("2.============================");			
			
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				flag = rs.getInt("cnt");
			}
			LOG.debug("3.============================");
			LOG.debug("3.flag="+flag);
			LOG.debug("3.============================");			
						
			
		}catch(SQLException e){
			LOG.debug("===================");
			LOG.debug("SQLException="+e.getMessage());
			LOG.debug("===================");
		}finally{
			JDBCReturnReso.close(rs);
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);
		}
		
		return flag;
	}
	
	//조회수 증가 
	public int do_updateReadCnt(DTO dto) {
		NoticeVO vo=(NoticeVO)dto;
		int flag=0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		try{
			StringBuilder sb = new StringBuilder();
			sb.append(" update board                                                    \n");
			sb.append(" set read_cnt = (SELECT NVL(read_cnt,0)+1 FROM board WHERE seq=?)\n");
			sb.append(" WHERE seq=?                                                     \n");
			
			conn= connectionMaker.getConnection();
			LOG.debug("1.===========================");
			LOG.debug("1.query\n"+sb.toString());
			LOG.debug("1.===========================");
			
			pstmt = conn.prepareStatement(sb.toString());
			pstmt.setString(1, vo.getSeq());
			pstmt.setString(2, vo.getSeq());
			LOG.debug("2.===========================");
			LOG.debug("2.param:"+vo);
			LOG.debug("2.===========================");
			
			flag=pstmt.executeUpdate();
			LOG.debug("3.===========================");
			LOG.debug("3.flag:"+flag);
			LOG.debug("3.===========================");
			
		}catch(SQLException s){
			LOG.debug("==========================");
			LOG.debug("SQLException="+s.toString());
			LOG.debug("==========================");
			
		}finally{
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);
		}
				
		return flag;
	}
	//저장
	@Override
	public int do_insert(DTO dto) {
		NoticeVO vo =(NoticeVO)dto;
		int flag=0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		try{
			StringBuilder sb = new StringBuilder();
			sb.append(" INSERT INTO board (     \n");
			sb.append("     seq,                \n");
			sb.append("     title,              \n");
			sb.append("     contents,           \n");
			sb.append("     reg_id,             \n");
			sb.append("     reg_dt              \n");
			sb.append(" ) VALUES (              \n");
			sb.append("     SEQ_BOARD.nextval,  \n");
			sb.append("     ?,                  \n");
			sb.append("     ?,                  \n");
			sb.append("     ?,                  \n");
			sb.append("     SYSDATE             \n");
			sb.append(" )                       \n");
			
			//오류나면 꺼낼 수 있도록 로그 만들기
			LOG.debug("1.=========================");
			LOG.debug("1.query\n:"+sb.toString());
			LOG.debug("1.=========================");
			
			//커넥션 만들기
			conn = connectionMaker.getConnection();
			pstmt= conn.prepareStatement(sb.toString());
			//파람 3개설정(물음표 3개임)
			pstmt.setString(1, vo.getTitle());
			pstmt.setString(2, vo.getContents());
			pstmt.setString(3, vo.getReg_id());
			LOG.debug("2.=========================");
			LOG.debug("2.param\n:"+vo.toString());
			LOG.debug("2.=========================");
			
			//쿼리날리기
			flag = pstmt.executeUpdate();
			LOG.debug("3.=========================");
			LOG.debug("3.flag\n:"+flag);
			LOG.debug("3.=========================");
				
		}catch(SQLException e){
			LOG.debug("=========================");
			LOG.debug("SQLException"+e.toString());
			LOG.debug("=========================");
			
		}finally{
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);	
		}
		
		return flag;
	}

	
	//수정
	@Override
	public int do_update(DTO dto) {
		NoticeVO vo=(NoticeVO)dto;
		int flag=0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		try{
			StringBuilder sb = new StringBuilder();
			sb.append(" UPDATE board            \n");
			sb.append(" SET title =  ?,         \n");
			sb.append("     contents =  ?,      \n");
			sb.append("     reg_id =  ?,        \n");
			sb.append("     reg_dt = SYSDATE    \n");
			sb.append(" WHERE seq = ?           \n");
			
			conn= connectionMaker.getConnection();
			LOG.debug("1.===========================");
			LOG.debug("1.query\n"+sb.toString());
			LOG.debug("1.===========================");
			
			pstmt = conn.prepareStatement(sb.toString());
			pstmt.setString(1, vo.getTitle());
			pstmt.setString(2, vo.getContents());
			pstmt.setString(3, vo.getReg_id());
			pstmt.setString(4, vo.getSeq());
			LOG.debug("2.===========================");
			LOG.debug("2.param:"+vo);
			LOG.debug("2.===========================");
			
			flag=pstmt.executeUpdate();
			LOG.debug("3.===========================");
			LOG.debug("3.flag:"+flag);
			LOG.debug("3.===========================");
			
		}catch(SQLException s){
			LOG.debug("==========================");
			LOG.debug("SQLException="+s.toString());
			LOG.debug("==========================");
			
		}finally{
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);
		}
				
		return flag;
	}
	//삭제
	@Override
	public int do_delete(DTO dto) {
		NoticeVO vo= (NoticeVO) dto;
		int flag = 0;
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		StringBuilder sb=new StringBuilder();
		sb.append(" DELETE FROM board \n");
		sb.append(" WHERE seq = ?     \n");
		
		try{
		    conn= connectionMaker.getConnection();
			conn.setAutoCommit(false); //트렌잭션을 내가 관리할 수 있게 됨. 원래 디폴드값은 true(자동 커밋)
			LOG.debug("1===========================");
			LOG.debug("query:\n"+sb.toString());
			LOG.debug("1===========================");
			
			pstmt = conn.prepareStatement(sb.toString()); //쿼리 디버깅
			//쿼리 파람세팅 (물음표에 대한 값세팅)
			pstmt.setString(1, vo.getSeq());
			LOG.debug("2===========================");
			LOG.debug("param,seq:\n"+vo.getSeq());
			LOG.debug("2===========================");
			
			// 쿼리날리기
			flag = pstmt.executeUpdate();
			//트렌젝션임. 
			if(flag>0) {
				LOG.debug("2===========================");
				LOG.debug("transaction:\n"+conn);
				LOG.debug("2===========================");
				conn.commit();
			}
			else {
				conn.rollback();
			}
			
		}catch (SQLException e) {
			e.printStackTrace();
		}finally{
			
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);						
	    }
		
		LOG.debug("3=====================");
		LOG.debug("flag:"+flag);
		LOG.debug("3=====================");
		
		return flag;
	}
	//단건검색
	@Override
	public NoticeVO do_selectOne(DTO dto) {
		NoticeVO vo= (NoticeVO) dto;
		NoticeVO outVO = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs= null;
		
		try{
			StringBuilder sb= new StringBuilder();
			sb.append(" SELECT                                               \n");
			sb.append("     seq,                                             \n");
			sb.append("     title,                                           \n");
			sb.append("     read_cnt,                                        \n");
			sb.append("     contents,                                        \n");
			sb.append("     reg_id,                                          \n");
			sb.append("     TO_CHAR(reg_dt,'YYYY-MM-DD HH24:mi:ss') reg_dt   \n");
			sb.append(" FROM                                                 \n");
			sb.append("     board                                            \n");
			sb.append(" WHERE seq = ?                                        \n");
			
			//커넥션 만들기
			conn= connectionMaker.getConnection();
			LOG.debug("1.==========================");
			LOG.debug("1. conn:"+conn);
			LOG.debug("1.query:\n"+sb.toString());
			LOG.debug("1.==========================");
			
			//prepareStatement 만들기
			pstmt = conn.prepareStatement(sb.toString());
			//쿼리 파람세팅(물음표 세팅)
			pstmt.setString(1, vo.getSeq()); //첫번째 물음표에 vo에 들어있는 값을 넣는다는 의미
			LOG.debug("2.==========================");
			LOG.debug("2.param seq:\n"+vo.getSeq());
			LOG.debug("2.==========================");
			
			//쿼리 날리기 
			rs = pstmt.executeQuery();
			//커서이동 반드시 해줘야함
			if(rs.next()){
				outVO = new NoticeVO();
				outVO.setSeq(rs.getString("seq"));
				outVO.setTitle(rs.getString("title"));
				outVO.setRead_cnt(rs.getString("read_cnt"));
				outVO.setContents(rs.getString("contents"));
				outVO.setReg_id(rs.getString("reg_id"));
				outVO.setReg_dt(rs.getString("reg_dt")); 
			}
			
		}catch(SQLException e){
			LOG.debug("=========================");
			LOG.debug("SQLException="+e.getMessage());
			LOG.debug("=========================");
			
		}finally{
			JDBCReturnReso.close(rs);
			JDBCReturnReso.close(pstmt);
			JDBCReturnReso.close(conn);	
		}
		
		return outVO;
	}
	//목록검색
	@Override
	public List<?> do_retrieve(DTO dto) {
		
		SearchVO vo= (SearchVO)dto;
		List<NoticeVO> list=new ArrayList<>();
		Connection conn = null;//db 연결
		PreparedStatement pstmt = null;//query수행
		ResultSet rs = null;//결과처리 
			
		//검색 query
		StringBuilder sbWhere=new StringBuilder();
		//제목=10,내용=20,ID=30
		if(null != vo){
			if("10".equals(vo.getSearchDiv())){
				sbWhere.append("WHERE title like ?||'%' \n");
			}else if("20".equals(vo.getSearchDiv())){
				sbWhere.append("WHERE contents like ?||'%' \n");
			}else if("30".equals(vo.getSearchDiv())){
				sbWhere.append("WHERE reg_id like ?||'%' \n");
			}
		}
			
			//main query
		StringBuilder sb=new StringBuilder();
		sb.append(" SELECT T1.*,T2.*                                            \n");
		sb.append(" FROM                                                        \n");
		sb.append(" (                                                           \n");
		sb.append("     SELECT b.rnum num,                                      \n");
		sb.append("            b.seq,                                           \n");
		sb.append("            b.title,                                         \n");
		sb.append("           (SELECT COUNT(*) FROM read_cnt BR WHERE BR.SEQ=B.SEQ  ) read_cnt, \n"); 
		sb.append("            b.contents,                                      \n");
		sb.append("            b.reg_id,                                        \n");
		sb.append("            DECODE(TO_CHAR(b.reg_dt,'YYYY-MM-DD')            \n");
		sb.append("                  ,TO_CHAR(SYSDATE,'YYYY-MM-DD')             \n");
		sb.append("                  ,TO_CHAR(b.reg_dt,'HH24:mi')               \n");
		sb.append("                  ,TO_CHAR(b.reg_dt,'YYYY-MM-DD')) as reg_dt \n"); 
		sb.append("     FROM(                                                   \n");
		sb.append("         SELECT ROWNUM rnum,A.*                              \n");
		sb.append("         FROM(                                               \n");
		sb.append("             SELECT a.*                                      \n");
		sb.append("             FROM board a                                    \n");
		sb.append("             --SEARCH CONDITION                              \n"); 
			//-------------------------------------------------------------------------------
			if(null != vo.getSearchDiv()){//검색구분
				if(null != vo.getSearchWord() && vo.getSearchWord().length()>0){ 
					sb.append(sbWhere.toString());
				}
			}
			//-------------------------------------------------------------------------------		
			
			sb.append(" 		ORDER BY a.reg_dt DESC                                  \n");  
			sb.append(" 	)A                                                        \n");  
			//sb.append("     WHERE ROWNUM <=(&PAGE_SIZE*(&PAGE_NUM-1)+&PAGE_SIZE)  )B  \n");  
			//sb.append(" WHERE B.rnum>= (&PAGE_SIZE*(&PAGE_NUM-1)+1)                   \n");  
			sb.append("     WHERE ROWNUM <=( ? * ( ?-1)+ ?)  )B    		              \n");  
			sb.append(" WHERE B.rnum>= ( ? * ( ?-1)+1)                  		       \n");  
			sb.append("                                                               \n");  
			sb.append(" )T1                                                           \n");  
			sb.append(" CROSS JOIN                                                    \n");  
			sb.append(" (                                                             \n");  
			sb.append(" SELECT COUNT(*) total_cnt                                     \n");  
			sb.append(" FROM board  a                                                 \n");
			sb.append(" --SEARCH CONDITION                                           \n");  
			//-------------------------------------------------------------------------------
			if(null != vo.getSearchDiv() ){//검색구분
				if(null != vo.getSearchWord() && vo.getSearchWord().length()>0){//검색어가 있는냐
					sb.append(sbWhere.toString());
				}
			}		
			//-------------------------------------------------------------------------------		
			sb.append( " )T2                                                             \n");		
			
			LOG.debug("2 sql \n:"+sb.toString());
			try{
				conn = new ConnectionMaker().getConnection();
				pstmt = conn.prepareStatement(sb.toString());
				
				//param
				if(null != vo.getSearchDiv()&& !"".equals(vo.getSearchDiv())){
					//검색어
					//PAGE_SIZE
					//PAGE_NUM
					//PAGE_SIZE
					//PAGE_SIZE
					//PAGE_NUM
					//검색어
					pstmt.setString(1, vo.getSearchWord());
					pstmt.setInt(2, vo.getPageSize());
					pstmt.setInt(3, vo.getPageNum());
					pstmt.setInt(4, vo.getPageSize());
					pstmt.setInt(5, vo.getPageSize());
					pstmt.setInt(6, vo.getPageNum());	
					pstmt.setString(7, vo.getSearchWord());
				}else{//검색이 없는 경우
					//PAGE_SIZE
					//PAGE_NUM
					//PAGE_SIZE
					//PAGE_SIZE
					//PAGE_NUM
					pstmt.setInt(1, vo.getPageSize());
					pstmt.setInt(2, vo.getPageNum());
					pstmt.setInt(3, vo.getPageSize());
					pstmt.setInt(4, vo.getPageSize());
					pstmt.setInt(5, vo.getPageNum());				
				}
				LOG.debug("3 param \n:"+vo);
				rs = pstmt.executeQuery();
				while(rs.next()){
					NoticeVO outVO=new NoticeVO();
					outVO.setNum(rs.getInt("num"));
					outVO.setSeq(rs.getString("seq"));
					outVO.setTitle(rs.getString("title"));
					outVO.setRead_cnt(rs.getString("read_cnt"));
					outVO.setContents(rs.getString("contents"));
					outVO.setReg_id(rs.getString("reg_id"));
					outVO.setReg_dt(rs.getString("reg_dt"));
					outVO.setTotal(rs.getInt("total_cnt"));
					
					list.add(outVO);
				}
				
			}catch(SQLException e){
				e.printStackTrace();
			}finally{
				JDBCReturnReso.close(rs);
				JDBCReturnReso.close(pstmt);
				JDBCReturnReso.close(conn);					
			}
			
			
			return list;
	}

}

 

NoticeService.java

- 조회할 때 ip에 따라 조회수를 늘려야하므로 서비스를 사용하였습니다.

package notice1;

import java.util.List;

import org.apache.log4j.Logger;

import cmn.DTO;
import read_cnt.ReadCntVO;


public class NoticeService {
	private final Logger LOG=Logger.getLogger(NoticeService.class);
	private NoticeDao noticeDao;
	
	//생성자의 목적은 초기화 
	public NoticeService(){
		noticeDao=new NoticeDao();
	}
	/**
	 * 
	 * @Method Name  : do_insert
	 * @작성일   : 2019. 7. 19.
	 * @작성자   : sist
	 * @변경이력  : 최초작성
	 * @Method 설명 :등록 기능 
	 * @param dto
	 * @return
	 */
	public int do_insert(DTO dto){
		return noticeDao.do_insert(dto);
	}
	/**
	 * 
	 * @Method Name  : do_update
	 * @작성일   : 2019. 7. 19.
	 * @작성자   : sist
	 * @변경이력  : 최초작성
	 * @Method 설명 : 수정기능 
	 * @param dto
	 * @return
	 */
	public int do_update(DTO dto){
		return noticeDao.do_update(dto);
	}
	/**
	 * 
	 * @Method Name  : do_delete
	 * @작성일   : 2019. 7. 19.
	 * @작성자   : sist
	 * @변경이력  : 최초작성
	 * @Method 설명 :삭제기능 
	 * @param dto
	 * @return
	 */
	public int do_delete(DTO dto){
		return noticeDao.do_delete(dto);
		
	}
	//단건조회 
	public NoticeVO do_selectOne(DTO dto){
		NoticeVO inVO =  (NoticeVO)dto;
		//단건조회
		NoticeVO outVO = (NoticeVO) noticeDao.do_selectOne(dto);
		//조회관리
			ReadCntVO readCntVO=new ReadCntVO();
			readCntVO.setSeq(inVO.getSeq());
			readCntVO.setIp(inVO.getIp());
		//조회수 증가 
		int flag = noticeDao.do_retSelectCnt(readCntVO);
		LOG.debug("1.do_selectOne=====================");
		if(flag == 0){
			flag= noticeDao.do_retInsert(readCntVO);
			LOG.debug("0-flag------------------"+flag);
			outVO.setwFlag(flag);
		}
		LOG.debug("1.outVO"+outVO);
		LOG.debug("1.do_selectOne=====================");
				
		return outVO;
		
	}
	//리스트조회
	public List<NoticeVO> do_retrieve(DTO dto) {
		return (List<NoticeVO>) noticeDao.do_retrieve(dto); 
	}
}

 

NoticeCrtl.java

-jsp와 연결할 서블릿 컨트롤러를 생성하였다. 

-doGet, doPost를 사용하지 않고 handler를 사용하여 case로 분기하는 방식으로 개발되었다.

package notice1;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.html.HTMLDocument.HTMLReader.HiddenAction;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import cmn.MessageVO;
import cmn.SearchVO;
import cmn.StringUtil;

/**
 * Servlet implementation class NoticeCtrl
 */
@WebServlet(description = "공지사항 게시판", urlPatterns = { "/villa/notice.do" })
public class NoticeCtrl extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private NoticeService noticeService;
	private final Logger LOG = Logger.getLogger(NoticeDao.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NoticeCtrl() {
    	noticeService= new NoticeService();
    
    }
    //글쓰기 이동
    public void do_write_move(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	LOG.debug("02 do_write_move()");
    	
       	//화면제어: readonly
    	request.setAttribute("mode", "insert");
    	RequestDispatcher dispatcher = request.getRequestDispatcher("/villa/noticePost.jsp");
    	dispatcher.forward(request, response);
 
    }
    
    
    protected void doServiceHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	//기능 분기 
    	LOG.debug("02 doServiceHandler()");
    	//work div가 들어오면 분기해서 처리한다 
    	request.setCharacterEncoding("UTF-8");
    	//request null 처리 
    	String workDiv = StringUtil.nvl(request.getParameter("work_div"),""); //request null 뜨면 ""으로 뜨도록 util로 묶어준다.
    	LOG.debug("02.1 workDiv"+workDiv);
    	
    	//case로 분기 하기 
    	/*do_retrieve : 목록
    	 *do_insert: 등록
    	 *do_update: 수정
    	 *do_selectone:단건조회
    	 *do_delete:삭제 
    	 */
    	//workDiv로 구분한다.
    	switch(workDiv){
    		case "do_write_move":
    			do_write_move(request,response);
    			break;
			case "do_insert": 
				//호출되는지 확인 
				do_insert(request,response);
				break;
			case "do_update": 
				//호출되는지 확인 
				do_update(request,response);
				break;
			case "do_delete": 
				//호출되는지 확인 
				do_delete(request,response);
				break;
			case "do_selectone": 
				//호출되는지 확인 
				do_selectone(request,response);
				break;
			case "do_retrieve": 
				//호출되는지 확인 
				do_retrieve(request,response);
				break;
	    	}
    }
    
    private void do_insert(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		LOG.debug("03.1 do_insert");
		NoticeVO inVO = new NoticeVO();
    	//param
		String seq= StringUtil.nvl(request.getParameter("seq"), "");
    	String title = StringUtil.nvl(request.getParameter("tname"),"");
        String readCnt = StringUtil.nvl(request.getParameter("read_cnt"),"");
        String contents = StringUtil.nvl(request.getParameter("contents"),"");
        String regId = StringUtil.nvl(request.getParameter("reg_id"),"admin");
        String regDt = StringUtil.nvl(request.getParameter("reg_dt"),"");
        inVO.setSeq(seq);
        inVO.setTitle(title);
        inVO.setRead_cnt(readCnt);
        inVO.setContents(contents);
        inVO.setReg_id(regId);
        inVO.setReg_dt(regDt);
    	LOG.debug("03.2 param:"+inVO);
   
    	int flag= this.noticeService.do_insert(inVO);
    	LOG.debug("03.3 flag:"+flag);
    	//--param
    	
    	Gson gson = new Gson();
    	response.setContentType("text/html;charset= utf-8");
    	PrintWriter out = response.getWriter();
    	
    	String msg ="";
    	String gsonString ="";
    	if(flag>0){
    		msg= "글을 등록하였습니다.";
    	}else{
    		msg="등록실패";
    	}
    	gsonString = gson.toJson(new MessageVO(String.valueOf(flag),msg));
    	LOG.debug("03.4 gsonString:"+gsonString);
    	out.print(gsonString);
    }
	

	private void do_update(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		LOG.debug("03.1 do_update");	
		NoticeVO inVO = new NoticeVO();
    	//param
		String seq= StringUtil.nvl(request.getParameter("seq"), "");
    	String title = StringUtil.nvl(request.getParameter("tname"),"");
        String readCnt = StringUtil.nvl(request.getParameter("read_cnt"),"");
        String contents = StringUtil.nvl(request.getParameter("contents"),"");
        String regId = StringUtil.nvl(request.getParameter("reg_id"),"admin");
        String regDt = StringUtil.nvl(request.getParameter("reg_dt"),"");
        inVO.setSeq(seq);
        inVO.setTitle(title);
        inVO.setRead_cnt(readCnt);
        inVO.setContents(contents);
        inVO.setReg_id(regId);
        inVO.setReg_dt(regDt);
    	LOG.debug("03.2 param:"+inVO);
    	
    	int flag= this.noticeService.do_update(inVO);
    	LOG.debug("03.3 flag:"+flag);
    	//--param
    	
    	Gson gson = new Gson();
    	response.setContentType("text/html;charset= utf-8");
    	PrintWriter out = response.getWriter();
    	
    	String msg ="";
    	String gsonString ="";
    	if(flag>0){
    		msg= "글을 수정하였습니다.";
    	}else{
    		msg="수정실패";
    	}
    	gsonString = gson.toJson(new MessageVO(String.valueOf(flag),msg));
    	LOG.debug("03.4 gsonString:"+gsonString);
    	out.print(gsonString);
	}

	private void do_delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		LOG.debug("03.1 do_delete");
		//service call 삭제
		NoticeVO inVO = new NoticeVO();
    	//param: seq
    	String seq = StringUtil.nvl(request.getParameter("seq"),""); //null처리 디폴트 값은 ""
    	inVO.setSeq(seq);
    	int flag= noticeService.do_delete(inVO);
    	LOG.debug("03.2 flag: "+flag);
    	//JSON
    	Gson gson = new Gson();
    	response.setContentType("text/html;charset=utf-8"); 
    	PrintWriter out = response.getWriter();
    	String msg = "";
    	String gsonString ="";
    	
    	//msgId=flag
    	//msgContents ='삭제되었습니다';
    	
    	//삭제되었습니다. 알림
    	if(flag>0){
    		msg="삭제되었습니다.";
    	}else{
    		msg="삭제 실패.";
    	}
    	gsonString=gson.toJson(new cmn.MessageVO(String.valueOf(flag),msg));
    	LOG.debug("03.3 gsonString: "+gsonString);
    	out.print(gsonString);
    	
	}
	
	private void do_selectone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("03.1 do_selectone");
		//param 세팅
		NoticeVO inVO = new NoticeVO();
		String seq= StringUtil.nvl(request.getParameter("seq"), "");
		// ip 찾는 것 request.getRemoteAddr('')
		String ip= StringUtil.nvl(request.getRemoteAddr(),"0.0.0.0");
		LOG.debug("03.2 ip:"+ip);
		HttpSession  session= request.getSession();
		//String userId = (String) session.getAttribute("user_id");
    	//String regId = StringUtil.nvl(userId,"admin");
    	
        inVO.setSeq(seq);
        inVO.setIp(ip);
        //TO_DO: session으로 변경 할것
    	//inVO.setReg_id(regId);
      
    	LOG.debug("03.2 inVO:"+inVO);
    	NoticeVO outVO =noticeService.do_selectOne(inVO);
    	LOG.debug("03.3 outVO:"+outVO);  	
    	request.setAttribute("vo",outVO);
    	
    	//화면제어 
    	request.setAttribute("mode", "udlate");
    	RequestDispatcher dispatcher = request.getRequestDispatcher("/villa/noticePost.jsp");
    	dispatcher.forward(request, response);
    	
	}
	
	private void do_retrieve(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("03.1 do_retrieve");
        SearchVO inVO = new SearchVO();
        String pageNum = StringUtil.nvl(request.getParameter("page_num"),"1");
        String searchDiv = StringUtil.nvl(request.getParameter("search_div"),"");
        String searchWord = StringUtil.nvl(request.getParameter("search_word"),"");
        String pageSize = StringUtil.nvl(request.getParameter("page_size"),"10");
        inVO.setPageNum(Integer.parseInt(pageNum));
        inVO.setSearchDiv(searchDiv);
        inVO.setSearchWord(searchWord);
        inVO.setPageSize(Integer.parseInt(pageSize));
        
        LOG.debug("03.2 inVO:"+inVO);
        List<NoticeVO> list = noticeService.do_retrieve(inVO);
        LOG.debug("-----------------------");
        for(NoticeVO vo:list){
           LOG.debug(vo);
        }
        LOG.debug("-----------------------");
        int totalCnt =0; //초기화
        //총 글수
        if(null !=list &&list.size()>0){
        	NoticeVO totalVO = list.get(0);
    		totalCnt = totalVO.getTotal();
    	}
        request.setAttribute("totalCnt",totalCnt);
        
        request.setAttribute("list",list);
        request.setAttribute("paramVO", inVO);
        RequestDispatcher dispacher= request.getRequestDispatcher("/villa/noticeList.jsp");
        dispacher.forward(request, response);
	}
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("01 doGet()");
		LOG.debug("01.1 noticeService:"+noticeService);
		doServiceHandler(request,response);//doServiceHandler로 모아준다. 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOG.debug("01 doPost()");
		LOG.debug("01.1 noticeService:"+noticeService);
		doServiceHandler(request,response);	
	}

}

 

jsp로 만든 view는 게시판 만들기 2에 업로드 하겠습니다

반응형

'teamPJ' 카테고리의 다른 글

게시판 만들기2- 관리자용뷰 jsp파일  (0) 2019.08.14
펜션 홈페이지 만들기 - 테이블 구조  (0) 2019.08.14