- DAO 클래스 : ThemeManager -insert() : 삽입 -update() : 수정 (Title, Content) -select() : 선택 (지정글 읽어오기) -selectList : 목록읽어오기 -delete : 삭제 -count : 조회수 |
- commons-fileupload-1.2.1.jar 파일을 이용한 업로드 클래스 : FileUploadRequestWrapper |
- ImageUtil : 썸네일 |
1. DAO 클래스 : ThemeManager
package madvirus.gallery; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.sql.SQLException; import madvirus.sequence.Sequencer; public class ThemeManager {
private static ThemeManager instance = new ThemeManager();
public static ThemeManager getInstance() { return instance; }
private ThemeManager() {} private Connection getConnection() throws Exception { return DriverManager.getConnection("jdbc:apache:commons:dbcp:/pool"); }
public void insert(Theme theme) throws Exception { Connection conn = null; Statement stmtGroup = null; ResultSet rsGroup = null;
PreparedStatement pstmtOrder = null; ResultSet rsOrder = null; PreparedStatement pstmtOrderUpdate = null;
PreparedStatement pstmtInsertMessage = null; PreparedStatement pstmtInsertContent = null;
try { conn = getConnection(); conn.setAutoCommit(false);
if (theme.getParentId() == 0) { stmtGroup = conn.createStatement(); rsGroup = stmtGroup.executeQuery( "select max(GROUP_ID) from THEME_MESSAGE"); int maxGroupId = 0; if (rsGroup.next()) { maxGroupId = rsGroup.getInt(1); } maxGroupId++; theme.setGroupId(maxGroupId); theme.setOrderNo(0); } else { pstmtOrder = conn.prepareStatement( "select max(ORDER_NO) from THEME_MESSAGE"+ "where PARENT_ID = ? or THEME_MESSAGE_ID = ?"); pstmtOrder.setInt(1, theme.getParentId()); pstmtOrder.setInt(2, theme.getParentId()); rsOrder = pstmtOrder.executeQuery(); int maxOrder = 0; if (rsOrder.next()) { maxOrder = rsOrder.getInt(1); } maxOrder ++; theme.setOrderNo(maxOrder); } if (theme.getOrderNo() > 0) { pstmtOrderUpdate = conn.prepareStatement( "update THEME_MESSAGE set ORDER_NO = ORDER_NO + 1"+ "where GROUP_ID = ? and ORDER_NO >= ?"); pstmtOrderUpdate.setInt(1, theme.getGroupId()); pstmtOrderUpdate.setInt(2, theme.getOrderNo()); pstmtOrderUpdate.executeUpdate(); } theme.setId(Sequencer.nextId(conn, "THEME_MESSAGE")); pstmtInsertMessage = conn.prepareStatement( "insert into THEME_MESSAGE values (?,?,?,?,?,?,?,?,?,?,?)"); pstmtInsertMessage.setInt(1, theme.getId()); pstmtInsertMessage.setInt(2, theme.getGroupId()); pstmtInsertMessage.setInt(3, theme.getOrderNo()); pstmtInsertMessage.setInt(4, theme.getLevels()); pstmtInsertMessage.setInt(5, theme.getParentId()); pstmtInsertMessage.setTimestamp(6, theme.getRegister()); pstmtInsertMessage.setString(7, theme.getName()); pstmtInsertMessage.setString(8, theme.getEmail()); pstmtInsertMessage.setString(9, theme.getImage()); pstmtInsertMessage.setString(10, theme.getPassword()); pstmtInsertMessage.setString(11, theme.getTitle()); pstmtInsertMessage.executeUpdate();
pstmtInsertContent = conn.prepareStatement( "insert into THEME_CONTENT values (?,?)"); pstmtInsertContent.setInt(1, theme.getId()); pstmtInsertContent.setCharacterStream(2, new StringReader (theme.getContent()), theme.getContent().length()); pstmtInsertContent.executeUpdate();
conn.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { conn.rollback(); }catch (SQLException ex1) {}
throw new Exception("insert", ex); } finally { if (rsGroup != null) try { rsGroup.close(); } catch(SQLException ex) {} if (stmtGroup != null) try { stmtGroup.close(); } catch(SQLException ex) {} if (rsOrder != null) try { rsOrder.close(); } catch(SQLException ex) {} if (pstmtOrder != null) try { pstmtOrder.close(); } catch(SQLException ex) {} if (pstmtOrderUpdate != null) try { pstmtOrderUpdate.close(); } catch(SQLException ex) {} if (pstmtInsertMessage != null) try { pstmtInsertMessage.close(); } catch(SQLException ex) {} if (pstmtInsertContent != null) try { pstmtInsertContent.close(); } catch(SQLException ex) {} if (conn != null) try { conn.setAutoCommit(true); conn.close(); }catch(SQLException ex) {} } }
public void update(Theme theme) throws Exception { Connection conn = null; PreparedStatement pstmtUpdateMessage = null; PreparedStatement pstmtUpdateContent = null;
try { conn = getConnection(); conn.setAutoCommit(false);
pstmtUpdateMessage = conn.prepareStatement( "update THEME_MESSAGE set NAME=?,EMAIL=?,IMAGE=?,TITLE=? "+ "where THEME_MESSAGE_ID=?"); pstmtUpdateContent = conn.prepareStatement( "update THEME_CONTENT set CONTENT=? "+ "where THEME_MESSAGE_ID=?");
pstmtUpdateMessage.setString(1, theme.getName()); pstmtUpdateMessage.setString(2, theme.getEmail()); pstmtUpdateMessage.setString(3, theme.getImage()); pstmtUpdateMessage.setString(4, theme.getTitle()); pstmtUpdateMessage.setInt(5, theme.getId()); pstmtUpdateMessage.executeUpdate();
pstmtUpdateContent.setCharacterStream(1, new StringReader(theme.getContent()), theme.getContent().length()); pstmtUpdateContent.setInt(2, theme.getId()); pstmtUpdateContent.executeUpdate();
conn.commit(); } catch(SQLException ex) { ex.printStackTrace(); try { conn.rollback(); } catch(SQLException ex1) {}
throw new Exception("update", ex); } finally { if (pstmtUpdateMessage != null) try { pstmtUpdateMessage.close(); } catch(SQLException ex) {} if (pstmtUpdateContent != null) try { pstmtUpdateContent.close(); } catch(SQLException ex) {} if (conn != null) try { conn.setAutoCommit(true); conn.close(); } catch(SQLException ex) {} } } public int count(List whereCond, Map valueMap) throws Exception { if (valueMap == null) valueMap = Collections.EMPTY_MAP;
Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null;
try { conn = getConnection(); StringBuffer query = new StringBuffer(200); query.append("select count(*) from THEME_MESSAGE "); if (whereCond != null && whereCond.size() > 0) { query.append("where "); for (int i = 0 ; i < whereCond.size() ; i++) { query.append(whereCond.get(i)); if (i < whereCond.size() -1 ) { query.append(" or "); } } } pstmt = conn.prepareStatement(query.toString());
Iterator keyIter = valueMap.keySet().iterator(); while(keyIter.hasNext()) { Integer key = (Integer)keyIter.next(); Object obj = valueMap.get(key); if (obj instanceof String) { pstmt.setString(key.intValue(), (String)obj); } else if (obj instanceof Integer) { pstmt.setInt(key.intValue(), ((Integer)obj).intValue()); } else if (obj instanceof Timestamp) { pstmt.setTimestamp(key.intValue(), (Timestamp)obj); } }
rs = pstmt.executeQuery(); int count = 0; if (rs.next()) { count = rs.getInt(1); } return count; } catch(SQLException ex) { ex.printStackTrace(); throw new Exception("count", ex); } finally { if (rs != null) try { rs.close(); } catch(SQLException ex) {} if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {} if (conn != null) try { conn.close(); } catch(SQLException ex) {} } }
public List selectList(List whereCond, Map valueMap, int startRow, int endRow) throws Exception { if (valueMap == null) valueMap = Collections.EMPTY_MAP;
Connection conn = null; PreparedStatement pstmtMessage = null; ResultSet rsMessage = null;
try { StringBuffer query = new StringBuffer(200);
query.append("select * from ( "); query.append(" select THEME_MESSAGE_ID,GROUP_ID,ORDER_NO,LEVELS,PARENT_ID,REGISTER,NAME,EMAIL,IMAGE,PASSWORD,TITLE,ROWNUM rnum "); query.append(" from ( "); query.append(" select THEME_MESSAGE_ID,GROUP_ID,ORDER_NO,LEVELS,PARENT_ID,REGISTER,NAME,EMAIL,IMAGE,PASSWORD,TITLE "); query.append(" from THEME_MESSAGE "); if (whereCond != null && whereCond.size() > 0) { query.append("where "); for (int i = 0 ; i < whereCond.size() ; i++) { query.append(whereCond.get(i)); if (i < whereCond.size() -1 ) { query.append(" or "); } } } query.append(" order by GROUP_ID desc, ORDER_NO asc "); query.append(" ) where ROWNUM <= ? "); query.append(") where rnum >= ? ");
conn = getConnection();
pstmtMessage = conn.prepareStatement(query.toString()); Iterator keyIter = valueMap.keySet().iterator(); while(keyIter.hasNext()) { Integer key = (Integer)keyIter.next(); Object obj = valueMap.get(key); if (obj instanceof String) { pstmtMessage.setString(key.intValue(), (String)obj); } else if (obj instanceof Integer) { pstmtMessage.setInt(key.intValue(), ((Integer)obj).intValue()); } else if (obj instanceof Timestamp) { pstmtMessage.setTimestamp(key.intValue(), (Timestamp)obj); } }
pstmtMessage.setInt(valueMap.size()+1, endRow + 1); pstmtMessage.setInt(valueMap.size()+2, startRow + 1);
rsMessage = pstmtMessage.executeQuery(); if (rsMessage.next()) { List list = new java.util.ArrayList(endRow-startRow+1);
do { Theme theme = new Theme(); theme.setId(rsMessage.getInt("THEME_MESSAGE_ID")); theme.setGroupId(rsMessage.getInt("GROUP_ID")); theme.setOrderNo(rsMessage.getInt("ORDER_NO")); theme.setLevels(rsMessage.getInt("LEVELS")); theme.setParentId(rsMessage.getInt("PARENT_ID")); theme.setRegister(rsMessage.getTimestamp("REGISTER")); theme.setName(rsMessage.getString("NAME")); theme.setEmail(rsMessage.getString("EMAIL")); theme.setImage(rsMessage.getString("IMAGE")); theme.setPassword(rsMessage.getString("PASSWORD")); theme.setTitle(rsMessage.getString("TITLE")); list.add(theme); } while(rsMessage.next());
return list;
} else { return Collections.EMPTY_LIST; }
} catch(SQLException ex) { ex.printStackTrace(); throw new Exception("selectList", ex); } finally { if (rsMessage != null) try { rsMessage.close(); } catch(SQLException ex) {} if (pstmtMessage != null) try { pstmtMessage.close(); } catch(SQLException ex) {} if (conn != null) try { conn.close(); } catch(SQLException ex) {} } } public Theme select(int id) throws Exception { Connection conn = null; PreparedStatement pstmtMessage = null; ResultSet rsMessage = null; PreparedStatement pstmtContent = null; ResultSet rsContent = null;
try { Theme theme = null;
conn = getConnection(); pstmtMessage = conn.prepareStatement( "select * from THEME_MESSAGE "+ "where THEME_MESSAGE_ID = ?"); pstmtMessage.setInt(1, id); rsMessage = pstmtMessage.executeQuery(); if (rsMessage.next()) { theme = new Theme(); theme.setId(rsMessage.getInt("THEME_MESSAGE_ID")); theme.setGroupId(rsMessage.getInt("GROUP_ID")); theme.setOrderNo(rsMessage.getInt("ORDER_NO")); theme.setLevels(rsMessage.getInt("LEVELS")); theme.setParentId(rsMessage.getInt("PARENT_ID")); theme.setRegister(rsMessage.getTimestamp("REGISTER")); theme.setName(rsMessage.getString("NAME")); theme.setEmail(rsMessage.getString("EMAIL")); theme.setImage(rsMessage.getString("IMAGE")); theme.setPassword(rsMessage.getString("PASSWORD")); theme.setTitle(rsMessage.getString("TITLE"));
pstmtContent = conn.prepareStatement( "select CONTENT from THEME_CONTENT "+ "where THEME_MESSAGE_ID = ?"); pstmtContent.setInt(1, id); rsContent = pstmtContent.executeQuery(); if (rsContent.next()){ Reader reader = null; try { reader = rsContent.getCharacterStream("CONTENT"); char[] buff = new char[512]; int len = -1; StringBuffer buffer = new StringBuffer(512); while( (len = reader.read(buff)) != -1) { buffer.append(buff, 0, len); } theme.setContent(buffer.toString()); } catch (IOException iex) { throw new Exception("select", iex); }finally{ if (reader != null) try { reader.close(); } catch(IOException iex) {} } } else { return null; } return theme; } else { return null; } } catch(SQLException ex) { ex.printStackTrace(); throw new Exception("select", ex); } finally { if (rsMessage != null) try { rsMessage.close(); } catch(SQLException ex) {} if (pstmtMessage != null) try { pstmtMessage.close(); } catch(SQLException ex) {} if (rsContent != null) try { rsContent.close(); } catch(SQLException ex) {} if (pstmtContent != null) try { pstmtContent.close(); } catch(SQLException ex) {} if (conn != null) try { conn.close(); } catch(SQLException ex) {} } }
public void delete (int id) throws Exception { Connection conn = null; PreparedStatement pstmtMessage = null; PreparedStatement pstmtContent = null;
try { conn = getConnection(); conn.setAutoCommit(false);
pstmtMessage = conn.prepareStatement( "delete from THEME_MESSAGE where THEME_MESSAGE_ID = ?"); pstmtContent = conn.prepareStatement( "delete from THEME_CONTENT where THEME_MESSAGE_ID = ?");
pstmtMessage.setInt(1, id); pstmtContent.setInt(1, id);
int updatedCount1 = pstmtMessage.executeUpdate(); int updatedCount2 = pstmtContent.executeUpdate();
if (updatedCount1 + updatedCount2 ==2) { conn.commit(); } else { conn.rollback(); throw new Exception("invalid id:"+id); } } catch (SQLException ex) { ex.printStackTrace(); try { conn.rollback(); } catch (SQLException ex1) {} throw new Exception("delete", ex); }finally { if (pstmtMessage != null) try { pstmtMessage.close();} catch (SQLException ex) {} if (pstmtContent != null) try { pstmtContent.close();} catch (SQLException ex) {} if (conn != null) try { conn.setAutoCommit(true); conn.close(); }catch (SQLException ex) {} }
}
} |
2. commons-fileupload-1.2.1.jar 파일을 이용한 업로드 클래스 : FileUploadRequestWrapper
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; } } } |
package madvirus.util; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.Graphics2D; import java.io.File; import java.io.InputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ImageUtil {
public static final int SAME = -1; public static final int RATIO = 0;
public static void resize(File src, File dest, int width, int height) throws IOException { FileInputStream srcIs = null; try { srcIs = new FileInputStream(src); ImageUtil.resize(srcIs, dest, width, height); }finally{ if (srcIs !=null) try { srcIs.close();} catch(IOException ex) {} } } public static void resize(InputStream src, File dest, int width, int height) throws IOException { BufferedImage srcImg = ImageIO.read(src); int srcWidth = srcImg.getWidth(); int srcHeight = srcImg.getHeight();
int destWidth = -1, destHeight = -1;
if (width == SAME) { destWidth = srcWidth; }else if (width > 0) { destWidth = width; }
if (height == SAME) { destHeight = srcHeight; }else if (height > 0) { destHeight = height; } if (width == RATIO && height == RATIO) { destWidth = srcWidth; destHeight = srcHeight; } else if (width == RATIO) { double ratio = ((double)destHeight) / ((double)srcHeight); destWidth = (int) ((double)srcWidth * ratio); } else if (height == RATIO) { double ratio = ((double)destWidth) / ((double)srcWidth); destHeight = (int)((double)srcHeight * ratio); }
BufferedImage destImg = new BufferedImage( destWidth, destHeight, BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = destImg.createGraphics(); g.drawImage(srcImg, 0, 0, destWidth, destHeight, null);
ImageIO.write(destImg, "jpg", dest); } } |
'웹개발 > HTML' 카테고리의 다른 글
이클립스 설치 및 JDK 설치 방법 (0) | 2014.05.20 |
---|---|
회원가입 form (0) | 2014.05.20 |
JSP/JAVA클래스 로 이미지 게시판 만들기 1 (Class편) (6) | 2014.04.18 |
오라클 공부 링크 (0) | 2014.04.17 |
C언어 시작하기 3 (0) | 2014.04.13 |