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

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월 9일 금요일

[OracleJavaCommunity,오라클자바커뮤니티]이번 강좌에서는 자바에서의 main 메소드에 대해 자세히 알아 보도록 하겠습니다

이번 강좌에서는 자바에서의 main 메소드에 대해 자세히 알아 보도록 하겠습니다. main 앞에 왜 static이 붙으며 왜 public이 붙는지등에 관한 것을 공부해 보도록 하겠습니다. 잘 알아두시기 바랍니다.


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



main 메소드의 특징 

메인 메소드는 JVM에 의해 자바 프로그램을 실행 할 때 처음 호출되는 메소드 입니다.
메인 메소드는 객체 생성을 위한 첫 실행 메소드 이다. 그러므로 어느 클래스에서 접근이 가능해야 하므로 public 이라는 접근 제어자를 사용 합니다.
해당 클래스로 부터 생성된 모든 객체에서 접근이 가능해야 한다. (static) --> static이라는 말이 붙으면 객체와 관련이 있는 것이 아니라 클래스와 관련이 있으며 초기화가 한번만 일어나며, 클래스가 실행되기 위해 메모리로 로딩되는 시점에 한번만 초기화가 일어 납니다. 즉 전역변수등에 사용되며...등등 [자바기초다지기#7]변수-인스턴스변수, 클래스변수 강좌에서 이미 공부 했던 부분 입니다.
Return 값을 가지지 않습니다.(void)
또한 실행 될 때 인자 값을 받아 들일 수 있습니다.

자바 인터프리터는 Java Application에 주어지는 각 명령형 인자들을 main(String[] args) 메소드에 매개변수로 넘겨 줍니다.
각 명령행 인자는 공백문자(whitespace)로 구분 하며, C/C++에서 메인 함수의 매개변수 개수를 나타내는 argc와 명령형 매개 변수 들을 문자열 배열로 받아 들이는 argv는 결국 Java의 args.length, args로 대체 될 수 있습니다.

[예제]

class ArgTest
{
public static void main (String[] args)
{
for(int i = 0; i < args.length; ++i) //이 프로그램을 실행할때 넘어 오는 아규멘트의 갯수 만큼 루프를 돕니다. >
System.out.println( "args[" + i + "] = " + args[i] );
}
}



[결과1]

java ArgTest test 100 이라고 실행시

args[0] = test
args[1] = 100


[결과2]

java ArgTest "test 100" 이라고 실행시

args[0] = test 100

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월 5일 월요일

(오라클자바교육,ORACELJAVA강좌)JAVA Swing과 JDBC(오라클)를 이용한 예제

//오라클의 EMP Table의 데이터를 가지고 화면에 뿌리는 예제
//이름을 입력하고 Enter Key를 누르면 JDBC를 이용하여  데이터를 가지고 옵니다.


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


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;

class DBTest {
        JTextField name;    JPasswordField tel;  JTextField addr;
        public DBTest() {
                JFrame f = new JFrame();
                Container cp = f.getContentPane();
                cp.setLayout(new FlowLayout());
                name = new JTextField("",10);
                name.setCaretColor(Color.blue);
                tel  = new JPasswordField("",10);
               
                                tel.setEditable(false);
                addr = new JTextField("",10);
                addr.setEditable(false);
                cp.add(new JLabel("성명 : "));        cp.add(name);
                cp.add(new JLabel("전화번호 : ")); cp.add(tel);
                cp.add(new JLabel("주소 : "));        cp.add(addr);

                name.addActionListener( new ActionListener()
                        {
                                public void actionPerformed(ActionEvent ae) {
                                        dataGet();
                                }
                        }
                );
                f.setSize(600, 100);                f.setVisible(true);
        }
       
                public static void main(String[] args) {
                new DBTest();       
        }

        public void dataGet() {
                Connection con=null;
                Statement stmt=null;
                ResultSet rs=null;
                try {
              Class.forName("oracle.jdbc.driver.OracleDriver");                       
                  con = DriverManager.getConnection("jdbc:oracle:thin:@***.***.***.***:1521:WINK", "test", "test");
                  stmt = con.createStatement();
                  rs = stmt.executeQuery("select tel, addr from emp where name = " + "'" + name.getText().trim() + "'");
                  if (rs!=null) {

                                            rs.next();
                          tel.setText(rs.getString("tel"));
                          addr.setText(rs.getString("addr"));
                  }
                }
                catch(Exception e) {System.out.println(e);}
                finally {
                        try        {
                                if (con != null) {con.close();        }
                        }
                        catch (Exception e){}
                }
        }
}