레이블이 Java Object인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Java Object인 게시물을 표시합니다. 모든 게시물 표시

2013년 10월 11일 금요일

[야간,Spring3.x]스프링게시판,Spring DI설정을 annotation으로

스프링3.X 게시판 (DI설정을 애노테이션으로 변경), XML설정-->Annotation으로...
 
지금까지 구현한 게시판의 기본 기능은 다음과 같다.
 
스프링게시판 현재 1차 버전까지의 기능(게시판 리스트보기 + 게시물 본문내용 미리 보기 + 게시 글 상세보기 + 커멘트(댓글)기능 + 글쓰기 + 글 수정하기 + 글 삭제하기 + 답변 글)
(http://www.oraclejavanew.kr/bbs/board.php?bo_table=LecSpring&wr_id=261&page=2)
 
그리고 마지막으로 Controller를 @Controller, @RequestMapping을 이용하여 변경 하였다.
(http://www.oraclejavanew.kr/bbs/board.php?bo_table=LecSpring&wr_id=261&page=2)
 
이번 강좌에서는 이 소스를 기본으로 스프링 주입(DI)을 애노테이션으로 변경해 보자. Spring Framework XML설정 파일이 깔끔해 진다.
 
그리고 다음 강좌에서 진행될 DAO단 Spring AOP를 적용하여 로깅하기를 위해 미라 SqlProvider를 구현하자. (jdbcTemplate에서 실행 sql문을 받아 내기 위해)
 

1. BoardDAO.java
 
package onj.board.dao;
import java.util.List;
import onj.board.model.BoardDTO;
import onj.board.model.CommentDTO;
import org.springframework.dao.DataAccessException;

public interface BoardDAO {
 //게시물 리스트 보기
 public List<BoardDTO> boardList() throws DataAccessException;

 //게시물 본문 미리보기
 public String preView(String seq) throws DataAccessException;

 //게시물 본문 읽기
 public BoardDTO readContent(String seq) throws DataAccessException;

 //읽은 글의 조회수 1증가
 public int updateReadCount(String seq) throws DataAccessException;

 //Comment저장
 public int insertComment(CommentDTO commentDTO) throws DataAccessException ;

 //Comment조회
 public List<CommentDTO> commentList(String seq) throws DataAccessException;

 //게시글 입력
 public int insertBoard(BoardDTO board) throws DataAccessException;

 //글 수정
 public int updateBoard(BoardDTO board) throws DataAccessException;

 //글 삭제
 public int deleteBoard(String sid , String password) throws DataAccessException;

 //답글 달기
 public int replyBoard(BoardDTO board) throws DataAccessException;

 //SQL리턴용
 public String getSql();


 
}
 
 

2. onj.board.dao.SpringBoardDAO.java
 
package onj.board.dao;
 
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import onj.board.model.BoardDTO;
import onj.board.model.CommentDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlProvider;
import org.springframework.stereotype.Component;
 
//아래 SqlProvider는 jdbcTemplate이 실행될 때의 SQL문장을 받아내기 위하여 구현, getSql()
@Component("boardDAO")
public class SpringBoardDAO implements BoardDAO, SqlProvider {
 private JdbcTemplate jdbcTemplate = null;
 String sql = "";
 @Autowired
 private DataSource dataSource;
 
 public JdbcTemplate getTemplate() {
  if (jdbcTemplate == null) {
   this.jdbcTemplate = new JdbcTemplate(dataSource);
  }
  return jdbcTemplate;
 }
 
@Override
 public String getSql() {
  // TODO Auto-generated method stub
  return sql;
 }

 // /게시판 전체 리스트 보기(list.html)
 public List<BoardDTO> boardList() throws DataAccessException {
  List<BoardDTO> boardList = null;
  // String sql = "select * from board";
 
  sql = " select * from  (select seq, name , passwd, "
    + "                        title, content, filename, regdate, "
    + "                        readcount, reply, reply_step, "
    + "                        reply_level , rownum r "
    + "                   from board "
    + "                  order by reply desc , reply_step asc)";
  boardList = getTemplate().query(sql, new RowMapper() {
   public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
    BoardDTO board = new BoardDTO();
    board.setSeq(rs.getInt("seq"));
    board.setName(rs.getString("name"));
    board.setPasswd(rs.getString("passwd"));
    board.setTitle(rs.getString("title"));
    board.setContent(rs.getString("content"));
    board.setFileName(rs.getString("filename"));
    board.setRegDate(rs.getString("regdate"));
    board.setReadCount(rs.getInt("readcount"));
    board.setReply(rs.getInt("reply"));
    board.setReply_step(rs.getInt("reply_step"));
    board.setReply_level(rs.getInt("reply_level"));
    return board;
   }
  });
  return boardList;
 }
 // 게시물 본문내용 미리보기(/preView)
 public String preView(String seq) throws DataAccessException {
  sql = "select * from board where seq = ?";
  String preContent = (String) getTemplate().queryForObject(sql,
    new Object[] { seq }, new RowMapper() {
     public Object mapRow(ResultSet rs, int rowNum)
       throws SQLException {
      return rs.getString("content");
     }
    });
  return preContent;
 }
 // 게시판 상세보기, 게시글 읽기
 public BoardDTO readContent(String seq) throws DataAccessException {
  sql = "select * from board where seq = ?";
  BoardDTO boardDTO = (BoardDTO) getTemplate().queryForObject(sql,
    new Object[] { seq }, new RowMapper() {
     public Object mapRow(ResultSet rs, int rowNum)
       throws SQLException {
      BoardDTO board = new BoardDTO();
      board.setSeq(rs.getInt("seq"));
      board.setName(rs.getString("name"));
      board.setPasswd(rs.getString("passwd"));
      board.setTitle(rs.getString("title"));
      board.setContent(rs.getString("content"));
      board.setFileName(rs.getString("filename"));
      board.setRegDate(rs.getString("regdate"));
      board.setReadCount(rs.getInt("readcount"));
      board.setReply(rs.getInt("reply"));
      board.setReply_step(rs.getInt("reply_step"));
      board.setReply_level(rs.getInt("reply_level"));
      return board;
     }
    });
  // 글 조회수 1증가
  this.updateReadCount(new Integer(boardDTO.getSeq()).toString());
  return boardDTO;
 }
 // 읽은 글의 조회수를 1증가
 public int updateReadCount(String seq) throws DataAccessException {
  sql = "update board set readcount = nvl(readcount,0) + 1 where seq = ?";
  Object[] obj = { seq };
  return getTemplate().update(sql, obj);
 }
 // 커맨트 입력
 public int insertComment(CommentDTO commentDTO) throws DataAccessException {
  sql = "insert into comment_t(seq, name, comm) values (?, ?, ?)";
  Object[] obj = { commentDTO.getSeq(), // 게시글순번
    commentDTO.getName(), // 작성자
    commentDTO.getComment() }; // 커맨트
  return getTemplate().update(sql, obj);
 }
 // 커맨트 조회
 public List<CommentDTO> commentList(String seq) throws DataAccessException {
  sql = "select * from comment_t where seq = ?";
  List<CommentDTO> commentList = getTemplate().query(sql,
    new Object[] { seq }, new RowMapper() {
     public Object mapRow(ResultSet rs, int rowNum)
       throws SQLException {
      CommentDTO commentDTO = new CommentDTO();
      commentDTO.setName(rs.getString("name"));
      commentDTO.setComment(rs.getString("comm"));
      return commentDTO;
     }
    });
  return commentList;
 }
 // 글쓰기
 public int insertBoard(BoardDTO board) throws DataAccessException {
  sql = "insert into board values(board_seq.nextval , ? , ? , ? , ? , ? , sysdate , 0 , board_seq.currval , 0 , 0)";
  if (board.getFileName() == null) {
   Object[] obj = { board.getName(), board.getPasswd(),
     board.getTitle(), board.getContent(), "" };
   return getTemplate().update(sql, obj);
  } else {
   Object[] obj = { board.getName(), board.getPasswd(),
     board.getTitle(), board.getContent(), board.getFileName() };
   return getTemplate().update(sql, obj);
  }
 }
 // 게시글 수정
 public int updateBoard(BoardDTO board) throws DataAccessException {
  sql = "update board set  title = ? , content = ? where seq = ?";
  Object[] obj = { board.getTitle(), board.getContent(), board.getSeq() };
  return getTemplate().update(sql, obj);
 }
 // 게시글 삭제
 public int deleteBoard(String seq, String passwd)
   throws DataAccessException {
  int result = 0;
  String sql = "delete from board where seq = ? and passwd = ?";
  result = getTemplate().update(sql, new Object[] { seq, passwd });
  return result;
 }
 // 답글달기
 public int replyBoard(BoardDTO boardDTO) throws DataAccessException {
  int result = 0;
  String name = boardDTO.getName();
  String passwd = boardDTO.getPasswd();
  String title = boardDTO.getTitle();
  String content = boardDTO.getContent();
  String fileName = boardDTO.getFileName();
  int reply = boardDTO.getReply();
  int reply_step = boardDTO.getReply_step();
  int reply_level = boardDTO.getReply_level();
  // 현재 답변을 단 게시물 보다 더 높은 스텝의 게시물이 있다면 스텝을 하나씩 상승시킴
  sql = "update board set reply_step = reply_step + 1 "
    + "where reply = " + reply + " and reply_step > " + reply_step;
  getTemplate().update(sql);
  sql = "insert into board values(board_seq.nextval , ? , ? , ? , ? , ? , sysdate , 0 , ? , ? , ?)";
  // reply_step과 reply_level을 1씩 증가시킨 후 내용을 저장
  Object[] obj2 = { name, passwd, title, content, fileName, reply,
    reply_step + 1, reply_level + 1 };
  result = getTemplate().update(sql, obj2);
  return 0;
 }
}
 

3. BoardServiceImpl.java
 
package onj.board.service;
 
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import onj.board.dao.BoardDAO;
import onj.board.model.BoardDTO;
import onj.board.model.CommentDTO;
 
@Component("boardService")
public class BoardServiceImpl implements BoardService {
    @Autowired
    private BoardDAO boardDAO;

   
    //게시물 리스트 보기
    public List<BoardDTO> boardList() {
     return boardDAO.boardList();
    }
   
    //게시물 본문 내용 미리보기
    public String preView(String seq) {
     return boardDAO.preView(seq);
    }
    //게시글 읽기
 public BoardDTO readContent(String seq) {
  return boardDAO.readContent(seq);
 }
 //커맨트 입력
 public int insertComment(CommentDTO commentDTO) {
  return boardDAO.insertComment(commentDTO);
 }
 //커맨트 조회
 public List<CommentDTO> commentList(String seq) {
  return boardDAO.commentList(seq);
 }   

 //게시글 입력
 public int insertBoard(BoardDTO board) {
  return boardDAO.insertBoard(board);
 }

 //게시글 수정
 public int updateBoard(BoardDTO board) {
  return boardDAO.updateBoard(board);
 }

 //게시글 삭제
 public int deleteBoard(String seq, String passwd) {
  return boardDAO.deleteBoard(seq, passwd);
 }

 //답글 등록
 public int replyBoard(BoardDTO board){
  return boardDAO.replyBoard(board);
 }

}
 
 

4. /WEB-INF/boardConfig.xml
 <aop:aspectj-autoproxy/>
 <context:component-scan base-package="onj.board.dao"/>
 <context:component-scan base-package="onj.board.service"/> 

</beans> 

2013년 8월 1일 목요일

자바의 OutputStream (JAVA OutputStream)

OutputStream 클래스는 모든 파일 시스템으로부터 스트림의 한 바이트를 쓴다. 
  public abstract void write(int b): 정수 b를 byte로 변환하여 출력한다.
  public void write(byte b[]): 배열 b의 모든 바이트를 쓴다.
  public void write(byte b[], int off, int len): b의 off 위치로부터 len만큼 쓴다. 
  public void close(): 출력 스트림을 닫는다.
  public void flush(): 버퍼에 남겨진 모든 데이터를 목적지에 보낸다.
  InputStream과 OutputStream은 추상 메소드를 포함하여 바이트들과 바이트 배열들을 읽고 쓰기 위하여 read()와 write()를 사용하는데 실제로 바이트 스트림을 읽고 쓰는 경우가 드물기 때문에 이 메소드는 거이 이용하지 않는다. 왜냐하면 자바에서 문자열은 바이트가 아니라 유니코드로서 일반적으로 숫자, 문자열, 객체형태로 입출력되기 때문이다. 


public class Iotest { //입력 문자열을 그대로 출력 
      public static void main(String []args) throws java.io.IOException {
            int i;
            while ((i=System.in.read())!=-1)
                System.out.write(i); // 정수 i를 문자로 바꾸어 출력한다.
      }
 }

Java.lang.Object 클래스

자바의 모든 클래스는 Object 클래스의 하위 클래스이므로 Object 클래스의 모든 메소드를 사용할 수 있다. Object 클래스의 메소드는 클래스의 객체를 조작하기 위한 가장 기본적인 메소드만을 제공하는데 그 중 주요 메소드만을 소개하면 다음과 같다. 

public java.lang.Class getClass() 
  현재 객체의 원형 클래스에 대한 정보를 자바의 Class 타입으로 반환하는 메소드이다. 두개의 객체가 동일 클래스의 객체인지 비교할 때 유용하다. 

public boolean equals(Object obj)
  현재 객체가 다른 객체(obj)와 내용이 동일한지를 비교하는 메소드이다. 이 메소드는 객체의 내부 필드와 메소드의 구조가 완전히 동일하고 또 필드에 설정되어 있는 값도 동일한지를 비교한다. 

protected java.lang.Object clone() 
  객체를 완전히 복사할 때 사용하는 메소드이다. =의 경우는 참조하는 위치만 전달하지만 clone의 경우는 새로운 객체를 만들어 값까지 동일하게 복사한다. 

public java.lang.String toString() 
  객체를 문자열의 형태로 변환하는 데 사용하는 메소드이다. 보통 객체를 대표할 수 있는 값을 문자열로 반환한다. 
 
protected void finalize()
객체가 더이상 사용되지 않을 때 쓰레기 수집기에 의해 수행되는 메소드이다. 이 메소드는 객체가 사용한 파일이나 데이터베이스를 닫을 때 주로 사용된다.