레이블이 JAVA Factorial인 게시물을 표시합니다. 모든 게시물 표시
레이블이 JAVA Factorial인 게시물을 표시합니다. 모든 게시물 표시

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월 8일 목요일

[오라클자바커뮤니티, ORACLEJAVANEW.KRstruts file upload DynaValidatorForm

Struts  ActionForm에서 구현한 형태입니다. 


오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  


이번엔 DynaValidatorForm에서 구현한 형태입니다.


======================================================================
============== struts-config.xml ============================================================================================================



name="applicationForm"
type="org.apache.struts.validator.DynaValidatorForm">


name="file"
type="org.apache.struts.upload.FormFile"/>


=============================================================================================== file_upload.jsp ==============================
======================================================================






======================================================================
======================= FileUploadAction ==============================
======================================================================

action class (though it's not getting this far using IE):
FormFile file= (FormFile)dForm.get("file");

2013년 8월 6일 화요일

(오라클자바커뮤니티, 자바교육, 오라클교육)Struts Exception Handler

ㅍException Handler

Action은 검사를 마친 예외들의 전부 혹은 일부를 ActionServlet으로 돌려 보내며 예외들을 처리하게 됩니다.

만약 ActionServlet이 예외를 처리 한다면 서블릿은 예외의 타입이나 상위 타입을 위한 Handler가 등록되었는지 검사 합니다.

ActionMapping 클래스의 지역 Exception Handler를 먼저 확인하고 그 다음 전역(global) 예외들을 검색 합니다.

ExceptionHandler는 exception 요소를 사용하여 다음과 같이 등록 합니다.

<exception
        type = “org.apache.struts.webapps.example.ExpiredPasswordException”
        key = “expired.password”
        path = “/changePWD.jsp” />

만약 ExpiredPasswordException이 발생 한다면 디폴트 핸들러는 특정 키와 특정 경로의 ActionForward를 사용하여 ActionError를 생성 합니다. 그러면 모듈안의 / changePWD.jsp로 포워드 됩니다.

이 순간 JSP는 메시지 리소스 번들로부터 expired.password라는 키에 해당 하는 메시지를 출력 할 것입니다. 만약 path 속성을 생략하게 되면 디폴트 핸들러는 ActionMapping의 input 속성을 이용 합니다.

ExceptionHandler 클래스는 반드시 org.apache.struts.action.ExceptionHandler의 하위 클래스이어야 합니다. 처음 실행되는 메소드는 execute() 메소드 입니다.

Action의 execute() 메소드처럼 작업이 끝나면 ActionForward를 반환하면 됩니다.

org.apache.struts.config.ExceptionConfig 빈은 struts-config.xml에서 exception 요소를 나타내며 특별한 프로퍼티 집합이 필요하면 ExceptionConfig의 서브 클래스를 만든 다음 <set-property> 요소를 사용하여 설정 파일로부터 속성을 초기화 하면 됩니다. 

2013년 8월 4일 일요일

재귀호출을 이용한 팩토리얼 구하기

재귀호출을 이용한 팩토리얼 구하기

 class RecursionTest {
  long factorial(int value) {
  if(value <= 1) return 1L;
  return value*factorial(value-1);
  }
  public static void main(String[] args) {
  if (args.length<1) {
  System.out.println("Usage : java RecursionTest number ");
  System.exit(1);
  }
                                    int value = Integer.parseInt(args[0]);
  RecursionTest r = new RecursionTest();
  long fact = r.factorial(value);
  System.out.println(value + "! = " + fact);
  }