본문 바로가기
웹개발/웹개발

JSP/JAVA클래스 로 이미지 게시판 만들기 1 (Class편)

by 에르소 2014. 4. 18.

 <완성본>

 

 

 

2014.04.17 // jsp, Java로 이미지 게시판 만들기를 했습니다 :)

 

Tool  : Eclipse / Apache Tomcat 6.0 / NotePad++ / Araxis Merge (Debuging)

 

시중에 있는 책들은 대부분, MySQL 로 되어있는데.. 저는 Oracle Database 10g 로 작업했습니다.

 

Oracle은.. windows 에 설치할경우, 나중에 제거할때 매우 애먹습니다..

개인사용자의 경우 VmPlayer 를 사용하시는게 좋습니다.

 

Dynamic web project 에서, ImageBoard 라는 이름으로 제작했습니다.

 

 

1. 프로젝트 구성 (Project Construction)

Java Resoureces ( class 파일)

WebContent ( jsp 파일)

 

 

 

2. JavaResource 구성 (JavaResource Construction) 

 

 

 

 - ID_SEQUENCES 테이블과 관련된 작업 처리 클래스 : Sequencer

 - 자바빈 클래스 (THEME_MESSAGE,THEME_CONTENT) : Theme

 - 예외처리 클래스 : ThemeManagerException

 - DAO 클래스 : ThemeManager

-insert() : 삽입

-update() : 수정 (Title, Content)

-select()  : 선택 (지정글 읽어오기)

-selectList : 목록읽어오기

-delete : 삭제

-count : 조회수

 - commons-fileupload-1.2.1.jar 파일을 이용한 업로드 클래스 : FileUploadRequestWrapper

 - ImageUtil : 썸네일

 

 

 

 

<썸네일의 정의>

<출처: 네이버 영한사전>

 

 

3. DBCPInit

 package jdbc;

import javax.servlet.http.HttpServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.util.StringTokenizer;

public class DBCPInit extends HttpServlet {
 public void init(ServletConfig config) throws ServletException
 {
  try
  {
   String drivers = config.getInitParameter("jdbcdriver");
   StringTokenizer st = new StringTokenizer(drivers, ",");
   while (st.hasMoreTokens())
   {
    String jdbcDriver = st.nextToken();
    Class.forName(jdbcDriver);
   }

   // Class.forName("oracle.jdbc.driver.OracleDriver");
   Class.forName("org.apache.commons.dbcp.PoolingDriver");
  }
  catch (Exception e)
  {
   throw new ServletException(e);
  }
 }
}

 

 

4. FileUploadRequestWrapper

앞에서 말씀드렸듯.. FileUploadRequset는

commons-fileupload-1.2.1.jar 파일이 있어야 합니다.

 

commons-fileupload-1.2.1.jar 파일은

Link : http://commons.apache.org/proper/commons-fileupload/ (Apache Site)

Link : http://www.google.com (Google)

Link : http:www.naver.com (Naver)

 

아파치 사이트를 들어가시면 나오고, 구글/ 네이버에서 검색해도 나옵니다 :)

<파일설치경로>

 package madvirus.fileupload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.HashMap;
import java.util.Enumeration;
import java.util.Iterator;

public class FileUploadRequestWrapper extends HttpServletRequestWrapper {

 private boolean multipart = false;

 private HashMap parameterMap;
 private HashMap fileItemMap;

 public FileUploadRequestWrapper(HttpServletRequest request)
   throws FileUploadException {
  this(request, -1, -1, null);
 }

 public FileUploadRequestWrapper(HttpServletRequest request, int threshold,
   int max, String repositoryPath) throws FileUploadException {
  super(request);

  parsing(request, threshold, max, repositoryPath);
 }

 private void parsing(HttpServletRequest request, int threshold, int max,
   String repositoryPath) throws FileUploadException {

  if (FileUpload.isMultipartContent(request)) {
   multipart = true;

   parameterMap = new java.util.HashMap();
   fileItemMap = new java.util.HashMap();

   DiskFileUpload diskFileUpload = new DiskFileUpload();
   if (threshold != -1) {
    diskFileUpload.setSizeThreshold(threshold);
   }
   diskFileUpload.setSizeMax(max);
   if (repositoryPath != null) {
    diskFileUpload.setRepositoryPath(repositoryPath);
   }

   java.util.List list = diskFileUpload.parseRequest(request);
   for (int i = 0; i < list.size(); i++) {
    FileItem fileItem = (FileItem) list.get(i);
    String name = fileItem.getFieldName();

    if (fileItem.isFormField()) {
     String value;
     try {
      value = fileItem.getString("euc-kr");

      String[] values = (String[]) parameterMap.get(name);
      if (values == null) {
       values = new String[] { value };
      } else {
       String[] tempValues = new String[values.length + 1];
       // System.arraycopy(values, 0, tempValues, 0, 1);
       System.arraycopy(values, 0, tempValues, 0,
         values.length);

       tempValues[tempValues.length - 1] = value;
       values = tempValues;
      }
      parameterMap.put(name, values);
     } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    } else {
     fileItemMap.put(name, fileItem);
    }
   }
   addTo();
  }
 }

 public boolean isMultipartContent() {
  return multipart;
 }

 public String getParameter(String name) {
  if (multipart) {
   String[] values = (String[]) parameterMap.get(name);
   if (values == null)
    return null;
   return values[0];
  } else
   return super.getParameter(name);
 }

 public String[] getParameterValues(String name) {
  if (multipart)
   return (String[]) parameterMap.get(name);
  else
   return super.getParameterValues(name);
 }

 public Enumeration getParameterNames() {
  if (multipart) {
   return new Enumeration() {
    Iterator iter = parameterMap.keySet().iterator();

    public boolean hasMoreElements() {
     return iter.hasNext();
    }

    public Object nextElement() {
     return iter.next();
    }
   };
  } else {
   return super.getParameterNames();
  }
 }

 public Map getParameterMap() {
  if (multipart)
   return parameterMap;
  else
   return super.getParameterMap();
 }

 public FileItem getFileItem(String name) {
  if (multipart)
   return (FileItem) fileItemMap.get(name);
  else
   return null;
 }

 public void delete() {
  if (multipart) {
   Iterator fileItemIter = fileItemMap.values().iterator();
   while (fileItemIter.hasNext()) {
    FileItem fileItem = (FileItem) fileItemIter.next();
    fileItem.delete();
   }
  }
 }

 public void addTo() {
  super.setAttribute(FileUploadRequestWrapper.class.getName(), this);
 }

 public static FileUploadRequestWrapper getFrom(HttpServletRequest request) {
  return (FileUploadRequestWrapper) request
    .getAttribute(FileUploadRequestWrapper.class.getName());
 }

 public static boolean hasWrapper(HttpServletRequest request) {
  if (FileUploadRequestWrapper.getFrom(request) == null) {
   return false;
  } else {
   return true;
  }
 }
}

 

 

5. Sequencer

 package madvirus.sequence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Sequencer {
    public synchronized static int nextId(Connection conn, String tableName)
    throws SQLException {
        PreparedStatement pstmtSelect = null;
        ResultSet rsSelect = null;
      
        PreparedStatement pstmtUpdate = null;
      
        try {
            pstmtSelect = conn.prepareStatement(
            "select MESSAGE_ID from ID_SEQUENCES where TABLE_NAME = ?");
            pstmtSelect.setString(1, tableName);
          
            rsSelect = pstmtSelect.executeQuery();
          
            if (rsSelect.next()) {
                int id = rsSelect.getInt(1);
                id++;
              
                pstmtUpdate = conn.prepareStatement(
                  "update ID_SEQUENCES set MESSAGE_ID = ? "+
                  "where TABLE_NAME = ?");
                pstmtUpdate.setInt(1, id);
                pstmtUpdate.setString(2, tableName);
                pstmtUpdate.executeUpdate();
              
                return id;
              
            } else {
                pstmtUpdate = conn.prepareStatement(
                "insert into ID_SEQUENCES values (?, ?)");
                pstmtUpdate.setString(1, tableName);
                pstmtUpdate.setInt(2, 1);
                pstmtUpdate.executeUpdate();
              
                return 1;
            }
        } finally {
            if (rsSelect != null)
                try { rsSelect.close(); } catch(SQLException ex) {}
            if (pstmtSelect != null)
                try { pstmtSelect.close(); } catch(SQLException ex) {}
            if (pstmtUpdate != null)
                try { pstmtUpdate.close(); } catch(SQLException ex) {}
        }
    }
}

 

6. 자바빈 클래스 (THEME_MESSAGE,THEME_CONTENT) : Theme

 package madvirus.gallery;

import java.sql.Timestamp;

public class Theme {
    private int id;
    private int groupId;
    private int orderNo;
    private int levels;
    private int parentId;
    private Timestamp register;
    private String name;
    private String email;
    private String image;
    private String password;
    private String title;
    private String content;
  
    public String getEmail() {
        return email;
    }
    public int getGroupId() {
        return groupId;
    }
    public int getId() {
        return id;
    }
    public String getImage() {
        return image;
    }
    public int getLevels() {
        return levels;
    }
    public String getName() {
        return name;
    }
    public int getOrderNo() {
        return orderNo;
    }
    public int getParentId() {
        return parentId;
    }
    public String getPassword() {
        return password;
    }
    public Timestamp getRegister() {
        return register;
    }
    public String getTitle() {
        return title;
    }
    public String getContent() {
        return content;
    }
  
    public void setEmail(String value) {
        email = value;
    }
    public void setGroupId(int value) {
        groupId = value;
    }
    public void setId(int value) {
        id = value;
    }
    public void setImage(String value) {
        image = value;
    }
    public void setLevels(int value) {
        levels = value;
    }
    public void setName(String value) {
        name = value;
    }
    public void setOrderNo(int value) {
        orderNo = value;
    }
    public void setParentId(int value) {
        parentId = value;
    }
    public void setPassword(String value) {
        password = value;
    }
    public void setRegister(Timestamp value) {
        register = value;
    }
    public void setTitle(String value) {
        title = value;
    }
    public void setContent(String value) {
        content = value;
    }
}

 

6-1 Class 쉽게 제작하는법 :)

 

일단 클래스 함수명을 다칩니다. 

package madvirus.gallery;

import java.sql.Timestamp;

public class Theme {
    private int id;
    private int groupId;
    private int orderNo;
    private int levels;
    private int parentId;
    private Timestamp register;
    private String name;
    private String email;
    private String image;
    private String password;
    private String title;
    private String content; 

 

 

 마우스 우클릭후에 -> Source -> Generate Getters and Setters.. 을 클릭합니다.

 

Generate Getters and Serrers 를 들어가시면, 자기가 친 함수가 다나오는데

1. Select All 을 눌러서 전체를 선택해줍시다.

2. Select All 을 눌러서 전체 선택을 하게되면, OK버튼이 활성화 되어집니다 :)

 

 

 

 7. 예외처리 클래스 (ThemeManagerException) 

 package madvirus.gallery;

public class ThemeManagerException extends Throwable {
    public ThemeManagerException(String msg) {
        super(msg);
    }
    public ThemeManagerException(String msg, Throwable cause) {
        super(msg, cause);
    }
  
}

 

 

댓글6