SpringMVC + iBatis 를 이용한 프로젝트 초기 설정 WAR

Published on: 2010. 1. 29. 17:40 by louis.dev
프로젝트를 하다 보면 주로 스프링과 iBatis를 통한 웹개발을 많이 하게 되는데

그때마다 똑같은 설정을 매번하는것이 번거러워 이렇게 초기 설정만해둔 WAR파일을 만들어 보았다.

Spring Framework 2.5 버전이고 elipse에서 import하면 바로 스프링에 대한 설정없이 controller와 service dao 구현만으로 프로젝트를 빠르게 진행 할수 있다.

게시판 Paging Source Code

Published on: 2009. 9. 6. 19:19 by louis.dev

적용 방법
paging을 하고 싶은 페이지에 업로드 된 paging.jsp를 include 한다.

작업 순서
1. Paging 정보를 가지고 있을 Bean 객체를 만든다. 이 Paging Class는 다음과 같은 property를 가진다. 이와 같은 Paging class는 다른 Bean class에서 상속 받아 사용할 수도 있다


[[ PagingBean.java ]]

① private int nowPage;                // 현재 페이지가 몇페이지 인가를 적용
② private int startNum;                // 게시판이 시작되는 ROW의 Number
③ private int totalCount;               // 게시판 총 페이지 수
④ private int countPerPage;         // 페이지당 보여줄 게시판 리스트 갯수
⑤ private int blockCount;             // paging 갯수를 표현함 예를 들어 blockCount = 5 라면 
                        << [1][2][3][4][5] 다음 >>  -> 다음을 클릭하면
                        << [6][7][8][9][10] 다음 >> -> 이런 식으로 페이징 수가 5개가 된다.
⑥ private String searchColumn;     // 검색할 때 사용, 카테고리 선택
⑦ private String searchWord;         // 검색어


2. 기본적으로 늘 초기화 세팅이 되어 있어야할 countPerPage 라든가 blockCount, startNum을 초기화 세팅해줄 PaingUtil Class를 생성한다.
초기화 세팅하지 않을 util 클래스를 작성하지 않으면 페이징 시에 항상 세팅을 해주어야 한다.
만약 페이징 할 모듈이 많고 각각 다른 세팅값을 가져야 한다면 사용자의 요구에 맞게 static method를 정의해 주고 그 안에 있는 값을 세팅을 각각 맞춰서 해주면 된다.


3. Paging을 할 페이지에 paging.jsp 파일을 다음과 같이 include 시킨다.


<jsp:include page="paging.jsp">
     <jsp:param name="actionPath" value="boardList.jsp"/>
     <jsp:param name="totalCount" value="<%=String.valueOf(paging.getTotalCount()) %>"/>
     <jsp:param name="countPerPage" value="<%=String.valueOf(paging.getCountPerPage()) %>"/>
     <jsp:param name="blockCount" value="<%=String.valueOf(paging.getBlockCount()) %>"/>
     <jsp:param name="nowPage" value="<%=String.valueOf(paging.getNowPage()) %>"/>
 </jsp:include>

물론 이 페이지를 인클루드 시키기 전에 위에 파라미터로 넘겨주는 모든 값은 세팅이 되어 있어야 한다.

페이지의 맨상단에서 다음과 같은 코드로 파라미터로 넘어오는 nowPage를 받아야 한다.
if(request.getParameter("nowPage") == null){
  paging.setNowPage(1);
 }else{
  paging.setNowPage(Integer.valueOf(request.getParameter("nowPage")));
 }

totalCount는
   SELECT COUNT(0) FROM 테이블 명
이런 Query문을 날려서 값을 받아 오는 값을 저장하면 된다.

iBatis - SqlMapClient class 만들어 주는 util

Published on: 2009. 8. 8. 03:17 by louis.dev


iBatis를 사용할때 template를 쓰지 않을때는 항상 SqlMapConfig파일을 통해 SqlMapClient를 생성해야 한다. 그것을 쉽게 해주기 위한 Abstract class이다.

package com.myhome.manager;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public abstract class SQLManager {
 
 private SqlMapClient sc = null;
 
 public SQLManager(){
  try{
   sc = SqlMapClientBuilder.buildSqlMapClient(
            Resources.getResourceAsReader(
              "com/myhome/manager/SqlMapConfig.xml"));           //sql설정이 들어가 있는 SqlMapConfig파일 위치 지정
                                                                                            //classes 폴더에 있으면 SqlMapClient.xml로 바로 지정 해도 됨
  }catch(java.io.IOException ie){
   ie.printStackTrace();
  }
 }
 
 public SqlMapClient getSqlMap(){
  return sc;
     }
}

사용방법은 extends로 다음 클래스 파일을 확장 받은다음에 getSqlMap을 통해 SqlMapCleint를 생성한다.

예)

public class UploadDAO extends SQLManager{
 
 public void insert(UploadDTO dto) throws SQLException{
           this.getSqlMap().insert("uploadInsert",dto);
 }

Ajax XMLHttpRequest Object 생성 Util

Published on: 2009. 7. 13. 15:00 by louis.dev


function getXMLHttpRequest() {
 if (window.ActiveXObject) {
  try {
   return new ActiveXObject("Msxml2.XMLHTTP");
  } catch(e) {
   try {
    return new ActiveXObject("Microsoft.XMLHTTP");
   } catch(e1) { return null; }
  }
 } else if (window.XMLHttpRequest) {
  return new XMLHttpRequest();
 } else {
  return null;
 }
}
var httpRequest = null;

function sendRequest(url, params, callback, method) {
 httpRequest = getXMLHttpRequest();
 var httpMethod = method ? method : 'GET';
 if (httpMethod != 'GET' && httpMethod != 'POST') {
  httpMethod = 'GET';
 }
 var httpParams = (params == null || params == '') ? null : params;
 var httpUrl = url;
 if (httpMethod == 'GET' && httpParams != null) {
  httpUrl = httpUrl + "?" + httpParams;
 }
 httpRequest.open(httpMethod, httpUrl, true);
 httpRequest.setRequestHeader(
  'Content-Type', 'application/x-www-form-urlencoded');
 httpRequest.onreadystatechange = callback;  //변환작업이 다끝났으면 callback로 넘어간다.
 httpRequest.send(httpMethod == 'POST' ? httpParams : null);    //method가 post 이면 httpParams를 아니면 null을 리턴한다.
}
---------------------------------------------------------------------------------------------------------
사용할 페이지에서
<script type="text/javascript" src="httpRequest.js"></script>
선언하고 사용하면 된다.

File Upload Rename Policy(파일이름 중복 정책)

Published on: 2009. 7. 6. 16:40 by louis.dev


File Upload를 수행할때 이전에 있던 파일과 비교하여 같은 이름이 있을경우 파일명 뒤에 숫자를 붙여주는 역할을 한다.사용 예)


package com.myhome.upload.policy;

import java.io.File;
import java.io.IOException;

public class FileRenamePolicy {
  
  public File rename(File f) {             //File f는 원본 파일
    if (createNewFile(f)) return f;        //생성된 f가 중복되지 않으면 리턴
    
    String name = f.getName();
    String body = null;
    String ext = null;

    int dot = name.lastIndexOf(".");
    if (dot != -1) {                              //확장자가 없을때
      body = name.substring(0, dot);
      ext = name.substring(dot);
    } else {                                     //확장자가 있을때
      body = name;
      ext = "";
    }

    int count = 0;
    //중복된 파일이 있을때
    //파일이름뒤에 a숫자.확장자 이렇게 들어가게 되는데 숫자는 9999까지 된다.
    while (!createNewFile(f) && count < 9999) {  
      count++;
      String newName = body + count + ext;
      f = new File(f.getParent(), newName);
    }
    return f;
  }

  private boolean createNewFile(File f) { 
    try {
      return f.createNewFile();                        //존재하는 파일이 아니면
    }catch (IOException ignored) {
      return false;
    }
  }
}

다음과 같이 사용할 수 있다.
File file = new File(UploadUtil.SAVE + bean.getFileFileName());
file = new FileRenamePolicy().rename(file);