프로젝트설정.txt
테이블 명세
테이블명 : album
컬럼명
글번호 num number primary key
작성자 writer not null
제목 subject not null
이메일 email
내용 content clob not null
비밀번호 passwd not null
작성일 reg_date timestamp not null
조회수 readcount number(4) default 0
ip ip not null
저장이미지 image (파일명 저장)
시퀀스명 : album_seq
테이블 만들기
create table album(
num number primary key,
writer varchar2(20) NOT NULL,
subject varchar2(100) NOT NULL,
email varchar2(40),
content clob NOT NULL,
passwd varchar2(10) NOT NULL,
reg_date TIMESTAMP NOT NULL,
readcount number(4) DEFAULT 0,
ip varchar2(20) NOT NULL,
image varchar2(40));
create sequence album_seq;
수업메모
1 Album 테이블의 컬럼
2 Album 기본구성
1. 싱글턴 패턴
2. getConnection
3. execClose()
3 액션 WriteFormAction -> /view2/writeForm.jsp (num,readcount,reg-date,ip 는빼고 폼에서 넘김)
4 맵핑 : commandMap.properties
AlbumDao
insertArticle(Album album){
sql = insert into album (컬럼명) value(???)
num album_seq.nextval
writer
subject
email
conten
password
reg_date sysdate
readcount
ip
image
}
파일
낙엽||jsp 분리
바뀐이름.jsp
주소 : D:/javaWork/work_jsp2/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/album/upload
\=>/ 셀렉트라인즈
1. 글쓰기 : WriteFormAction ,WriteProAction
2. 목록 : ListAction (검색)
3. 상세보기 : ContentAction
4. 수정 : UpdateFormAction, UpdateProAction
5. 삭제 : DeleteFormAction, DeleteProAction
1. 글쓰기 : writeForm ,writePro
2. 목록 : List (검색)
3. 상세보기 : content
4. 수정 : updateForm, updatePro
5. 삭제 : deleteForm, deletePro
clob 읽어오기
목록 ->상세 -> 수정 -> 삭제
StringBuffer output = new StringBuffer();
Reader input = rs.getCharacterStream("content");
char[] buffer = new char[1024];
int byteRead = 0;
while((byteRead=input.read(buffer,0,1024))!=-1){
output.append(buffer,0,byteRead);
}
// contents -> CLOB 데이터가 저장될 String
String content = output.toString();
album.setContent(content);
album.war
album (1).war
프로젝트명 : album
팩키지
Java Resources
src
com.action
ContentAction
package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;
public class ContentAction implements Action{
@Override
public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
request.setCharacterEncoding("utf-8");
int num =Integer.parseInt(request.getParameter("num"));
AlbumDao manager = AlbumDao.getInstance();
Album album = manager.getArticle(num);
if(album !=null){
album.setReadcount(manager.updateReadCount(num));
}
request.setAttribute("album", album);
return "/view2/content.jsp;";
}
}
DeleteFormAction
package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.controller.Action;
public class DeleteFormAction implements Action{
@Override
public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
return "/view2/deleteForm.jsp";
}
}
DeleteProAction
package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;
//import com.oreilly.servlet.MultipartRequest;
import com.util.FileUtil;
public class DeleteProAction implements Action{
@Override
public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
request.setCharacterEncoding("utf-8");
int num = Integer.parseInt(request.getParameter("num"));
String passwd = request.getParameter("passwd");
AlbumDao manager = AlbumDao.getInstance();
int check = manager.userCheck(num, passwd);
if(check== 1){
Album album = manager.getArticle(num);
manager.deleteArticle(num);
if(album.getImage() != null){
FileUtil.removeFile(album.getImage());
}
}
request.setAttribute("check", new Integer(check));
return "/view2/deletePro.jsp";
}
}
ListAction
package com.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.AlbumPage;
import com.domain.Album;
public class ListAction implements Action{
public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
request.setCharacterEncoding("utf-8");
String keyField =request.getParameter("keyField");
String keyWord =request.getParameter("keyWord");
if(keyField==null){
keyField="";
}
if(keyWord==null){
keyWord="";
}
String pageNum =request.getParameter("pageNum");
if(pageNum ==null){
pageNum = "1";
}
int pageSize = 20;
int currentPage = Integer.parseInt(pageNum);
int startRow =(currentPage-1)*pageSize +1;
int endRow =currentPage * pageSize;
int count = 0;
int number = 0;
List<Album> albumList =null;
AlbumDao manager = AlbumDao.getInstance();
count =manager.getArticleCount(keyField,keyWord);
if(count>0){
albumList = manager.getArticles(startRow, endRow, keyField, keyWord);
}
//가짜 글번호
number=count-(currentPage-1)*pageSize;
AlbumPage page= new AlbumPage();
page.setCount(count);
page.setCurrentPage(currentPage);
page.setNumber(number);
page.setPageSize(pageSize);
page.setKeyField(keyField);
page.setKeyWord(keyWord);
request.setAttribute("page", page);
request.setAttribute("albumList", albumList);
return "/view2/list.jsp";
}
}
UpdateFormAction
package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;
public class UpdateFormAction implements Action{
@Override
public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
int num = Integer.parseInt(request.getParameter("num"));
AlbumDao manager = AlbumDao.getInstance();
Album album = manager.getArticle(num);
request.setAttribute("album", album);
return "/view2/updateForm.jsp";
}
}
UpdateProAction
package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;
import com.oreilly.servlet.MultipartRequest;
import com.util.FileUtil;
public class UpdateProAction implements Action{
@Override
public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
request.setCharacterEncoding("utf-8");
MultipartRequest multi = FileUtil.createFile(request);
//전송된이미지정보
String image= multi.getFilesystemName("image");
AlbumDao manager = AlbumDao.getInstance();
//인증
int check = manager.userCheck(Integer.parseInt(multi.getParameter("num")),multi.getParameter("passwd"));
if(check==1){
String originImage = multi.getParameter("originImage");
Album album =new Album();
album.setNum(Integer.parseInt(multi.getParameter("num")));
album.setWriter(multi.getParameter("writer"));
album.setEmail(multi.getParameter("email"));
album.setSubject(multi.getParameter("subject"));
album.setPasswd(multi.getParameter("passwd"));
album.setContent(multi.getParameter("content"));
album.setIp(request.getRemoteAddr());
if(image !=null){
//이미지가 변경되었을 경우
album.setImage(FileUtil.rename(image));
}else{
//이미지가 변경되지 않았을경우
album.setImage(originImage);
}
manager.update(album);
if(image !=null){
FileUtil.removeFile(originImage);
}
}else{
//비번이 틀려 인증 실패시 올리려고 전송된 이미지 삭제
if(image !=null)FileUtil.removeFile(image);
}
request.setAttribute("check", new Integer(check));
return "/view2/updatePro.jsp;";
}
}
WriteFormAction
package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.controller.Action;
public class WriteFormAction implements Action{
@Override
public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
return "/view2/writeForm.jsp";
}
}
WriteProAction
package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.controller.Action;
import com.dao.AlbumDao;
import com.domain.Album;
import com.util.FileUtil;
import com.oreilly.servlet.MultipartRequest;
public class WriteProAction implements Action{
@Override
public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
MultipartRequest multi =FileUtil.createFile(request);
Album album = new Album();
album.setWriter(multi.getParameter("writer"));
album.setSubject(multi.getParameter("subject"));
album.setEmail(multi.getParameter("email"));
album.setContent(multi.getParameter("content"));
album.setPasswd(multi.getParameter("passwd"));
album.setIp(request.getRemoteAddr());
//image 파라미터네임
album.setImage(FileUtil.rename(multi.getFilesystemName("image")));
AlbumDao manager = AlbumDao.getInstance();
manager.insertArticle(album);
return "/view2/writePro.jsp";
}
}
com.controller
Action
package com.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//요청 파라미터로 명령어를 전달하는 방식의 슈퍼 인터페이스
public interface Action {
public String execute(HttpServletRequest request,HttpServletResponse response)throws Throwable;
}
Controller
package com.controller;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Controller extends HttpServlet {
private Map commandMap = new HashMap();//명령어와 명령어 처리 클래스를 쌍으로 저장
//명령어와 처리클래스가 매핑되어 있는 properties 파일을 읽어서 Map객체인 commandMap에 저장
//명령어와 처리클래스가 매핑되어 있는 properties 파일은 Command.properties파일
public void init(ServletConfig config) throws ServletException {
String configFile = config.getInitParameter("configFile");
Properties prop = new Properties();
FileInputStream fis = null;
try {
String configFilePath = config.getServletContext().getRealPath(
configFile);
fis = new FileInputStream(configFilePath);
prop.load(fis);
} catch (IOException e) {
throw new ServletException(e);
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ex) {
}
}
Iterator keyIter = prop.keySet().iterator();
while (keyIter.hasNext()) {
String command = (String) keyIter.next();
String handlerClassName = prop.getProperty(command);
try {
Class handlerClass = Class.forName(handlerClassName);
Object handlerInstance = handlerClass.newInstance();
commandMap.put(command, handlerInstance);
} catch (ClassNotFoundException e) {
throw new ServletException(e);
} catch (InstantiationException e) {
throw new ServletException(e);
} catch (IllegalAccessException e) {
throw new ServletException(e);
}
}
}
public void doGet(//get방식의 서비스 메소드
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestPro(request, response);
}
protected void doPost(//post방식의 서비스 메소드
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestPro(request, response);
}
//시용자의 요청을 분석해서 해당 작업을 처리
private void requestPro(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String view = null;
Action com=null;
try {
String command = request.getRequestURI();
if (command.indexOf(request.getContextPath()) == 0) {
command = command.substring(request.getContextPath().length());
}
com = (Action)commandMap.get(command);
view = com.execute(request, response);
} catch(Throwable e) {
throw new ServletException(e);
}
RequestDispatcher dispatcher =request.getRequestDispatcher(view);
dispatcher.forward(request, response);
}
}
com.dao
AlbumDao
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.domain.Album;
import com.util.StringUtil;
public class AlbumDao {
private static AlbumDao instance =new AlbumDao();
//싱글턴 패턴
private AlbumDao(){}
public static AlbumDao getInstance(){
return instance;
}
//getConnection : JDBC DB연동
private Connection getConnection() throws Exception{
Context initCtx= new InitialContext();
Context envCtx=(Context)initCtx.lookup("java:comp/env");
DataSource ds=(DataSource)envCtx.lookup("jdbc/orcl");
return ds.getConnection();
}
//글쓰기 등록
public void insertArticle(Album album)throws Exception{
Connection conn= null;
PreparedStatement pstmt = null;
String sql=null;
int cnt = 0;
try{
conn= getConnection();
//빠지는게 있을때는 컬럼명을 다 넣어줘야함
sql = "insert into ALBUM (num,writer,subject,email,content,passwd,reg_date,ip,image) " +
"values(album_seq.nextval,?,?,?,?,?,sysdate,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(++cnt, album.getWriter());
pstmt.setString(++cnt, album.getSubject());
pstmt.setString(++cnt, album.getEmail());
pstmt.setString(++cnt, album.getContent());
pstmt.setString(++cnt, album.getPasswd());
pstmt.setString(++cnt, album.getIp());
pstmt.setString(++cnt, album.getImage());
pstmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}finally{
execClose(null,pstmt,conn);
}
}
//글갯수
public int getArticleCount(String keyField,String keyWord)throws Exception{
Connection conn= null;
PreparedStatement pstmt =null;
ResultSet rs= null;
int count =0;
String sql =null;
try{
conn=getConnection();
if(keyWord == null || "".equals(keyWord.trim())){
sql="select count(*) from ALBUM";
pstmt =conn.prepareStatement(sql);
}else{
sql="select count(*) from album where "+keyField+" like ?";
pstmt =conn.prepareStatement(sql);
pstmt.setString(1, "%"+keyWord+"%");
}
rs =pstmt.executeQuery();
if (rs.next()){
count =rs.getInt(1);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
execClose(rs,pstmt,conn);
}
return count;
}
//리스트뽑기
public List<Album> getArticles(int startRow, int endRow, String keyField,String keyWord)throws Exception{
Connection conn= null;
PreparedStatement pstmt =null;
ResultSet rs= null;
List<Album> list =null;
String sql=null;
try{
conn =getConnection();
if(keyWord == null || "".equals(keyWord.trim())){
sql ="select * from (select a.*, rownum rnum from (select * from ALBUM order by num desc)a) where rnum >=? and rnum <=?";
pstmt =conn.prepareStatement(sql);
pstmt.setInt(1, startRow);
pstmt.setInt(2, endRow);
}else{
sql ="select * from(select a.*, rownum rnum from(select * from ALBUM where "+keyField+" like ? order by num desc)a) where rnum >=? and rnum <=?";
pstmt =conn.prepareStatement(sql);
pstmt.setString(1, "%"+keyWord+"%");
pstmt.setInt(2, startRow);
pstmt.setInt(3, endRow);
}
rs = pstmt.executeQuery();
if(rs.next()){
list= new ArrayList<Album>();
do{
Album album =new Album();
album.setNum(rs.getInt("num"));
album.setWriter(rs.getString("writer"));
album.setSubject(rs.getString("subject"));
album.setEmail(rs.getString("email"));
album.setPasswd(rs.getString("passwd"));
album.setReg_date(rs.getTimestamp("reg_date"));
album.setIp(rs.getString("ip"));
album.setImage(rs.getString("image"));
album.setReadcount(rs.getInt("readcount"));
album.setContent(StringUtil.clobToString(rs,"content"));
list.add(album);
}while(rs.next());
}else{
list = Collections.EMPTY_LIST;
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
execClose(rs,pstmt,conn);
}
return list;
}
//상세페이지
public Album getArticle(int num)throws Exception{
Connection conn =null;
PreparedStatement pstmt= null;
ResultSet rs = null;
Album album =null;
String sql=null;
try{
conn=getConnection();
sql ="select * from ALBUM where num = ? ";
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, num);
rs=pstmt.executeQuery();
if(rs.next()){
album =new Album();
album.setNum(rs.getInt("num"));
album.setWriter(rs.getString("writer"));
album.setSubject(rs.getString("subject"));
album.setEmail(rs.getString("email"));
album.setPasswd(rs.getString("passwd"));
album.setReg_date(rs.getTimestamp("reg_date"));
album.setIp(rs.getString("ip"));
album.setImage(rs.getString("image"));
album.setReadcount(rs.getInt("readcount"));
album.setContent(StringUtil.clobToString(rs,"content"));
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
execClose(rs,pstmt,conn);
}
return album;
}
//조회수증가
public int updateReadCount(int num)throws Exception{
Connection conn= null;
PreparedStatement pstmt = null;
ResultSet rs= null;
int count =0;
String sql =null;
try{
conn=getConnection();
//조회수 증가
sql="update album set readcount=readcount+1 where num = ?";
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, num);
pstmt.executeUpdate();
//증가된 조회수 조회
sql="select readcount from album where num = ?";
pstmt =conn.prepareStatement(sql);
pstmt.setInt(1, num);
rs= pstmt.executeQuery();
if(rs.next()){
count =rs.getInt(1);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
execClose(null,pstmt,conn);
}
return count;
}
//수정
public void update(Album album)throws Exception{
Connection conn=null;
PreparedStatement pstmt =null;
int cnt =0;
String sql = null;
try{
conn =getConnection();
sql = "update ALBUM set writer=?,email=?, subject=?,image=?,content=? where num=?";
pstmt =conn.prepareStatement(sql);
pstmt.setString(++cnt, album.getWriter());
pstmt.setString(++cnt, album.getEmail());
pstmt.setString(++cnt, album.getSubject());
pstmt.setString(++cnt, album.getImage());
pstmt.setString(++cnt, album.getContent());
pstmt.setInt(++cnt, album.getNum());
pstmt.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
execClose(null,pstmt,conn);
}
}
//삭제
public void deleteArticle(int num)throws Exception{
Connection conn =null;
PreparedStatement pstmt=null;
String sql=null;
try{
conn= getConnection();
sql="delete from ALBUM where num=?";
pstmt =conn.prepareStatement(sql);
pstmt.setInt(1, num);
pstmt.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
execClose(null,pstmt,conn);
}
return ;
}
//인증
public int userCheck(int num, String passwd)throws Exception{
Connection conn =null;
PreparedStatement pstmt=null;
ResultSet rs=null;
String dbpasswd="";
String sql="";
int x=-1;
try{
conn= getConnection();
sql="select passwd from ALBUM where num=?";
pstmt =conn.prepareStatement(sql);
pstmt.setInt(1, num);
rs=pstmt.executeQuery();
if(rs.next()){
dbpasswd =rs.getString("passwd");
if(dbpasswd.equals(passwd)){
x=1;//인증성공
}else
x=0;//비밀전호 틀림
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
execClose(rs,pstmt,conn);
}
return x;
}
//execClose : 자원정리
public void execClose(ResultSet rs, PreparedStatement pstmt, Connection conn)throws Exception{
if(rs !=null) try{rs.close();}catch(SQLException sqle){}
if(pstmt !=null) try{pstmt.close();}catch(SQLException sqle){}
if(conn !=null) try{conn.close();}catch(SQLException sqle){}
}
}
com.domain
Alubm
package com.domain;
import java.sql.Timestamp;
public class Album {
private int num;
private String writer;
private String subject;
private String email;
private String content;
private String passwd;
private Timestamp reg_date;
private int readcount;
private String ip;
private String image;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public Timestamp getReg_date() {
return reg_date;
}
public void setReg_date(Timestamp reg_date) {
this.reg_date = reg_date;
}
public int getReadcount() {
return readcount;
}
public void setReadcount(int readcount) {
this.readcount = readcount;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
AlbumPage
package com.domain;
public class AlbumPage {
private int count;
private int pageSize;
private int currentPage;
private int number;
private String keyField;
private String keyWord;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getKeyField() {
return keyField;
}
public void setKeyField(String keyField) {
this.keyField = keyField;
}
public String getKeyWord() {
return keyWord;
}
public void setKeyWord(String keyWord) {
this.keyWord = keyWord;
}
}
com.util
FileUtil
package com.util;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
public class FileUtil {
public static final String UPLOAD_PATH = "D:/javaWork/work_jsp2/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/album/upload";
public static final String ENCODING_TYPE = "utf-8";
public static final int MAX_SIZE = 10*1024*1024;//10M
public static MultipartRequest createFile(HttpServletRequest request) throws IOException{
return new MultipartRequest(request,UPLOAD_PATH,MAX_SIZE,ENCODING_TYPE,new DefaultFileRenamePolicy());
}
//알아서 파일명을 만들어줌
public static String rename(String filename) throws Exception{
if(filename ==null) return null;
String newName = Long.toString(System.currentTimeMillis())+(int)(Math.random()*50);
return rename(filename, newName);
}
//지정한 파일명을 사용한다.
public static String rename(String filename, String newName) throws Exception{
if(filename == null) return null;
File file = new File(UPLOAD_PATH,filename);
//파일명을 원하는 형식으로 변경하기
int idx = filename.lastIndexOf(".");
String extention = "";
String newFileName = "";
if(idx != -1) {
extention = filename.substring(idx);
}
// newName 전달시 확장자를 제외해야 하지만 확장자를 포함할 경우 제거함
int newIdx = newName.lastIndexOf(".");
if(newIdx !=-1){
newName = newName.substring(0,newIdx);
}
newFileName = newName + extention.toLowerCase();
File fs = new File(UPLOAD_PATH,newFileName);
file.renameTo(fs);
return newFileName;
}
//파일삭제
public static void removeFile(String filename){
if(filename != null){
File file = new File(UPLOAD_PATH,filename);
if(file.exists()) file.delete();
}
}
}
StringUtil
package com.util;
import java.io.IOException;
import java.io.Reader;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StringUtil {
public static String clobToString(ResultSet rs, String msg) throws SQLException, IOException{
StringBuffer sb = new StringBuffer();
//getCharacterStream : String 으로 읽어드려 char 배열에넣고 StringqBuffer에 넣음
Reader rd = rs.getCharacterStream(msg);
char[] buffer = new char[1024];
int byteRead;
while((byteRead=rd.read(buffer,0,1024))!=-1){
sb.append(buffer,0,byteRead);
}
rd.close();
return sb.toString();
}
}
WebContent
docs
album.sql
create table album(
num number primary key,
writer varchar2(20) NOT NULL,
subject varchar2(100) NOT NULL,
email varchar2(40),
content clob NOT NULL,
passwd varchar2(10) NOT NULL,
reg_date date NOT NULL,
readcount number(4) DEFAULT 0,
ip varchar2(20) NOT NULL);
create sequence album_seq;
META-INF
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!--
maxActive="20" //최대 커넥션 수
maxIdle="10" //미리 만들어둘 기본커낵션 수
-->
<Resource name="jdbc/orcl"
auth="container"
type="javax.sql.DataSource"
username="hr"
password="hr"
driverClassName="oracle.jdbc.driver.OracleDriver"
factory="org.apache.commons.dbcp.BasicDataSourceFactory"
url="jdbc:oracle:thin:@localhost:1521:orcl"
maxActive="20"
maxIdle="10" />
</Context>
view2
content.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width ="70%" border ="1" cellpadding="0" cellspacing="0" align="center">
<tr><td colspan="2" align="center"><h1>상세보기</h1></tr>
<tr>
<td>글번호</td>
<td>${album.num}</td>
</tr>
<tr>
<td>작성자</td>
<td>${album.writer}</td>
</tr>
<tr>
<td>IP</td>
<td>${album.ip}</td>
</tr>
<tr>
<td>조회수</td>
<td>${album.readcount}</td>
</tr>
<tr>
<td>작성일</td>
<td><fmt:formatDate value="${album.reg_date}" pattern="yyyy년MM월dd일"/></td>
</tr>
<tr>
<td>이메일</td>
<c:if test="${! empty album.email}">
<td>${album.email}</td>
</c:if>
<c:if test="${empty album.email}">
<td> </td>
</c:if>
</tr>
<tr><td>이미지</td><td>
<img src="upload/${album.image}">
</td></tr>
<tr><td>글제목</td><td>
${album.subject}
</td></tr>
<tr><td>내용</td><td>
${album.content}
</td></tr>
<tr><td colspan="2" align="center">
<input type="button" value="수정하기" onClick="location.href='updateForm.do?num=${album.num}'">
<input type="button" value="삭제하기" onClick="location.href='deleteForm.do?num=${album.num}'">
<input type="button" value="목록보기" onClick="location.href='list.do'">
</td></tr>
</table>
</body>
</html>
deleteForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String num = request.getParameter("num");
String image = request.getParameter("image");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>글삭제</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
<!--
function begin(){
document.myform.passwd.focus();
}
function checkIt(){
if(!document.myform.passwd.value){
alert("비밀번호를 입력하지 않으셨습니다.");
document.myform.passwd.focus();
return false;
}
return true;
}
//-->
</script>
</head>
<BODY onload="begin()">
<form name="myform" action="deletePro.do?num=<%=num %>" method="post" onSubmit="return checkIt()">
<table cellspacing=1 cellpadding=1 width="260" border=1 align="center" >
<tr height="30">
<td colspan="2" align="center">
<font size="+1" ><b>글삭제</b></font></td></tr>
<tr height="30">
<td width="110" align=center>비밀번호</td>
<td width="150" align=center>
<input type=password name="passwd" size="15" maxlength="12"></td></tr>
<tr height="30">
<td colspan="2" align="center">
<input type=submit value="글삭제하기">
<input type="button" value="취 소" onclick="location.href='list.do'"></TD></TR>
</TABLE>
</form>
</BODY>
</HTML>
deletePro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${check == 1}">
<script type="text/javascript">
alert("글정보가 삭제 되었습니다.");
location.href="list.do";
</script>
</c:if>
<c:if test="${check != 1}">
<script type="text/javascript">
alert("비밀번호가 맞지 않습니다.");
history.go(-1);
</script>
</c:if>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>글목록</title>
<script type="text/javascript">
function searchMessage(){
if(document.search.keyWord.value==""){
alert("검색어를 입력하세요");
document.search.keyWord.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<c:if test="${page.count == 0}">
<table width="70%" border="1" cellpadding="0" cellspacing="0" align="center">
<tr>
<td bgcolor="#e9e9e9">
앨범에 저장된 글이 없습니다.
</td>
</table>
</c:if>
<c:if test="${page.count > 0}">
<table width="70%" border="1" cellpadding="0" cellspacing="0" align="center">
<tr><td colspan="6" align="center"><h1>게시판</h1></td></tr>
<tr bgcolor="gray">
<td width="70">번호</td>
<td width="70">글번호</td>
<td>글제목</td>
<td width="120">작성자</td>
<td width="70">조회수</td>
<td width="120">작성일 </td>
</tr>
<c:set var="number" value="${page.number}"/>
<c:forEach var="album" items="${albumList}">
<tr>
<td>${number}<c:set var="number" value="${number - 1}"/></td>
<td>${album.num}</td>
<td><a href="content.do?num=${album.num}">${album.subject}</a></td>
<td>${album.writer}</td>
<td>${album.readcount}</td>
<td><fmt:formatDate value="${album.reg_date}" pattern="yyyy년MM월dd일"/></td>
</tr>
</c:forEach>
</table>
</c:if>
<form action="list.do" name="search" method="get" onsubmit="return searchMessage()">
<table width="70%" border="1" align="center" cellpadding="4" cellspacing="0">
<tr><td width="200"><a href="writeForm.do">글쓰기</a></td>
<td align="center" valign="bottom">
<select name="keyField">
<option value="subject">제목</option>
<option value="writer">이름</option>
<option value="content">내용</option>
</select></td>
<td><input type="text" size=16 name="keyWord"><input type="submit" value="찾기"></td>
</tr>
<tr><td colspan="3" align="center">
<c:if test="${page.count > 0}">
<c:set var="pageCount" value="${(page.count - 1) / page.pageSize + 1}"/>
<c:set var="pageBlock" value="${10}"/>
<fmt:parseNumber var="rs" value="${(currentPage - 1) / pageBlock}" integerOnly="true" />
<c:set var="startPage" value="${rs*pageBlock+1}"/>
<c:set var="endPage" value="${startPage + pageBlock-1}"/>
<c:if test="${endPage > pageCount}">
<c:set var="endPage" value="${pageCount}"/>
</c:if>
<c:if test="${startPage > pageBlock}">
<a href="list.do?pageNum=${startPage - pageBlock }&keyField=${page.keyField}&keyWord=${page.keyWord}">[이전]</a>
</c:if>
<c:forEach var="i" begin="${startPage}" end="${endPage}">
<c:if test="${i == page.currentPage}">
[${i}]
</c:if>
<c:if test="${i != page.currentPage}">
<a href="list.do?pageNum=${i}&keyField=${page.keyField}&keyWord=${page.keyWord}">[${i}]</a>
</c:if>
</c:forEach>
<c:if test="${endPage < pageCount}">
<a href="list.do?pageNum=${startPage + pageBlock}&keyField=${page.keyField}&keyWord=${page.keyWord}">[다음]</a>
</c:if>
</c:if>
</td></tr>
</table>
</form>
</body>
</html>
updateForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import ="com.dao.AlbumDao" %>
<%@ page import ="com.domain.Album" %>
<%
int num = Integer.parseInt(request.getParameter("num"));
AlbumDao manager = AlbumDao.getInstance();
Album album = manager.getArticle(num);
if(album.getEmail()==null){
album.setEmail("");
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>글수정</title>
<script type="text/javascript">
<!--
function checkIt(){
var user =document.userinput;
if(!user.writer.value){
alert("사용자 이름을 입력하세요");
user.name.focus();
return false;
}
if(!user.passwd.value){
alert("비밀번호를 입력하세요");
user.passwd.focus();
return false;
}
if(!user.content.value){
alert("내용을 입력하세요");
user.content.focus();
return false;
}
}
//-->
</script>
</head>
<body>
<form action="updatePro.do" method="post" encType="multipart/form-data" name="userinput" onSubmit="return checkIt()">
<input type="hidden" name="num" value="<%=num%>">
<table width ="70%" border ="1" cellpadding="0" cellspacing="0" align="center">
<tr>
<td colspan="2" align="center"><h1>수정하기</h1></td>
</tr>
<tr>
<td>글번호</td>
<td><%=album.getNum() %></td>
</tr>
<tr>
<td>이름</td>
<td><input type="text" name="writer" value="<%=album.getWriter() %>" size="10"></td>
</tr>
<tr>
<td>이메일</td>
<td><input type="text" name="email" value="<%=album.getEmail() %>" size="30"></td>
</tr>
<tr>
<td>제목</td>
<td><input type="text" name="subject" value="<%=album.getSubject()%>" size="50"></td>
</tr>
<tr>
<td>이미지교체</td>
<input type="hidden" name="originImage" value="<%=album.getImage()%>">
<td><img src="upload/<%=album.getImage()%>" width="50" height="50">
<input type="file" size="8" name="image"></td>
</tr>
<tr>
<td>내용</td>
<td><textarea name="content" rows="5" cols="50"><%=album.getContent() %></textarea></td>
</tr>
<tr>
<td>암호</td>
<td><input type="password" name ="passwd" size="10">
암호와 동일해야 글이 수정됩니다.</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="수정하기" >
<input type="reset" value="다시작성">
<input type="button" value="목록보기" onClick="location.href='list.do'">
</td>
</tr>
</table>
</form>
</body>
</html>
updatePro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${check == 1}">
<script type="text/javascript">
alert("글정보가 수정 되었습니다.");
location.href="list.do";
</script>
</c:if>
<c:if test="${check != 1}">
<script type="text/javascript">
alert("비밀번호가 맞지 않습니다.");
history.go(-1);
</script>
</c:if>
writeForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>게시판</title>
<script type="text/javaScript">
function writeSave(){
if(document.writeform.writer.value==""){
alert("작성자를 입력하십시요.");
document.writeform.writer.focus();
return false;
}
if(document.writeform.subject.value==""){
alert("제목을 입력하십시요.");
document.writeform.subject.focus();
return false;
}
if(document.writeform.content.value==""){
alert("내용을 입력하십시요.");
document.writeform.content.focus();
return false;
}
if(document.writeform.passwd.value==""){
alert(" 비밀번호를 입력하십시요.");
document.writeform.passwd.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<center><b>글쓰기</b></center>
<br>
<form method="post" name="writeform" action="writePro.do" encType="multipart/form-data" onsubmit="return writeSave()">
<table width="400" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td width="70" align="center">이 름</td>
<td width="330">
<input type="text" size="10" maxlength="10" name="writer"></td>
</tr>
<tr>
<td width="70" align="center" >제 목</td>
<td width="330">
<input type="text" size="40" maxlength="50" name="subject">
</td>
</tr>
<tr>
<td width="70" align="center">Email</td>
<td width="330">
<input type="text" size="40" maxlength="30" name="email" ></td>
</tr>
<tr>
<td width="70" align="center" >내 용</td>
<td width="330" >
<textarea name="content" rows="13" cols="40"></textarea> </td>
</tr>
<tr>
<td width="70" align="center" >비밀번호</td>
<td width="330" >
<input type="password" size="8" maxlength="12" name="passwd">
</td>
</tr>
<tr>
<td width="70" align="center" >이미지</td>
<td width="330" >
<input type="file" size="8" name="image">
</td>
</tr>
<tr>
<td colspan=2 align="center">
<input type="submit" value="글쓰기" >
<input type="reset" value="다시작성">
<input type="button" value="목록보기" onClick="location.href='list.do'">
</td></tr></table>
</form>
</body>
</html>
writePro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<script type="text/javascript">
<!--
alert("앨범게시판에 글을 등록하였습니다.")
location.href="list.do";
//-->
</script>
WEB-INF
lib (jar 5개 3개는 커넥션풀 3개 jstl 1개 업로드cos 1개)
commons-collections-3.1.jar
commons-dbcp-1.2.1.jar
commons-pool-1.2.jar
cos.jar
jstl-1.2.jar
commandMap.properties
/writeForm.do=com.action.WriteFormAction
/writePro.do=com.action.WriteProAction
/updateForm.do=com.action.UpdateFormAction
/updatePro.do=com.action.UpdateProAction
/deleteForm.do=com.action.DeleteFormAction
/deletePro.do=com.action.DeleteProAction
/list.do=com.action.ListAction
/content.do=com.action.ContentAction
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>member</display-name>
<!-- Controller start -->
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>com.controller.Controller</servlet-class>
<init-param>
<param-name>configFile</param-name>
<param-value>/WEB-INF/commandMap.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- Controller end -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>