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();
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();
}
}


String을 리턴함.






http://www.okjsp.pe.kr/seq/104320




요즘 대세라 할 수 있는 날짜 표기 입니다



자바파일 에서 properties 파일 경로 설정


그리고 Date 타입 설정후 리턴되는 값을 사용


'JSP > 기본(Oracle)' 카테고리의 다른 글

MVC 모델2 : (Album게시판)  (2) 2012.06.20
방명록  (0) 2012.06.20
회원관리  (1) 2012.06.20
모델2 : MVC : Model View Controller - DB연동  (0) 2012.06.20
모델2 : MVC : Model View Controlle r- DB연동없이  (0) 2012.06.20


프로젝트설정.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>&nbsp;</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>











create table guestbook(
num number primary key,
register date NOT NULL,
name varchar2(20) NOT NULL,
email varchar2(40),
passwd varchar2(10) NOT NULL,
content varchar2(4000) NOT NULL);

create sequence guestbook_seq;




글번호 num


insert into GUESTBOOK (num,register,name,email,passwd,content) values(guestbook_seq.nextval,?,?,?,?,?)


오라클 sequence guestbook_seq.curval 현재번호

          sequence guestbook_seq.nextval 다음번호


테이블작성






select * from(
       //시스템에서 제공하는 행번호 rownum의 별칭 rnum : 명시적 행번호 호출
       //a.* =  num,register,name,email,.... a아래있는 모든 컬럼이다. (a: 테이블에 대한 별칭)
select a.*, rownum rnum 
from(
//서브쿼리
select * 
from GUESTBOOK
order by num desc
)a//테이블 별칭
) where rnum >=1 and rnum <=10  //행번호 1~10 까지






M: Model : 자바클래스, 데이터 처리

V: View : JSP, 화면 디스클레이

C: Controller : servlet, 요청을 받아서 모델과 뷰를 호출하는 역활







Java Resources

        src

            com.guestbook.action

                 DeleteAction

package com.guestbook.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;

public class DeleteAction  implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        //1.전송된 num,비밀번호 추출
        int num = Integer.parseInt(request.getParameter("num"));
        String passwd = request.getParameter("passwd");
        
        //2. GuestbookDao의 uesrCheck에 num, 비밀번호 전달
        GuestbookDao manager = GuestbookDao.getInstance();
        int check = manager.userCheck(num, passwd);
        
        //3. check가 1인 경우 delete 메서드 호출
        if(check == 1){
            manager.delete(num);
        }
        //4. check를 request에 저장
        request.setAttribute("check", check);
        
        return "/view2/delete.jsp";
    }
}



                 DeleteFormAction

package com.guestbook.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guestbook.controller.Action;

public class DeleteFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        return "/view2/deleteForm.jsp";
    }
}



                 ListAction

package com.guestbook.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;
import com.guestbook.domain.Guestbook;
import com.guestbook.domain.GuestbookPage;

public class ListAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        //한페이지 글의수
        int pageSize = 10;
        
        String pageNum =request.getParameter("pageNum");
        if(pageNum ==null){
            pageNum = "1";
        }
        
        int currentPage = Integer.parseInt(pageNum);
        int startRow =(currentPage-1)*pageSize +1;
        int endRow =currentPage * pageSize;
        int count = 0;
        
        List<Guestbook> bookList =null;
        GuestbookDao manager = GuestbookDao.getInstance();
        count =manager.getCount();
        
        if(count>0){
            bookList = manager.getList(startRow, endRow);
        }

        //GuestbookPage : 자바빈 하나더 만들기
        //Guestbook 자바빈에 다 넣을수도있다, 그러나 분류를위해 나눠쓴것
        //작업자가 효율적으로 분류해서 쓰도록한다.
        GuestbookPage page= new GuestbookPage();
        page.setCount(count);
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        
        
        request.setAttribute("page", page);
        request.setAttribute("bookList", bookList);

        return "/view2/list.jsp";
    }
}



                 UpdateAction

package com.guestbook.action;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;
import com.guestbook.domain.Guestbook;

public class UpdateAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        //1.인코딩처리
        request.setCharacterEncoding("utf-8");            

        //2.자바빈 생성 및 전송된 데이터를 자바빈에 저장
        Guestbook book =new Guestbook();
        book.setNum(Integer.parseInt(request.getParameter("num")));
        book.setName(request.getParameter("name"));
        book.setEmail(request.getParameter("email"));   
        book.setPasswd(request.getParameter("passwd"));
        book.setContent(request.getParameter("content"));
        
        //3.GuestbookDao의 userCheck 메소드에 num과 비밀번호 전달인증
        GuestbookDao manager = GuestbookDao.getInstance();
        int check = manager.userCheck(book.getNum(),book.getPasswd());
        
        //4.check가 1인 경우 GuestbookDao의 update 메소드에 자바빈 전달                
        if(check==1){
        manager.update(book);        
        }
        //5.check를 request에 저장
        request.setAttribute("check", check);
        
        return "/view2/update.jsp;";
    }
}



                 UpdateFormAction

package com.guestbook.action;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;
import com.guestbook.domain.Guestbook;

public class UpdateFormAction  implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        //1. 전송된 글번호(num)를 request에서 추출
        int num = Integer.parseInt(request.getParameter("num"));
        
        
        //2. GuestbookDao의 getGuestbook 메소드에 num를 전달
        GuestbookDao manager = GuestbookDao.getInstance();
        Guestbook book = manager.getGuestBook(num);        
        
        //3. 자바빈을 reqeust에 저장
        request.setAttribute("book", book);
        
        return "/view2/updateForm.jsp";
    }
}



                 WriteAction

package com.guestbook.action;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guestbook.controller.Action;
import com.guestbook.dao.GuestbookDao;
import com.guestbook.domain.Guestbook;

public class WriteAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        //1.인코딩처리
        request.setCharacterEncoding("utf-8");
        
        //2.자바빈 생성 및 전송된 데이터를 자바빈에 저장
        Guestbook guestbook =new Guestbook();
        guestbook.setRegister(new Timestamp(System.currentTimeMillis()));
        guestbook.setName(request.getParameter("name"));
        guestbook.setEmail(request.getParameter("email"));   
        guestbook.setPasswd(request.getParameter("passwd"));
        guestbook.setContent(request.getParameter("content"));
        
        //3.GuestbookDao의 insert 메소드에 자바빈 전달                
        GuestbookDao manager = GuestbookDao.getInstance();
        manager.insert(guestbook);        
        
        return "/view2/write.jsp";
    }
}



                 WriteFormAction

package com.guestbook.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.guestbook.controller.Action;

public class WriteFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        return "view2/writeForm.jsp";
    }
}



        com.guestbook.controller

                 Action

package com.guestbook.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.guestbook.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.guestbook.dao

                 GuestbookDao

package com.guestbook.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.guestbook.domain.Guestbook;

public class GuestbookDao {
    private static GuestbookDao instance =new GuestbookDao();
    
    public static GuestbookDao getInstance(){
        return instance;
    }
    private GuestbookDao(){}
    
    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 insert(Guestbook book) throws Exception{
        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql="";
        //바인드문자 ?의 순서
        int cnt = 0;        
        
        try{
            conn= getConnection();
            sql = "insert into GUESTBOOK (num,register,name,email,passwd,content) " +
                    "values(guestbook_seq.nextval,?,?,?,?,?)";
            //sql ="insert into GUESTBOOK values(guestbook_seq.nextval,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(++cnt, book.getRegister());
            pstmt.setString(++cnt, book.getName());
            pstmt.setString(++cnt, book.getEmail());
            pstmt.setString(++cnt, book.getPasswd());
            pstmt.setString(++cnt, book.getContent());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //글의 총갯수
    public int getCount() throws Exception{
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        int count =0;
        String sql =null;
        
        try{
            conn=getConnection();
            // 갯수를 구하는 sql 함수 count(*) :레코드의 총수는
            sql="select count(*) from GUESTBOOK";
            pstmt =conn.prepareStatement(sql);
            rs =pstmt.executeQuery();
            if (rs.next()){
                //1: 컬럼의 순서 (가상의 컬럼 count(*))
                //getInt(count(*))도 가능
                count =rs.getInt(1);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }            
        return count;
    }
    
    //글 목록 
    public List<Guestbook> getList(int startRow, int endRow)throws Exception{
        
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        List<Guestbook>list =null;
        String sql="";
        
        try{
            conn =getConnection();
            //새글이 위로 올라오게 내림차순
            //sql ="select * from GUESTBOOK order by num desc";
            // select(select 서브쿼리)
            sql ="select * from(select a.*, rownum rnum from(select * from GUESTBOOK order by num desc)a) where rnum >=? and rnum <=?";
            pstmt =conn.prepareStatement(sql);
            
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            
            //sql문 반영
            rs=pstmt.executeQuery();
            
            //데이터가 있는가없는가 확인
            if(rs.next()){
                //있으면
                list= new ArrayList<Guestbook>();
                //if문에서 이미 커서가 첫번째 행을 가리키기 때문에 첫번째 행 부터 뽑기위해 do while 문
                do{
                    Guestbook book =new Guestbook();
                    book.setNum(rs.getInt("num"));
                    book.setRegister(rs.getTimestamp("register"));
                    book.setName(rs.getString("name"));
                    book.setEmail(rs.getString("email"));
                    book.setPasswd(rs.getString("passwd"));
                    book.setContent(rs.getString("content"));
                    list.add(book);
                }while(rs.next());
            }else{
                //없으면
                //데이터가 없는 경우 비어있는 List 생성
                list = Collections.EMPTY_LIST;
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return list;
    }
    
    //수정 폼에 보여질 한건의 레코드 정보
    public Guestbook getGuestBook(int num)throws Exception{
        Connection conn =null;
        PreparedStatement  pstmt= null;
        ResultSet rs = null;
        Guestbook book=null;
        String sql=null;
        
        try{
            conn=getConnection();
            sql ="select * from GUESTBOOK where num = ? ";
            
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                book=new Guestbook();
                book.setNum(rs.getInt("num"));
                book.setRegister(rs.getTimestamp("register"));
                book.setName(rs.getString("name"));
                book.setEmail(rs.getString("email"));
                book.setPasswd(rs.getString("passwd"));
                book.setContent(rs.getString("content"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return book;
    }
    
    //인증
    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 GUESTBOOK 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;
    }
    
    //글수정
    public void update(Guestbook book)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        int cnt =0;
        String sql = null;
        
        try{
            conn =getConnection();
            sql = "update GUESTBOOK set name=?,email=?, content=? where num=?";
            pstmt =conn.prepareStatement(sql);
            
            pstmt.setString(++cnt, book.getName());
            pstmt.setString(++cnt, book.getEmail());
            pstmt.setString(++cnt, book.getContent());    
            pstmt.setInt(++cnt, book.getNum());
            
            pstmt.executeUpdate();
            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }        
    }
    
    //글삭제
    public void delete(int num)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt=null;
        String sql=null;        
        
        try{            
            conn= getConnection();
            
            sql="delete from GUESTBOOK where num=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            pstmt.executeUpdate();

        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }        
        return ;
    }    
    
    //자원정리
    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.guestbook.domain

                 Guestbook

package com.guestbook.domain;

import java.sql.Timestamp;

public class Guestbook {
    
    private int num;
    private Timestamp register;
    private String name;
    private String email;
    private String passwd;
    private String content;
    
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public Timestamp getRegister() {
        return register;
    }
    public void setRegister(Timestamp register) {
        this.register = register;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}



                 GuestbookPage

package com.guestbook.domain;

public class GuestbookPage {

    private int count;
    private int pageSize;
    private int currentPage;
    
    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;
    }    
}



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>



WebContent

        view2

            delete.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>



            deleteForm.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></head>
<body>
<form action="delete.do" method="post">
<input type="hidden" name="num" value="${param.num }">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td>암호</td>
    <td><input type="password" name="passwd" size="10"><br>
    글을 쓸때 입력한 암호와 동일해야 글이 삭제됩니다.</td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글삭제하기"></td>
</tr>
</table>
</form>
</body>
</html>



            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></head>
<body>
<table width="100%" align="center">
<tr>
    <td>
    <a href="writeForm.do">글쓰기</a>
    </td>
</table>
<c:if test="${page.count == 0}">
<table width="100%" border="1" cellpadding="0" cellspacing="0" align="center">
<tr>
    <td bgcolor="#e9e9e9">
    방명록에 저장된 글이 없습니다.
    </td>
</table>
</c:if>
<c:if test="${page.count > 0}">
<table width="100%" border="1" cellpadding="0" cellspacing="0" align="center">
<!--
bookList를 받아 반복문 
EL 함수(잘안씀 교제 P523)외에는 프로퍼티형식
\$ 는 주석에서도 \로 무력화 시켜야한다.
\${book.email} O  \${book,getEmial()} X옳지않다.
\${book.name} O  \${book,getName()} X옳지않다.
표기법은 변수명이지만 사실상 getter메소드를 통해 출력받는다.
-->
<c:forEach var="book" items="${bookList}">
<tr>
    <td bgcolor="#e9e9e9">
    <b>${book.name}(${(book.email == null) ? "" : book.email})</b>
    - <font size="2">
    <fmt:formatDate value="${book.register}" pattern="yyyy년MM월dd일"/>
    <a href="updateForm.do?num=${book.num}">[수정]</a>
    <a href="deleteForm.do?num=${book.num}">[삭제]</a>
    </font>
    </td>
</tr>
<tr>
    <td>${book.content }</td>
</tr>
</c:forEach>
</table>
</c:if>
<div align="center">
<c:if test="${page.count > 0}">
    <!--
    1.페이지블록지정  EL로 감싸 넘김 ${10} Integer로 인정
    re: 
    value="${(page.currentPage - 1) / pageBlock}" integerOnly="true" :실수가 나와도 정수로만표현 
    -->
   <c:set var="pageBlock" value="${10}"/>
   <c:set var="pageCount" value="${(page.count - 1) / page.pageSize + 1}"/>
   <fmt:parseNumber var="rs" value="${(page.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 }">[이전]</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}">[${i}]</a>
       </c:if>
   </c:forEach>

   <c:if test="${endPage < pageCount}">
        <a href="list.do?pageNum=${startPage + pageBlock}">[다음]</a>
   </c:if>
</c:if>
</div>
</body>
</html>



            update.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>


 

            updateForm.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 checkIt() {
        var user = document.userinput;
               
        if(!user.name.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="update.do" method="post">
<!-- 
get방식으로 넘어온 num을 EL을 통해서 뽑아낸다. value="${param.num}"
-->
<input type="hidden" name="num" value="${param.num}">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td>암호</td>
    <td><input type="password" name="passwd" size="10"><br>
    글을 쓸때 입력한 암호와 동일해야 글이 수정됩니다.</td>
</tr>
<tr>
    <td>이름</td>
    <td><input type="text" name="name" 
               value="${book.name}" size="10"></td>
</tr>
<tr>
    <td>이메일</td>
    <td><input type="text" name="email" 
               value="${book.email}" size="30"></td>
</tr>
<tr>
    <td>내용</td>
    <td>
    <textarea name="content" rows="5" 
       cols="50">${book.content}</textarea>
    </td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글수정하기"></td>
</tr>

</table>
</form>
</body>
</html>



            write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<script type="text/javaScript">
alert("방명록에 글을 등록하였습니다.");
location.href="list.do";
</script>


  

            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 checkIt() {
        var user = document.userinput;
               
        if(!user.name.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 name="userinput" action="write.do" method="post" onsubmit="return checkIt()">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td>이름</td>
    <td><input type="text" name="name" size="10"></td>
</tr>
<tr>
    <td>암호</td>
    <td><input type="password" name="passwd" size="10"></td>
</tr>
<tr>
    <td>이메일</td>
    <td><input type="text" name="email" size="30"></td>
</tr>
<tr>
    <td>내용</td>
    <td><textarea name="content" rows="5" cols="50"></textarea></td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글남기기"></td>
</tr>
</table>
</form>
</body>
</html>



        WEB-INF

            lib

                 commons-collections-3.1.jar

                 commons-dbcp-1.2.1.jar

                 commons-pool-1.2.jar

                 jstl-1.2.jar


            commandMap.properties

/writeForm.do=com.guestbook.action.WriteFormAction
/write.do=com.guestbook.action.WriteAction
/list.do=com.guestbook.action.ListAction
/updateForm.do=com.guestbook.action.UpdateFormAction
/update.do=com.guestbook.action.UpdateAction
/deleteForm.do=com.guestbook.action.DeleteFormAction
/delete.do=com.guestbook.action.DeleteAction



            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>guestbook</display-name>
 <!-- Controller start -->
 <servlet>
     <servlet-name>Controller</servlet-name>
     <servlet-class>com.guestbook.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>






글등록 테스트  WriteFormAction -> writeForm.jsp -> WriteAction -> write.jsp









글목록 테스트  ListAction -> list.jsp




수정테스트 UpdateFormAction -> updateForm.jsp -> UpdateAction -> update.jsp -> list.do











삭제테스트 :  DeleteFormAction  -> deleteForm.jsp -> DeleteAction -> delete.jsp -> list.do







//Struts2 : MVC모델제공 => FrameWork


모델1, 모델2  DAO 나 자바빈은 변하지않아 재활용가능


예제. MEMBER (회원관리)

회원가입,아이디중복확인,로그인,정보수정,회원탈퇴(회원삭제)


member.war



Java Resources

        src

            com.action

                 ConfirmIdAction

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.controller.Action;
import com.dao.MemberDao;

public class ConfirmIdAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        String id =request.getParameter("id");
        MemberDao manager = MemberDao.getInstance();
        int check=manager.confirmId(id);
        
        request.setAttribute("check", new Integer(check));
        request.setAttribute("id", id);
        
        return "/view2/confirmId.jsp";
    }
}



                 DeleteFormAction

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.controller.Action;

public class DeleteFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        HttpSession session = request.getSession();
        if(session.getAttribute("memId") == null)
            return "/view2/loginForm.jsp";
            
        return "/view2/deleteForm.jsp";
    }
}



                 DeleteProAction

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.controller.Action;
import com.dao.MemberDao;

public class DeleteProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");
        
        //1. 로그인 여부 체크
        HttpSession session =request.getSession();
        if(session.getAttribute("memId")==null)
            return"/view2/loginForm.jsp";
        
        //2. session에서 id를 추출해고 전송받은 비밀번호를
        
        String id =(String)session.getAttribute("memId");
        String passwd = request.getParameter("passwd");
                
        //     memberDao의 userCheck 에 전달
        MemberDao manager = MemberDao.getInstance();
        int check = manager.userCheck(id, passwd);
        
        //3. check 1인 경우 deleteMember 메소드에 id 전달
        if(check== 1){
            manager.deleteMember(id);
            session.invalidate();
        }           
        
        //4. check를 request에 저장
        request.setAttribute("check", check);
        
        return "/view2/deletePro.jsp";
    }
}


                InputFormAction

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.controller.Action;

public class InputFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        return "/view2/inputForm.jsp";
    }  
}



                 InputProAction

package com.action;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.controller.Action;
import com.dao.MemberDao;
import com.domain.Member;

public class InputProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        //1.인코딩처리
        request.setCharacterEncoding("utf-8");
        
        //2.request에서 전송된 데이터를 추출        
        //3.자바빈에 데이터 셋팅        
        Member member =new Member();
        member.setId(request.getParameter("id"));
        member.setName(request.getParameter("name"));
        member.setPasswd(request.getParameter("passwd"));
        member.setJumin1(request.getParameter("jumin1"));
        member.setJumin2(request.getParameter("jumin2"));
        member.setEmail(request.getParameter("email"));
        member.setBlog(request.getParameter("blog"));       
        member.setReg_date(new Timestamp(System.currentTimeMillis()));
        
        //4.MemberDao의 insertMember 메소드 호출
        MemberDao manager = MemberDao.getInstance();
        manager.insertMember(member);
        
        return "/view2/inputPro.jsp";
    }
}


                 LoginAction

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.controller.Action;

public class LoginAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        HttpSession session =request.getSession();
        if(session.getAttribute("memId")==null)
            return "/view2/loginForm.jsp";

        return "/view2/login.jsp";
    }    
}


                 LoginFormAction

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.controller.Action;

public class LoginFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        return "/view2/loginForm.jsp";
    }  
}



                 LoginProAction

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.controller.Action;
import com.dao.MemberDao;

public class LoginProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        String id =request.getParameter("id");
        String passwd =request.getParameter("passwd");
        
        MemberDao manager = MemberDao.getInstance();
        int check= manager.userCheck(id, passwd);        
        
        if(check==1){
            HttpSession session=request.getSession();
            session.setAttribute("memId", id);
        }
        
        request.setAttribute("check", new Integer(check));
        
        return "/view2/loginPro.jsp";
    }
}



                 LogoutAction

package com.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.controller.Action;

public class LogoutAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        HttpSession session =request.getSession();
        session.invalidate();
        
        return "view2/logout.jsp";
    }
}



                 ModifyFormAction

package com.action;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.controller.Action;
import com.dao.MemberDao;
import com.domain.Member;

public class ModifyFormAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        //1. 로그인 여부 조사
        HttpSession session =request.getSession();
        if(session.getAttribute("memId")==null)
            return"/view/loginForm.jsp";

        //2.session에 저장된 id 호출        
        String id = (String)session.getAttribute("memId");  
            
        //3.MemberDao의 getMember 메서드에 id 전달
        MemberDao manager = MemberDao.getInstance();
        Member member = manager.getMember(id);        
        
        //4.반환받은  Member를 request에 저장
        request.setAttribute("member", member);
        
        return "/view2/modifyForm.jsp";
    }
}



                 ModifyProAction

package com.action;

import java.sql.Timestamp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.controller.Action;
import com.dao.MemberDao;
import com.domain.Member;

public class ModifyProAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        //1.로그인 여부 조사
        HttpSession session =request.getSession();
        if(session.getAttribute("memId")==null)
            return"/view/loginForm.jsp";
        
        //2.인코딩처리
        request.setCharacterEncoding("utf-8");
        
        //3.자바빈을 생성하고 자바빈에 전송된 데이터를 저장
        Member member =new Member();
        member.setId((String)session.getAttribute("memId"));
        member.setName(request.getParameter("name"));
        member.setPasswd(request.getParameter("passwd"));
        member.setJumin1(request.getParameter("jumin1"));
        member.setJumin2(request.getParameter("jumin2"));
        member.setEmail(request.getParameter("email"));
        member.setBlog(request.getParameter("blog"));  
        member.setReg_date(new Timestamp(System.currentTimeMillis()));
        
        //4.MemberDao의 updateMember 메소드에 자바빈 전달
        MemberDao manager = MemberDao.getInstance();
        manager.updateMember(member);
        
        return "/view2/modifyPro.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

                 MemberDao

package com.dao;

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

import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;

import com.domain.Member;

public class MemberDao {
    
        
/*    @싱글턴 패턴
    생성자의 접근지정자는 private으로 지정
    static한 getInstance()를  메소드를 사용
    객체의 주소를 보관하는 static 참조변수 사용 
      //참조변수 instance에 객체 주소할당
      //객체를 한번생성해서 계속가지고있슴 (변경에관한게 아무것도없슴)
    객체를 하나만 생성해서 공유하고자 싱글턴 패턴 구현
    @멤버변수가 있는 경우에는 절대로 싱글턴 패턴을 구현하면 안된다.
      //멤버변수를 공유시켜버리면 여러사용자가 멤버변수를 같이 변경하게됨    */
    private static MemberDao instance =new MemberDao();
    
    public static MemberDao getInstance(){
        return instance;
    }

    //생성자 인데 private 외부에서는 생성못하게 막아둔거
    //메소드를 static 하게만들어  메서드를  이용해서 
    //Member.getInstance();
    private MemberDao(){
    }
    
    //커네션풀로 부터 커넥션을 할당 받는 메소드
    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 insertMember(Member member)throws Exception{
        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql="";
        int cnt = 0;
        
        try{
            //커넥션 풀로 부터 커넥션 할당
            conn= getConnection();
            sql ="insert into MEMBER values(?,?,?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getId());
            pstmt.setString(++cnt, member.getPasswd());
            pstmt.setString(++cnt, member.getName());
            pstmt.setString(++cnt, member.getJumin1());
            pstmt.setString(++cnt, member.getJumin2());
            pstmt.setString(++cnt, member.getEmail());
            pstmt.setString(++cnt, member.getBlog());
            pstmt.setTimestamp(++cnt, member.getReg_date());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //회원 아이디 , 비밀번호 체크
    public int userCheck(String id, String passwd)throws Exception{
        
        Connection conn= null;
        PreparedStatement pstmt = null;
        ResultSet rs =null;
        String sql="";
        String dbpasswd="";
        int x = -1;
        
        try{
            conn =getConnection();
            sql ="select passwd from MEMBER where id = ?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                dbpasswd =rs.getString("passwd");
                if(dbpasswd.equals(passwd))
                    x=1; //인증성공
                else
                    x=0; //비밀번호 틀림
            }else
                x=-1; //해당 아이디 없음
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return x;
    }
    
    //회원 상세정보 
    public Member getMember(String id)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Member member=null;
        String sql="";
        try{
            conn=getConnection();
            sql="select * from MEMBER where id= ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs= pstmt.executeQuery();
            
            if(rs.next()){
                member=new Member();
                member.setId(rs.getString("id"));
                member.setPasswd(rs.getString("passwd"));
                member.setName(rs.getString("name"));
                member.setJumin1(rs.getString("jumin1"));
                member.setJumin2(rs.getString("jumin2"));
                member.setEmail(rs.getString("email"));
                member.setBlog(rs.getString("blog"));
                member.setReg_date(rs.getTimestamp("reg_date"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return member;
    }
    
    //회원정보 수정
    public void updateMember(Member member)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        int cnt =0;
        try{
            conn =getConnection();
            sql = "update MEMBER set passwd=?,name=?,email=?, blog=? where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getPasswd());
            pstmt.setString(++cnt, member.getName());
            pstmt.setString(++cnt, member.getEmail());
            pstmt.setString(++cnt, member.getBlog());
            pstmt.setString(++cnt, member.getId());
            
            pstmt.executeUpdate();
            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }   
    
    //회원탈퇴 , 회원정보 삭제
    public void deleteMember(String id)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        try{
            conn =getConnection();
            sql = "delete from MEMBER where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //ID 중복 체크
    public int confirmId(String id)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql="";
        int x=-1;
        try{
            conn=getConnection();
            sql="select * from MEMBER where id= ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs= pstmt.executeQuery();    
            
            if(rs.next())
                x=1; //해당아이디 있음
            else
                x=-1;//해당아이디 없음
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        
        return x;
    }
    
    //자원 정리를 위한 메소드
    //계란노른자
    //Connection 를통해서 PreparedStatement 를생성하고 
    //PreparedStatement 를 통해서 ResultSet 를 생성하기때문에
    //종료할때는 ResultSet=>PreparedStatement=>Connection 와같이 생성순서의 역순으로 close 해줘야한다
    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.doamin

                 Member

package com.domain;
import java.sql.Timestamp;

//자바빈
public class Member {
    //프로퍼티
    private String id;
    private String passwd;
    private String name;
    private String jumin1;
    private String jumin2;
    private String email;
    private String blog;
    private Timestamp reg_date;
    
    //getter
    public String getId() {
        return id;
    }
    //setter
    public void setId(String id) {
        this.id = id;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJumin1() {
        return jumin1;
    }
    public void setJumin1(String jumin1) {
        this.jumin1 = jumin1;
    }
    public String getJumin2() {
        return jumin2;
    }
    public void setJumin2(String jumin2) {
        this.jumin2 = jumin2;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getBlog() {
        return blog;
    }
    public void setBlog(String blog) {
        this.blog = blog;
    }
    public Timestamp getReg_date() {
        return reg_date;
    }
    public void setReg_date(Timestamp reg_date) {
        this.reg_date = reg_date;
    }
    
    @Override
    public String toString() {
        return "Member [id=" + id + ", passwd=" + passwd + ", name=" + name
                + ", jumin1=" + jumin1 + ", jumin2=" + jumin2 + ", email="
                + email + ", blog=" + blog + ", reg_date=" + reg_date + "]";
    }    
}




WebContent

        view2

            confirmId.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>ID 중복확인</title>
<script type="text/javascript">
<!--
  function setid()
    {        
        opener.document.userinput.id.value="${id}";
        self.close();
    }
        //-->
</script>
</head>
<body>
<c:if test="${check == 1}">
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <td height="39" >${id }이미 사용중인 아이디입니다.</td>
  </tr>
</table>
<form name="checkForm" method="post" action="confirmId.do">
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <td align="center"> 
       다른 아이디를 선택하세요.<p>
       <input type="text" size="10" maxlength="12" name="id"> 
       <input type="submit" value="ID중복확인">
    </td>
  </tr>
</table>
</form>
</c:if>
<c:if test="${check != 1}">
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr> 
    <td align="center"> 
      <p>입력하신 ${id} 는 사용하실 수 있는 ID입니다. </p>
      <input type="button" value="닫기" onclick="setid()">
    </td>
  </tr>
</table>
</c:if>
</body>
</html>



            deleteForm.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>
<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" 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='login.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" %>  
<!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>
</head>
<body>
<c:if test="${check == 1}">
회원정보가 삭제되었습니다.
<input type="button" value="확인" onclick="location.href='loginForm.do'">
</c:if>
<c:if test="${check != 1}">
    <script>
        alert("비밀번호가 맞지 않습니다.");
        history(-1);
    </script>
</c:if>
</body>
</html>



            inputForm.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 checkIt() {
        var userinput = document.userinput;
        if(!userinput.id.value) {
            alert("ID를 입력하세요");
            userinput.id.focus();
            return false;
        }
        if(!userinput.passwd.value ) {
            alert("비밀번호를 입력하세요");
            userinput.passwd.focus();
            return false;
        }
        if(userinput.passwd.value != userinput.passwd2.value){
            alert("비밀번호를 동일하게 입력하세요");
            userinput.passwd2.focus();
            return false;
        }
        if(!userinput.name.value) {
            alert("사용자 이름을 입력하세요");
            userinput.name.focus();
            return false;
        }
        if(!userinput.jumin1.value)
        {
            alert("주민등록번호를 입력하세요");
            userinput.jumin1.focus();
            return false;
        }
        if(!userinput.jumin2.value)
        {
            alert("주민등록번호를 입력하세요");
            userinput.jumin2.focus();
            return false;
        }
    }

    // 아이디 중복 여부를 판단
    function openConfirmid(userinput) {
        // 아이디를 입력했는지 검사
        if (userinput.id.value == "") {
            alert("아이디를 입력하세요");
            return;
        }
        // url과 사용자 입력 id를 조합합니다.
        url = "confirmId.do?id=" + userinput.id.value ;
        
        // 새로운 윈도우를 엽니다.
        open(url, "confirm", 
        "toolbar=no, location=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=300, height=200");
    }
    //주민번호 6자리 입력 후 자동으로 다음 칸으로 이동
    function nextField(userinput,checklength){
            if( userinput.jumin1.value.length  >= checklength ) {
            userinput.jumin2.focus();
        }
        return true;
    }
</script>
</head>
<body>
<form method="post" action="inputPro.do" name="userinput" onSubmit="return checkIt()">
  <table width="600" border="1" cellspacing="0" cellpadding="3" align="center" >
    <tr> 
    <td colspan="2" height="39" align="center">
       <font size="+1" ><b>회원가입</b></font></td>
    </tr>
    <tr> 
      <td width="200"><b>아이디 입력</b></td>
      <td width="400">&nbsp;</td>
    </tr>  
    <tr> 
      <td width="200"> 사용자 ID</td>
      <td width="400"> 
        <input type="text" name="id" size="10" maxlength="12">
        <input type="button" name="confirm_id" value="ID중복확인" OnClick="openConfirmid(this.form)">
      </td>
    </tr>
    <tr> 
      <td width="200"> 비밀번호</td>
      <td width="400" > 
        <input type="password" name="passwd" size="15" maxlength="12">
      </td>
    </tr>  
    <tr>  
      <td width="200">비밀번호 확인</td>
      <td width="400"> 
        <input type="password" name="passwd2" size="15" maxlength="12">
      </td>
    </tr>
    <tr> 
      <td width="200"><b>개인정보 입력</b></td>
      <td width="400">&nbsp;</td>
    </tr>  
    <tr> 
      <td width="200">사용자 이름</td>
      <td width="400"> 
        <input type="text" name="name" size="15" maxlength="10">
      </td>
    </tr>
    <tr> 
      <td width="200">주민등록번호</td>
      <td width="400"> 
        <input type="text" name="jumin1" onKeyUp="nextField(this.form,6);"  size="7" maxlength="6">
        -<input type="text" name="jumin2" size="7" maxlength="7">
      </td>
    </tr>
    <tr> 
      <td width="200">E-Mail</td>
      <td width="400"> 
        <input type="text" name="email" size="40" maxlength="30">
      </td>
    </tr>
    <tr> 
      <td width="200"> Blog</td>
      <td width="400"> 
        <input type="text" name="blog" size="60" maxlength="50">
      </td>
    </tr>
    <tr> 
      <td colspan="2" align="center"> 
          <input type="submit" name="confirm" value="등   록" >
          <input type="reset" name="reset" value="다시입력">
          <input type="button" value="가입안함" onclick="javascript:window.location='login.do'">
      </td>
    </tr>
  </table>
</form>
</body>
</html>


 

           inputPro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<script>
alert("축하! 축하!");
location.href="login.do"
</script>



            login.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>
</head>
<body>
   <table width=500 cellpadding="0" cellspacing="0"  align="center" border="1" >
         <tr>
           <td width="300" height="20">하하하</td>

           <td rowspan="3" align="center">
             ${sessionScope.memId}님이 <br>
             방문하셨습니다
             <form  method="post" action="logout.do">  
             <input type="submit"  value="로그아웃">
              <input type="button" value="회원정보변경" onclick="javascript:window.location='modifyForm.do'">
             <input type="button" value="회원탈퇴" onclick="javascript:window.location='deleteForm.do'">
             </form>
         </td>
        </tr> 
       <tr> 
         <td rowspan="2" width="300" >메인입니다.</td>
      </tr>
     </table>
     <br>
</body>
</html>



            loginForm.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 begin(){
         document.myform.id.focus();
       }
       function checkIt(){
         if(!document.myform.id.value){
           alert("이름을 입력하지 않으셨습니다.");
           document.myform.id.focus();
           return false;
         }  
         if(!document.myform.passwd.value){
           alert("비밀번호를 입력하지 않으셨습니다.");
           document.myform.passwd.focus();
           return false;
         }
         return true;
       }
     //-->
   </script>
</head>
<BODY onload="begin()">
<form name="myform" action="loginPro.do" method="post" onSubmit="return checkIt()">
<table cellspacing=1 cellpadding=1 width="260" border=1 align="center" >
  
  <tr height="30">
    <td colspan="2" align="center"><strong>회원로그인</strong></td></tr>
  
  <tr height="30">
    <td width="110" align=center>아이디</td>
    <td width="150" align=center>
       <input type="text" name="id" size="15" maxlength="12"></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='inputForm.do'"></td></tr>
</table>
</form>

</body>
</html>



            loginPro.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>
    location.href="login.do";
</script>
</c:if>
<c:if test="${check == 0}">
<script>
    alert("비밀번호가 맞지 않습니다.");
    history.go(-1);
</script>
</c:if>
<c:if test="${check == -1}">
<script>
    alert("아이디가 맞지 않습니다.");
    history.go(-1);
</script>
</c:if>



            logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    response.sendRedirect("loginForm.do");
%> 



            modifyForm.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>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javaScript">
   <!-- 
    function checkIt() {
        var userinput = document.userinput;
               
        if(!userinput.passwd.value ) {
            alert("비밀번호를 입력하세요");
            return false;
        }
       
        if(!userinput.name.value) {
            alert("사용자 이름을 입력하세요");
            return false;
        }
        return true;
    }
//-->
</script>
</head>
<body>
<form method="post" action="modifyPro.do" name="userinput" onsubmit="return checkIt()">

  <table width="600" border="1" cellspacing="0" cellpadding="3"  align="center">
    <tr> 
      <td colspan="2" height="39" align="center">
         <font size="+1" ><b>회원 정보수정</b></font></td>
    </tr>
    <tr>
      <td colspan="2" align="center">회원의 정보를 수정합니다.</td>
    </tr>
     <tr> 
      <td width="200"><b>아이디 입력</b></td>
      <td width="400">&nbsp;</td>
    </tr>  
    <tr> 
      <td  width="200"> 사용자 ID</td>
      <td  width="400">${member.id}</td>
    </tr>
    
     <tr> 
      <td width="200"> 비밀번호</td>
      <td width="400"> 
        <input type="password" name="passwd" size="10" maxlength="10" value="${member.passwd}">
      </td>
    </tr>  
    <tr> 
      <td  width="200"><b>개인정보 입력</b></td>
      <td width="400">&nbsp;</td>
    </tr>  
    <tr> 
      <td   width="200">사용자 이름</td>
      <td  width="400"> 
        <input type="text" name="name" size="15" maxlength="10" value="${member.name}">
      </td>
    </tr>
    <tr> 
      <td width="200">주민등록번호</td>
      <td width="400"> 
        ${member.jumin1}-${member.jumin2}
      </td>
    </tr>
   <tr> 
      <td width="200">E-Mail</td>
      <td width="400">
          <input type="text" name="email" size="40" maxlength="30" value="${member.email}">
      </td>
    </tr>
    <tr> 
      <td width="200">Blog</td>
      <td width="400"> 
        <input type="text" name="blog" size="60" maxlength="50" value="${member.blog}">
      </td>
    </tr>      
    <tr> 
      <td colspan="2" align="center"> 
       <input type="submit" name="modify" value="수   정" >
       <input type="button" value="취  소" onclick="javascript:window.location='login.do'">      
      </td>
    </tr>
  </table>
</form>
</body>
</html>


            modifyPro.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>회원정보 수정</title>
</head>
<body>
회원정보가 수정되었습니다.
<input type="button" value="메인으로" onclick="location='login.do'">
</body>
</html>



        WEB-INF

            lib

                 commons-collections-3.1.jar

                 commons-dbcp-1.2.1.jar

                 commons-pool-1.2.jar

                 jstl-1.2.jar


            commandMap.properties

/inputForm.do=com.action.InputFormAction
/inputPro.do=com.action.InputProAction
/loginForm.do=com.action.LoginFormAction
/loginPro.do=com.action.LoginProAction
/login.do=com.action.LoginAction
/logout.do=com.action.LogoutAction
/modifyForm.do=com.action.ModifyFormAction
/modifyPro.do=com.action.ModifyProAction
/deleteForm.do=com.action.DeleteFormAction
/deletePro.do=com.action.DeleteProAction
/confirmId.do=com.action.ConfirmIdAction



            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>



회원가입 테스트 : InputFormAction -> inputForm -> InputAction -> input -> LoginFormAction -> loginForm





로그인 테스트 : LoginAction(섹션내용으로 로그인체크) ->로그아웃상태 -> LoginFormAction ->  LoginProAction->






로그아웃 테스트  LogoutAction -> logout ->login.do




수정 테스트 : ModifyFormAction -> modifyForm.jsp -> ModifyProAction -> modifyPro.jsp -> login.do










회원탈퇴 테스트 : DeleteFormAction -> deleteForm.jsp -> DeleteProAction -> deletePro.jsp -> loginForm.do






중복아이디 체크  ConfirmIdAction-> confirmId




예제3: Model 2  DB연동 : ORACLE DB. MEMBER1 테이블 사용


mvcMain2.war


Java Resources 
     dr.mini.action 

         DeleteAction

package dr.mini.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dr.mini.controller.Action;
      
import dr.mini.dao.MemberDao;

public class DeleteAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");
                
        MemberDao manager = MemberDao.getInstance();
        int check = manager.userCheck(request.getParameter("id"), request.getParameter("passwd"));
        
        if(check == 1){
            manager.deleteMember(request.getParameter("id"));
        }
        
        request.setAttribute("check", check);

        return "/view/delete.jsp";
    }
}


DeleteFormAction
package dr.mini.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dr.mini.controller.Action;

public class DeleteFormAction implements Action{
      
    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        request.setCharacterEncoding("utf-8");
        
        String id = request.getParameter("id");
        
        request.setAttribute("id", id);
        
        return "/view/deleteForm.jsp";
    }
}


InsertAction
package dr.mini.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dr.mini.controller.Action;

import java.sql.Timestamp;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class InsertAction implements Action{
     
    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
            
        request.setCharacterEncoding("utf-8");
        
        Member member =new Member();
        member.setId(request.getParameter("id"));
        member.setName(request.getParameter("name"));
        member.setPasswd(request.getParameter("passwd"));
        member.setRegister(new Timestamp(System.currentTimeMillis()));
        
        MemberDao manager = MemberDao.getInstance();
        manager.insertMember(member);
                
        return "/view/insert.jsp";
    }
}
InsertFormAction
package dr.mini.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dr.mini.controller.Action;

public class InsertFormAction implements Action{
   
    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        return "/view/insertForm.jsp";
    }
}

SelectDetailAction
package dr.mini.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class SelectDetailAction implements Action {

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
           
        request.setCharacterEncoding("utf-8");
        
        String id = request.getParameter("id");
        MemberDao mdb=MemberDao.getInstance();
        Member member =mdb.getMember(id);
        
        request.setAttribute("member", member);
        
        return "/view/selectDetail.jsp";
    }
}


SelectListAction
package dr.mini.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;
import java.util.List;

public class SelectListAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");

        List<member> List =null;        
        MemberDao mdb = MemberDao.getInstance();
        List = mdb.getMemberList();
        
        request.setAttribute("memberList", List);
   
        return "/view/selectList.jsp";
    }
}


UpdateAction
package dr.mini.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class UpdateAction implements Action{

    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setCharacterEncoding("utf-8");
            
        MemberDao manager = MemberDao.getInstance();        
        int check = manager.userCheck(request.getParameter("id"), request.getParameter("passwd"));
        
        if(check==1){
            Member member =new Member();
            member.setId(request.getParameter("id"));
            member.setName(request.getParameter("name"));
            manager.updateMember(member);
        }
        //오토박싱
        request.setAttribute("check", check);
        
        return "/view/update.jsp";
    }
}

   

 UpdateFormAction

package dr.mini.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dr.mini.controller.Action;
import dr.mini.dao.MemberDao;
import dr.mini.domain.Member;

public class UpdateFormAction implements Action{
      
    @Override
    public String execute(HttpServletRequest request,HttpServletResponse response) throws Throwable {
    
        request.setCharacterEncoding("utf-8");
        
        String id = request.getParameter("id");
        
        MemberDao manager= MemberDao.getInstance();
        Member member = manager.getMember(id);
        
        request.setAttribute("member", member);
        
        return "/view/updateForm.jsp";
    }
}

dr.mini.controller 

 Action

package dr.mini.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 dr.mini.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);
    }
}


dr.mini.dao 

 MemberDao

package dr.mini.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 dr.mini.domain.Member;

public class MemberDao {
    
    private static MemberDao instance = new MemberDao();

    public static MemberDao getInstance() {
        return instance;
    }

    private MemberDao(){}
   
    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 insertMember(Member member)throws Exception {
        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql="";
        int cnt = 0;
        
        try{
            conn= getConnection();
            sql ="insert into MEMBER1 values(?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getId());
            pstmt.setString(++cnt, member.getPasswd());
            pstmt.setString(++cnt, member.getName());
            pstmt.setTimestamp(++cnt, member.getRegister());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //회원 목록 보기
    public List getMemberList()throws Exception {
        
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        List memeberList =null;
        Member member=null;
        String sql="";
        
        try{
            conn =getConnection();
            sql ="select * from MEMBER1 order by register desc";
            pstmt =conn.prepareStatement(sql);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                memeberList= new ArrayList();
                do{
                    member =new Member();
                    member.setId(rs.getString("id"));
                    member.setPasswd(rs.getString("passwd"));
                    member.setName(rs.getString("name"));
                    member.setRegister(rs.getTimestamp("register"));
                    memeberList.add(member);
                }while(rs.next());
            }else{
                //없으면
                //데이터가 없는 경우 비어있는 List 생성
                memeberList = Collections.EMPTY_LIST;
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return memeberList;
    }
    
    //회원 상세 정보 보기
    public Member getMember(String id)throws Exception {
        
        Connection conn =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Member member=null;
        String sql="";
        try{
            conn=getConnection();
            sql="select * from MEMBER1 where id= ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs= pstmt.executeQuery();
            
            if(rs.next()){
                member=new Member();
                member.setId(rs.getString("id"));
                member.setPasswd(rs.getString("passwd"));
                member.setName(rs.getString("name"));
                member.setRegister(rs.getTimestamp("register"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return member;
    }
    
    //회원 인증
    public int userCheck(String id, String passwd)throws Exception {
        Connection conn= null;
        PreparedStatement pstmt = null;
        ResultSet rs =null;
        String sql="";
        String dbpasswd="";
        int x = -1;
        
        try{
            conn =getConnection();
            sql ="select passwd from MEMBER1 where id = ?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                dbpasswd =rs.getString("passwd");
                if(dbpasswd.equals(passwd))
                    x=1; //인증성공
                else
                    x=0; //비밀번호 틀림
            }else
                x=-1; //해당 아이디 없음
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return x;
    }
    
    //회원 정보 수정
    public void updateMember(Member member)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        int cnt =0;
        try{
            conn =getConnection();
            sql = "update MEMBER1 set name=? where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getName());
            pstmt.setString(++cnt, member.getId());
            
            pstmt.executeUpdate();
            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //회원 탈퇴 //회원정보 삭제
    public void deleteMember(String id)throws Exception {
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        try{
            conn =getConnection();
            sql = "delete from MEMBER1 where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //자원정리
        private void execClose(ResultSet rs,PreparedStatement pstmt, Connection conn){
            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) {}
        }
}

dr.mini.domain 

 Member

package dr.mini.domain;

import java.sql.Timestamp;

//자바빈
public class Member {
    //프로퍼티
    private String id;
    private String passwd;
    private String name;
    private Timestamp register;    
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Timestamp getRegister() {
        return register;
    }
    public void setRegister(Timestamp register) {
        this.register = register;
    }
}

WebContent 
     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>

view 

 delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<%    //오토언박싱
    int check =(Integer)request.getAttribute("check");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>레코드 삭제 예제</title>
</head>
<body>
<%if (check == 1){ %>
<script type="text/javascript">
alert("글을 삭제하였습니다");
location.href="selectList.do";
</script>
<% 
    }else{
%>
<script type="text/javascript">
alert("암호가 다릅니다.");
history.go(-1);
</script>
<%
    }
%>
</body>
</html>



deleteForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<% 
  String id = (String)request.getAttribute("id");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>레코드 삭제 예제</title></head>
<body>
  <h2>member1 테이블에 삭제 예제</h2>
  <form method="post" action="delete.do">
  <input type="hidden" name="id" value="<%=id %>">
    아이디 : <%=id %><p>
    패스워드 : <input type="password" name="passwd"><p>
    <input type="submit" value="보내기">
  </form>
</body>
</html>

insert.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>
</head>
<body>
  member1 테이블에 새로운 레코드를 삽입(추가)했습니다.
  <input type="button" value="목록보기" onclick="location.href='selectList.do'">
</body>
</html>    

insertForm.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></head>
<body>
  <h2>member1 테이블에 레코드삽입(추가)예제</h2>
  <form method="post" action="insert.do">
    아이디 : <input type="text" name="id"><p>
    패스워드 : <input type="password" name="passwd"><p>
    이름:<input type="text" name="name"><p>
    <input type="submit" value="보내기">
  </form>
</body>
</html>  

selectDetail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="dr.mini.domain.Member" %>
<%
    Member member = (Member)request.getAttribute("member");
%>
<!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>
</head>
<body>
<h2>회원관리 상세 페이지</h2>
아이디:<%=member.getId() %><br/>
패스워드:<%=member.getPasswd() %><br/>
이름:<%=member.getName() %><br/>
<input type="button" value="수정" onclick="location.href='updateForm.do?id=<%=member.getId()%>'">
<input type="button" value="삭제" onclick="location.href='deleteForm.do?id=<%=member.getId()%>'">
</body>
</html>   

selectList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="dr.mini.domain.Member"%>
<%@ page import="java.text.SimpleDateFormat"%>
<!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>
</head>
<body>
    <h2>member1 테이블의 레코드를 화면에 표시하는 예제</h2>
    <a href="insertForm.do">등록</a>
    <br />
    
    <% //목록같은경우는 어쩔수없이 jsp에서 루프를 돌려야함.
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy년 MM월 dd일  HH:mm:ss");
        //제네릭표현에 의해 타입이 정해져있음
        List<Member> memberList = (List<Member>)request.getAttribute("memberList");
        
        Member mb=null;
        if(!memberList.isEmpty()){
            for(int i=0;i<memberList.size();i++){
                //제네릭 표현때문에 (Member)memberList를 memberList로 생략가능
                mb=memberList.get(i);
    %>
    <a href="selectDetail.do?id=<%=mb.getId()%>"><%=mb.getId()%></a>-<%=mb.getPasswd()%>-<%=mb.getName()%>-<%=dateFormat.format(mb.getRegister())%><br />
    <%}}%>
</body>
</html>

update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>   
<%   //오토언박싱 
    int check =(Integer)request.getAttribute("check");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>레코드 수정 예제</title>
</head>
<body>
<%if (check == 1){ %>
<script type="text/javascript">
alert("글을 수정하였습니다");
location.href="selectList.do";
</script>
<% 
    }else{
%>
<script type="text/javascript">
alert("암호가 다릅니다.");
history.go(-1);
</script>
<%
    }
%>
</body>
</html>

updateForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="dr.mini.domain.Member" %>
<%
    Member member=(Member)request.getAttribute("member");
%>
<!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>
</head>
<body>
<h2>member1 테이블에 레코드 수정 예제</h2>
<form method="post" action="update.do">
<input type="hidden" name="id" value="<%=member.getId()%>">
아이디:<%=member.getId() %><p>
패스워드:<input type="password" name="passwd"><p>
이름:<input type="text" name="name" value="<%=member.getName()%>"><p>
<input type="submit" value="보내기">
</form>
</body>
</html>
WEB-INF 
 lib 
 commons-collections-3.1.jar 
 commons-dbcp-1.2.1.jar 
 commons-pool-1.2.jar 

 commandMap.properties
/insertForm.do=dr.mini.action.InsertFormAction
/insert.do=dr.mini.action.InsertAction
/selectList.do=dr.mini.action.SelectListAction
/selectDetail.do=dr.mini.action.SelectDetailAction
/updateForm.do=dr.mini.action.UpdateFormAction
/update.do=dr.mini.action.UpdateAction
/deleteForm.do=dr.mini.action.DeleteFormAction
/delete.do=dr.mini.action.DeleteAction

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">
 
 <!-- Controller start -->
 <servlet>
     <servlet-name>Controller</servlet-name>
     <servlet-class>dr.mini.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 -->
   
  <display-name>mvcMain2</display-name>
  <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>



컨트롤러 맵핑확인 :Controller


insertForm.do 로연결확인



회원가입 테스트 [Controller 실행 ->요청-> InsertFormAction.java->insertForm.jsp  -> insertAction.java-> insert.jsp]


DB입력확인


리스트확인 : selectList.do


상세페이지 테스트 : SelectDetailAction -> selectDetail.jsp


수정페이지 테스트 : UpdateFormAction ->updateForm.jsp ->UpdateActioc ->update.jsp




삭제테스트 : DeleteFormAction ->deleteForm.jsp ->DeleteActioc ->delete.jsp

'JSP > 기본(Oracle)' 카테고리의 다른 글

방명록  (0) 2012.06.20
회원관리  (1) 2012.06.20
모델2 : MVC : Model View Controlle r- DB연동없이  (0) 2012.06.20
MVC: Model View Controller 모델2 ( 완전중요)  (0) 2012.06.20
EL(표현언어), JSTL, 국제화 태그 - 예제  (0) 2012.06.20

모델2

액션클레스  <= 인터페이스  다수의 액션클래스 동일한형태

                                                          자료형일치

                                                          형태통일화


servlet : BasicController

클래스핸들러 : HelloHandler

인터페이스 :  CommandHandler

뷰 : hello.jsp

맵핑 : web.xml


properties 설정파일 : commandHandler.properties

                                                      hello = HelloHandler

                                                      list = ListHandler

                                                      Notice = NoticeHandler







1.클라이언트 요청 :  /basic?command=hello

       ||

2.servlet(controller)  : 분석 command = hello 이더라 설정파일에서 hello에 맞는 액션클래스로!!

       ||

3.액션클래스(Model의 입구) : 요청에 맞는 비지니스 로직을 처리하여 request에 값을저장하고 

servlet으로 jsp경로 전달

       ||

4.servlet(controller) : 받아온 jsp경로를 view로 선택

       ||

5.JSP(View) : request로부터 값을받아들여 (포워딩되어 request영역을 공유,session은 과부하가 우려된다.)

사용자에게 HTML응답해줌



예제2: Model 2  DB연동 X




Java Resources

            kame.chap24

                      BasicController (설정파일없이 서블릿안에서 요청분석

package kame.chap24;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kame.chap24.command.HelloHandler;
import kame.chap24.command.ListHandler;
import kame.chap24.command.NoticeHandler;
import kame.mvc.command.CommandHandler;

public class BasicController extends HttpServlet{

    //1단계의 요청을 받음 
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        processRequest(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

        String view=null;
        
        //글로벌 자료형사용하기위해 인터페이스 사용
        CommandHandler com = null;

        //클라이언트가 어떤한 걸 모델클레스를 요청하는지 알려줄꺼 
        String command= request.getParameter("command");        

        if(command.equals("hello")){
            com =new HelloHandler();
            //모델클래스 분기점
        }else if(command.equals("list")){
            com =new ListHandler();
        }else if(command.equals("notice")){
            com =new NoticeHandler();
        }
        try{
            view=com.process(request, response);
        }catch(Throwable e){
            e.printStackTrace();
        } 


        //5단계, RequestDispatcher를 사용하여 알맞은 뷰로 포워딩
        RequestDispatcher dispatcher=request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }
}


kame.chap24.command (액션클래스 servlet이 요청분석을하여 요청처리에맞는 액션클래스 호출) 
ByeHandler
package kame.chap24.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kame.mvc.command.CommandHandler;


public class ByeHandler implements CommandHandler{

    @Override
    public String process(HttpServletRequest request,
            HttpServletResponse response) throws Throwable {

        request.setAttribute("bye", "안녕히 가세요!!");
        
        
        return "/view/bye.jsp";
    }
}

HelloHandler

package kame.chap24.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kame.mvc.command.CommandHandler;

public class HelloHandler implements CommandHandler{

    @Override
    public String process(HttpServletRequest request,HttpServletResponse response) throws Throwable {

        request.setAttribute("hello", "안녕하세요!");
        
        return "/view/hello.jsp";
    }
}


ListHandler

package kame.chap24.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kame.mvc.command.CommandHandler;

public class ListHandler implements CommandHandler{

    @Override
    public String process(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setAttribute("list", "목록을 화면에 리스트 합니다.");
        
        return "/view/list.jsp";
    }
}

NoticeHandler

package kame.chap24.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kame.mvc.command.CommandHandler;

public class NoticeHandler implements CommandHandler {

    @Override
    public String process(HttpServletRequest request,HttpServletResponse response) throws Throwable {
        
        request.setAttribute("notice", "뉴스를 알려드리겠습니다.");        
        
        return "/view/notice.jsp";
    }
}



kame.mvc.command (액션클래스의 인터페이스 : 다수의 액션클래스에 자료형일치,형태통일화)

CommandHandler

package kame.mvc.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//인터페이스
public interface CommandHandler {
    public String process(HttpServletRequest request, HttpServletResponse response)throws Throwable;
}



kame.mvc.contoller

                      ControllerUsingFile (요청설정파일을통한 컨트롤러:서블릿)

package kame.mvc.controller;

import java.io.FileInputStream;
import java.io.IOException;
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;

import kame.mvc.command.CommandHandler;

public class ControllerUsingFile extends HttpServlet {

    // <커맨드, 핸들러인스턴스> 매핑 정보 저장
    //데이터를 담을 HashMap을 생성
    private Map commandHandlerMap = new java.util.HashMap();

    //ServletConfig : 서블릿이 만들어질때 각각의 서블릿에 생성되는 ServletConfig :비서같은 역활
    public void init(ServletConfig config) throws ServletException {
        String configFile = config.getInitParameter("configFile");
        //Properties 키 = 값 을 구분해서 분리해줌
        Properties prop = new Properties();
        FileInputStream fis = null;
        try {
            //getRealPath : 상대경로를 절대경로로 만들어줌
            ///WEB-INF/commandHandler.properties 를 절대경로로 만듬
            String configFilePath = config.getServletContext().getRealPath(configFile);
            //commandHandler.properties 설정파일을 파일내용 그대로 읽어옴
            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()) {
            //command 키값
            String command = (String) keyIter.next();
            //prop.getProperty(command) : 값(value)를 리턴함
            String handlerClassName = prop.getProperty(command);
            try {
                //Class.forName() : 클래스정보를 문자열(handlerClassName)로 받아서 실제클래스를 찾는다.
                Class handlerClass = Class.forName(handlerClassName);
                Object handlerInstance = handlerClass.newInstance();
                commandHandlerMap.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(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        process(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }

    private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       
     String command = request.getParameter("command");

        CommandHandler handler = (CommandHandler) commandHandlerMap
                .get(command);
        
        String viewPage = null;
        
        try {
            viewPage = handler.process(request, response);
        } catch (Throwable e) {
            throw new ServletException(e);
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
        dispatcher.forward(request, response);
    }
}

ControllerUsingURI (요청설정파일을통한 URI 컨트롤러:서블릿)
package kame.mvc.controller;

import java.io.FileInputStream;
import java.io.IOException;
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;

import kame.mvc.command.CommandHandler;

public class ControllerUsingURI extends HttpServlet {

    // <커맨드, 핸들러인스턴스> 매핑 정보 저장
    //데이터를 담을 HashMap을 생성
    private Map commandHandlerMap = new java.util.HashMap();

    //ServletConfig : 서블릿이 만들어질때 각각의 서블릿에 생성되는 ServletConfig :비서같은 역활
    public void init(ServletConfig config) throws ServletException {
        String configFile = config.getInitParameter("configFile");
        //Properties 키 = 값 을 구분해서 분리해줌
        Properties prop = new Properties();
        FileInputStream fis = null;
        try {
            //getRealPath : 상대경로를 절대경로로 만들어줌
            ///WEB-INF/commandHandler.properties 를 절대경로로 만듬
            String configFilePath = config.getServletContext().getRealPath(configFile);
            //commandHandler.properties 설정파일을 파일내용 그대로 읽어옴
            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()) {
            //command 키값
            String command = (String) keyIter.next();
            //prop.getProperty(command) : 값(value)를 리턴함
            String handlerClassName = prop.getProperty(command);
            try {
                //Class.forName() : 클래스정보를 문자열(handlerClassName)로 받아서 실제클래스를 찾는다.
                Class handlerClass = Class.forName(handlerClassName);
                Object handlerInstance = handlerClass.newInstance();
                commandHandlerMap.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(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        process(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }

    private void process(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        
        String command = request.getRequestURI();
        if(command.indexOf(request.getContextPath())==0){
            //ex> substring으로 앞을짤라 hello.do 만 구해내기
            command=command.substring(request.getContextPath().length());
        }

        
        CommandHandler handler = (CommandHandler) commandHandlerMap.get(command);
        
        String viewPage = null;
        
        try {
            viewPage = handler.process(request, response);
        } catch (Throwable e) {
            throw new ServletException(e);
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
        dispatcher.forward(request, response);
    }
}

WebContent
            view (View : JSP : 출력 화면정의 : 서블릿이 액션클래스로부터받은 jsp경로를 view로 선택함 액션클래스에서        
  request로 저장해둔 결과값 출력)
  
     

bye.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Bye</title>
</head>
<body>
${bye}
</body>
</html>

                 

 hello.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
${hello}
</body>
</html>

                

  list.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>목록</title>
</head>
<body>
${list}
</body>
</html>


notice.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>뉴스</title>
</head>
<body>
${notice}
</body>
</html>



WEB-INF

                 commandHandler.properties (요청경로 설정 파일)

hello=kame.chap24.command.HelloHandler
list=kame.chap24.command.ListHandler
notice=kame.chap24.command.NoticeHandler
bye=kame.chap24.command.ByeHandler

    commandHandlerURI.properties (요청 URI경로(*.do) 설정 파일)

/hello.do=kame.chap24.command.HelloHandler
/list.do=kame.chap24.command.ListHandler
/notice.do=kame.chap24.command.NoticeHandler
/bye.do=kame.chap24.command.ByeHandler



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>mvcMain</display-name>
  
  <!-- Mapping -->
    <!-- SimpleController start -->
    <servlet>
    <servlet-name>SimpleController</servlet-name>
    <servlet-class>kame.chap24.SimpleController</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>SimpleController</servlet-name>
    <url-pattern>/simple</url-pattern>
    </servlet-mapping>
    
    <servlet>
    <servlet-name>BasicController</servlet-name>
    <servlet-class>kame.chap24.BasicController</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>BasicController</servlet-name>
    <url-pattern>/basic</url-pattern>
    </servlet-mapping>
    
    <servlet>
    <servlet-name>ControllerUsingFile</servlet-name>
    <servlet-class>kame.mvc.controller.ControllerUsingFile</servlet-class>
    <init-param>
        <param-name>configFile</param-name>
        <param-value>/WEB-INF/commandHandler.properties</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>ControllerUsingFile</servlet-name>
    <url-pattern>/controllerUsingFile</url-pattern>
    </servlet-mapping>
    
    <servlet>
    <servlet-name>ControllerUsingURI</servlet-name>
    <servlet-class>kame.mvc.controller.ControllerUsingURI</servlet-class>
    <init-param>
        <param-name>configFile</param-name>
        <param-value>/WEB-INF/commandHandlerURI.properties</param-value>
    </init-param>
    </servlet>
    <servlet-mapping>
    <servlet-name>ControllerUsingURI</servlet-name>
    <!-- 가상의 확장자 .do  -->
    <url-pattern>*.do</url-pattern>
    </servlet-mapping>    
    <!-- /Mapping -->

    <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>



실행테스트

command=hello 요청


command=list 요청


1. 파일 : properties 설정파일을 통한  command=notice 요청


2. URI : properties URI 설정파일을 통한  hello.do 요청






모델2의 진행과정

 과정1

(요청)

 웹브라우저가 전송한 HTTP 요청을 받는다. 서블릿의 doGet() 메서드나 doPost()메서드가 호출된다.

 과정2

(요구기능분석)

 웹브라우저가 어떤 기능을 요청했는지 분석한다. 예를 들어 , 게시판 목록을 요청했는지, 글쓰기를 요청했는지 알아낸다. 

 과정3

(요청 비지니스 로직을 

처리하는 모델사용)

 모델을 사용하여 요청한 기능을 수행한다.

 과정4
(결과를 request나 

session에 저장)

 모델로부터 전달받은 결과물을 알맞게 가공한 후 request의 setAttribute()메서드를 사용하여 결과값을 속서에 저장한다.  이렇게 저장된 결과값은 뷰인 JSP에서 사용된다.  (session 서부부하 때문에 많이는안씀)

 과정5
(알맞은 뷰 선택 후, 뷰로 포워딩

(또는 리다이렉트))

 웹브라우저에 보여줄 JSP를 선택한 후, 해당 JSP로 포워딩 한다. 경우에 따라서 리다이렉트 하기도 한다.



M 때고 VC : View와 Controller 연결  Model를 생략하고 하는 연습이기 때문에  Controller에서 작업처리를해준다. 


★ Servlet 사용시 중요한점 !!

1.extends Httpservlet

2.web.xml Mapping

3.모델2는 사용자에게 요청을받는 Servlet이 시작이다.





mvcMain.war




SimpleController
package kame.chap24;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleController extends HttpServlet{
    
    //1단계의 요청을 받음 
    //get 이건 post 이건  요청 다받아~ processRequest로 넘겨준다.
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        processRequest(request, response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        processRequest(request, response);
    }
    
    private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //2단계 , 요청파악
        //request 객체로부터 사용자의 요청을 파악하는 코드
        //get 이건 post 이건  요청은 이리로 오는구나
        //요기서는 type으로 값을 요청값을 받아왔구려
        String type = request.getParameter("type");
        
        //3단계, 요청한 기능을 수행한다.
        //사용자에 요청에 따라 알맞은 코드
        //가져온 값에 맞는 값을  출력해줄 코드~
        Object resultObject=null;
        if(type==null || type.equals("greeting")){
            resultObject = "안녕하세요.";            
        }else if(type.equals("date")){
            resultObject = new java.util.Date();
        }else{
            resultObject = "invalid Type";
        }
        
        //4단계, request에 처리 결과를 저장
        //결과값을 request에 담겨서 슝~
        request.setAttribute("result", resultObject);
        
        //5단계, RequestDispatcher를 사용하여 알맞은 뷰로 포워딩
        //어디로? jsp로 슝~
        RequestDispatcher dispatcher=request.getRequestDispatcher("/simpleView.jsp");
        dispatcher.forward(request, response);
        }
}
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>mvcMain</display-name>

    <!-- Mapping -->
    <!-- SimpleController start -->
    <servlet>
    <servlet-name>SimpleController</servlet-name>
    <servlet-class>kame.chap24.SimpleController</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>SimpleController</servlet-name>
    <url-pattern>/simple</url-pattern>
    </servlet-mapping>    
    <!-- /Mapping -->

    <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>
simpleView.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>뷰</title>
</head>
<body>
결과 : <%=request.getAttribute("result")%><br/>
결과 (EL:표현언어) : ${result}
</body>
</html>






ELTest02.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>EL Test</title>
</head>
<body>
<%    //메소드 , EL 두가지형태로 값을 얻을수있음
    pageContext.setAttribute("msg", "봄비");
    request.setAttribute("msg2", "여름장마");
    session.setAttribute("msg3", "가을바람");
    application.setAttribute("msg4", "겨울눈");
%>

page 영역 : <%=pageContext.getAttribute("msg") %><br/>
page 영역 (EL) : ${pageScope.msg} <br/>

request 영역 : <%=request.getAttribute("msg2") %><br/>
request 영역 (EL) : ${requestScope.msg2} <br/>

session 영역 : <%=session.getAttribute("msg3") %><br/>
session 영역 (EL) : ${sessionScope.msg3} <br/>

application 영역 : <%=application.getAttribute("msg4") %><br/>
application 영역 (EL) : ${applicationScope.msg4} <br/>

<!--
page -> request - > session -> application 순으로 뒤져서 찾아냄
page 영역 (EL) : ${msg} <br/>
request 영역 (EL) : ${msg2} <br/>
session 영역 (EL) : ${msg3} <br/>
application 영역 (EL) : ${msg4} <br/>
-->

</body>
</html>



ELTest03.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>표현언어의 사용예제2</title>
</head>
<body>
<h3> 표현 언어의 사용예제2 - 파라미터 값 처리</h3>
<br/>
<form action ="ELTest03.jsp" method="post">
이름<input type="text" name ="name" value ="${param.name}">
<input type="submit" value="확인">
</form><br/>
이름은 (request.getParameter): <%=request.getParameter("name") %> 입니다.
<br/> 
이름은 (EL) : ${param.name} 입니다.
</body>
</html>




<c:set>태그

src/kame.chap16/Membe.java
package kame.chap16;

public class Member {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }    
}

WebContent/use_c_set.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="kame.chap16.Member" %>
    <%@ page import="java.util.HashMap" %>
    <!-- 
    uri="http://java.sun.com/jsp/jstl/core" <=식별자
     식별자를통해  WEB-INF/lib/jstl-1.2.jar 로 들감
     c 식별자를 통해 jar파일에 연결 
      -->
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%
        Member member =new Member();
        HashMap<String, String> pref= new HashMap<String,String>();
    %>  
<!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>
<!-- 자바빈이 page영역에 등록 -->
<c:set var="member" value="<%=member %>"/>
<!-- 
EL이 데이터를 읽어오는것을 담당해주기때문에 꼭 알아야한다.
member의 name property에 최범균을등록
 -->
<c:set target="${member}" property="name" value="최범균" />


<!-- HashMap pref 을 page 영역에 등록 -->
<c:set var="pref" value="<%=pref %>" />
<!-- 
# : 명시만 할수있다. 데이터 없이 위치만 잡는것.
EL에서 $와 같이 사용하는 기호 : 최근에 도입 그러나 사용하지 않는게 좋음
이유:Struts에서 #을 사용하기때문에 충돌이 날수있다.
-->
<c:set var="favoriateColor" value="#{pref.color}"/>

회원 이름 : ${member.name},
좋아하는 색 : ${favoriateColor}
<br/>

<c:set target="${pref}" property="color" value="red"/>

설정 이후 좋아하는 색 :${favoriateColor}

</body>
</htm>



<c:if> 태그

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>if 태그</title>
</head>
<body>
<c:if test="true"> 항상 true. 몸체 내용을 실행함<br/> </c:if>


<c:if test="${param.name=='bk'}">
name파라미터의 값이${param.name} 입니다.<br/></c:if>

<c:if test="${18 <= param.age }">당신의 나이는 18세 이상입니다. </c:if>


</body>
</html>



http://localhost:8080/chap13/use_if_tag.jsp?name=bk&age=18



<c:choose>,<c:when>,<c:otherwise> 태그

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
<!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>choose 태그</title>
</head>
<body>
<ul>
<c:choose>    
    <!-- 순서대로 체크하며 True가 나오면 choose 문을 빠져나간다. -->
    <c:when test="${param.name=='bk'}">
    <li> 당신의 이름은 ${param.name}입니다.</li>    
    </c:when>
    <c:when test="${param.age >=20}">
    <li> 당신은 20세 이상입니다.</li>
    </c:when>
    <c:otherwise>
    <li> 당신은 'bk'가 아니고 20세 이상이 아닙니다.</li>
    </c:otherwise>
</c:choose>
</ul>
</body>
</html>


<!-- 순서대로 체크하며 True가 나오면 choose 문을 빠져나간다. -->



<c:forEach> 태그
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.HashMap" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>forEach 태그</title>
</head>
<body>
<h4>1부터 100까지 홀수의 합</h4>
<c:set var="sum" value="0"/>
<c:forEach var="i" begin="1" end="100" step="2" >
<c:set var="sum" value="${sum+i}" />
</c:forEach>
결과 =${sum}

<h4>구구단: 4단</h4>
<ul>
<c:forEach var="i" begin="1" end="9">
<li>4 * ${i} =${4*i}</li>
</c:forEach>
</ul>

<h4>int형 배열  : new int[] {1,2,3,4,5}</h4>
<c:set var="intArray" value="<%= new int[] {1,2,3,4,5} %>" />
<c:forEach var="i" items="${intArray}" begin="2" end="4" varStatus="status">
    인덱스값:${status.index}-루프실행횟수카운트:${status.count}-값[${i}] <br/>
</c:forEach>
<%
HashMap<String,Object> mapData = new HashMap<String,Object>();
mapData.put("name","최범균");
mapData.put("today",new java.util.Date());
%>
<h4>Map</h4>
<c:set var="map" value="<%=mapData %>" />
<c:forEach var="i" items="${map}">
    ${i.key}=${i.value}<br/>
</c:forEach>

</body>
</html>


<c:forTokens >태그

use_fortokens_tag.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>forTokens 태그</title>
</head>
<body>
콤마와 점을 구분자로 사용:<br>
<c:forTokens var="token" items="빨강색,주황색.노란색.초록색,파랑색,남색.보라색" delims=",.">


${token} <br/>
</c:forTokens>
</body>
</html>


<c:out >태그

use_out_tag.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.FileReader" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
</head>
<body>
<%
    FileReader reader = null;
    try{
        String path = request.getParameter("path");
        reader = new FileReader(getServletContext().getRealPath(path));
    
%>
<pre>
소스코드 = <%=path %>
<c:out value="<%=reader %>" escapeXml="true" />
</pre>
<%
    }catch(IOException ex){
%>에러:<%=ex.getMessage() %> 
<%
    }finally{//파일리더 스트림 자원해제 하기위해 트라이캐치
        if(reader !=null)
            try{reader.close();}catch(IOException ex){}        
    }
%>
</body>
</html>


<c:catch> 태그

ues_catch_tag.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>catch 태그</title>
</head>
<body>
<c:catch var="ex">

name 파라미터의 값 =<%=request.getParameter("name") %><br/>
<% if(request.getParameter("name").equals("test")){ %>
${param.name}은 test입니다.
<%} %>
</c:catch>

<p/>
<c:if test="${ex !=null}">
예외가 발생하였습니다.:<br/>
${ex}
</c:if>
</body>
</html>





모델2방식


1. 표현언어 


2. JSTL



EL(Expression Language: 표현언어) 

EL(Expression Language: 표현언어) = ${변수} => 출력이라는점은 <%= %> 와같지만 기능은 다르다.


${변수}는 
Page
request
session
application
자바빈
의 속성값을 가져올수있다.

(키, 값) Map객체에서 ${변수}는key 와 value를 읽어올수있음

<%= %> 한정적인 :  출력 객체를 생성선언하고 메소드를 사용 해서 가져옴 : 

${ } 표현식과 읽어오는 범위가 서로 다르다.

EL은 연산이 가능하다.


표현식
${2 + 5}7
${"10" + 5}15
${"십" + 5}에러발생(EL에서의 +는 연산만 연결+없음) 
EL 에서는 문자열을 자동으로 형변환시켜서 연산을 진행한다.
${null + 5}5  : EL 에서는 null 이 연산에 들어가면 0으로 치환
${4/5}0.8    : EL 에서 연산은가능하지만 원하는 값이 안나오고 다른값을 출력받을수도 있으니 
           나누기는 미리연산한뒤 출력하자
${5 div 6}0.8333333333333334     : EL 에서 연산은가능하지만 원하는 값이 안나오고 다른값을 
                                  출력받을수도 있으니 나누기는 미리연산한뒤 출력하자
${5 mod 7}5
${2 < 3}true
${2 gt 3}false
${3.1 le 3.2}true
${(5 > 3) ? 5 : 3}5
${someValue == '2011'}true (someValue는 2011로 셋팅) : 순수자바에서는 == 는 객체비교인데 
                                                EL에서는 문자비교도 == 로 가능
${empty someValue2}true (someValue2는 null)
${header["host"]}localhost:8080
${header["user-agent"]}Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.2)


수치 연산자   {   + : 덧셈 , - : 뺄셈 , * : 곱셈 , /또는 div : 나눗셈 ,  % 또는 mod :  나머지 }

비교 연산자  { == 또는 eq : ,  != 또는 ne, < 또는 lt , > 또는 gt  , <= 또는 le,  >= 또는 ge }

논리 연산자 { &&또는 and : || 또는 or : ! 또는 not }

empty 연산자 : 객체가 있느냐 null이냐,데이터가 있느냐 없느냐 두가지를 동시에 체크해준다.
(순수자바에서 if(msg !=null && !msg.equals("")) 를 한방에 처리해줌)
{ null,""빈문자열,길이가0,빈MAP,빈Collection => true 리턴   :  이외는 false 를 리턴 }

비교선택 연산자 

<수식> ? <true 값1> : <false 값2>

연산자들의 우선순위 

[].
()
- (단일) not ! empty
* / div % mod
+ -
< > <= >= it gt le ge
== != eq ne
&& and
|| or
? :


특수문자 처리하기

표현식 기본 문법 : \${expr}, \#{expr} => 출력 "${expr}, #{expr} "



표현언어의 기본(내장)객체

pageContext  : JSP의 page 기본객체와 동일하다

pageScope                     
requestScope                  각 객체에 저장된 속성의 <속성,값> 매핑을 저장한 Map객체
sessionScope
applicationScope


param  : request.getParameter(이름)  기능을 구현
param  : request.getparameterValues(이름) 와 동일

cookie  : <쿠키이름, Cookie> 매핑을 저장한 Map 객체 request.getCookies()로 구한 Cookie배열로부터 맵핑
initparam : application.getInitParameter(이름) 과 동일기능




JSTL (표준 태그 라이브러리)

 lib


jstl-1.2.jar




커스텀 태그 : 사용자생성 태그

===복습===
액션태그 : 컨테이너에서 기본 제공태그
<jsp:include />
<jsp:forward />
<jsp:useBean />
<jsp:setProperty />
<jsp:getProperty />

=========

JSP                JSTL                     JSTL+EL (커스텀태그)
                                                   (기본적으로 EL을 알고있어야 한다.)                                   
Struts                                          JSP 4개의 영역에서 EL로 뽑아낸다.                                                                             
                                                   
Spring

==========================================================================================

변수 지원 태그 

EL  => JSP 4개영역에서만 데이터를 읽어옴
JSTL => JSP 4개영역에서만 데이터를 읽어옴


<% 
        //EL은 스크립트릿 영역 변수선언 데이터를 가져오지못한다. 
        String str="행복";
        //읽어드릴려면
        pageContext.setAttribute("aaa",str);
%>


${str} => 못불러옴
${aaa} => 불러옴


<c:set /> 태그  => setAttribute (속성명, 속성값) => jsp 4개영역에 저장
   ${속성명}     => getAttribute (속성명)  => jsp 4개영역에서 값을 가져옴
<c:remove />   => removeAttribute(속성명)




흐름 제어 태그

<c:if> 태그 : 단일조건 체크만 가능하다.

항상 true. 몸체 내용을 실행함
<c:if test="true"> ...  </c:if>

항상 false. 몸체 내용을 실행하지않음
<c:if test="false"> ...  </c:if>

EL의 결과값이 true인 경우  몸체 내용을 실행함
<c:if test="${expr}"> ...  </c:if>

표현식의 결과값이 true 인 경우 몸체 내용을 실행함
<c:if test="<%=expr %>"> ...  </c:if>


<c:choose>,<c:when>,<c:otherwise> 태그
다중 조건체크 choose에서  첫번째 true 값인 when 에서 출력하고 빠져나옴

<c:forEach> 태그

확장 for문 
<c:forEach var="변수" items="아이템">
...
<tr>
     <td align="right" bgcolor="#ffffff">
   ${변수사용}
</td>
...
</c:forEach>

기본for문
<c:forEach var="i" begin="1" end="10" step="2">
${i} 사용
</c:forEach>

기본for문 + 확장for문  (index 2~4 출력)
<c:forEach var="i" items="${intArray}" begin="2" end="4">
[${i}]
</c:forEach>

<c:forEach var="i" items="<%= someItemList %>" varstatus="status">
${status.index +1} 번재 항목 : ${iteml.name}
</c:forEach>

index : 루프실행에서 현대 인덱스
count : 루프 실행 횟수
begin : begin 속성값
end :  end 속성값
step : step 속성값 = 반복증가량
first : 현재 실행이 첫번째 실행인경우 true
last : 현재 실행이 루프의 마지막 실행인 경우 true
current :  컬렉션 중 현재 루프에서 사용할 객체

<c:forTokens> 태그
StringTokenizer 기능
<c:forTokens var="token" items="빨강색,주황색.노란색.초록색,파랑색,남색.보라색" delims=",.">

<c:import> 태그
특정 URL의 결과를 읽어와 현재 위치에 삽입하거나 EL 변수에 저장할때 사용.

<c:import url="URL" [var="변수명"] [scope="영역"] [charEncoding="개릭터셋"]>

</c:import>

<c:import url="http://search.daum.net/search">

  <c:param name="nill_suggest" value="btn"/>

  <c:param name="q" value="보라매공원"/>

</c:import>


<c:url> 태그

링크가능한 주소를 만들어줌

<c:url value="URL" [var="varName"] [scope="영역"]>

   <c:param name="이름" value="값"/>

</c:url>

<c:url value="/view/list.jsp"/>


<c:redirect> 태그
<c:redirect url="URL" [context="콘텍스트경로"]>

  <c:param name="이름" value="값"/>

</c:redirect>

<c:redirect url="/use_c_set.jsp" />


//response.sendRedirect()를 많이씀

<c:out> 태그
//EL을 많이씀

 
<c:catch> 태그
<c:catch var="exName">

.. 예외가 발생할 수 있는 코드 ...

</c:catch>

...

${exName}사용


예외처리

<c:catch var="ex">
name 파라미터의 값 =<%=request.getParameter("name") %><br/>
<% if(request.getParameter("name").equals("test")){ %>
${param.name}은 test입니다.
<%} %>
</c:catch>
<p/>
<c:if test="${ex !=null}">
예외가 발생하였습니다.:<br/>
${ex}
</c:if>




국제화 태그

플러그인 설치
 jp.gr.java_conf.ussiy.app.propedit_4.8.1_for_eclipse3.0.zipD:\javaWork\eclipse

features,plugins 덮어쓰기



한글로 입력해도 유니코드로 저장된다.


message.properties

TITLE = MadVirus's Learning JSP 2.0
GREETING = HI! I'm BK
VISITOR = Your ID is {0}.

message_ko.properties

TITLE = 최범균의 JSP 2.0 배우기
GREETING = 안녕하세요. 최범균입니다.
VISITOR = 당신의 아이디는 {0}입니다.

파일로저장될때는  유니코드로 자동 변경

TITLE = \ucd5c\ubc94\uade0\uc758 JSP 2.0 \ubc30\uc6b0\uae30
GREETING = \uc548\ub155\ud558\uc138\uc694. \ucd5c\ubc94\uade0\uc785\ub2c8\ub2e4.
VISITOR = \ub2f9\uc2e0\uc758 \uc544\uc774\ub514\ub294 {0}\uc785\ub2c8\ub2e4.

<fmt:setBundle> 태그와 <fmt:message> 태그
use_message_tag.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!-- 강제로 지역값 설정(영문) -->
<%-- <fmt:setLocale values="en"/> --%>
<fmt:bundle basename="resource.message">
<!-- 가져와서 변수에 넣음  -->
<fmt:message key="TITLE" var="title"/>
<!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}</title>
</head>
<body>
<!-- 가져와서 변수가없으니 바로 출력 -->
<fmt:message key="GREETING" />
<br/>
<c:if test="${! empty param.id}">
<fmt:message key="VISITOR">
    <fmt:param value="${param.id}" />
</fmt:message>
</c:if>
</body>
</html>
</fmt:bundle>


지역 미국 영어로 바꾸기

자동으로 영문화




<fmt:formatNumber> 태그

http://www.servlets.com/



cos-26Dec2008.zip


 

 

파일업로드는 Post방식으로만 가능하다 
Get 방식 불가능

Http 요청 메시지
header : get방식: http://localhost:8080/chap13/index.jsp?파일주소 << 정말 파일의 위치주소만 전송된다.
body

form  enctype="multipart/form-data" 명시를 해야 파일데이터라고 인식을함.
input type="file" 

파일을 첨부해서 보낸경우 request.getParameter(무력화당함..) 로 추출을못함. => 통체로 MultipartRequest 에 넘겸줌
WEB-INF/lib/cos.jar 
cos라이브러리는 동시에 여러 파일을 올리수있다.
maxSize : 모든파일의 합의 제한용량


WEB-INF/fileSelect.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>파일 업로드 예제</title>
</head>
<body>
<!-- 
method="post" : get방식은 파일업로드 못함
enctype="multipart/form-data" : 파일업로드시 반드시 명시
type="file" : 선택파일을 매치시켜 파일을 업로드 
-->
<form name="fimeForm" method="post" enctype="multipart/form-data" action="fileUpload.jsp">
작성자: <input type="text" name="user"><br/>
제목:<input type="text" name="title"><br/>
파일명:<input type="file" name="uploadFile"><br/>
파일명2:<input type="file" name="uploadFile2"><br/>
<input type="submit" value="파일 올리기"><br/>
</form>
</body>
</html>
WEB-INF/fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<!-- 
MultipartRequest : 
DefaultFileRenamePolicy : 기존에 업로드 파일중 이름이 똑같은것이 있는경우  업로드시 이름을 변경해주는것 ex)a.jsp,a1.jsp
 -->
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>

<%
    String realFolder = ""; //웹 어플레케이션상의  절대경로

    //파일이 업로드되는 폴더를 지정한다
    String saveFolder = "upload";
    String encType = "utf-8";///엔코딩타입
    int maxSize = 5 * 1024 * 1024;//최대 업로드될 파일크기 5mb

    ServletContext context = getServletContext();
    //현재 jsp 페이지의 웹어플리케이션상의 절대 경로를 구한다.
    realFolder = context.getRealPath(saveFolder);
    out.println("the realpath is: " + realFolder + "<br/>");

    try {
        MultipartRequest multi = null;

        //전송을 담당할 콘포넌트를 생성하고 파일을 전송한다.
        //전송할 파일명을 가지고 있는 객체, 서버상의 절대경로, 최대 업로드될 파일크기
        /*
        MultipartRequest(
                request, :    요청request를 통채로 넘겨줌 
                realFolder, : 웹어플리케이션상의 절대경로
                maxSize, : 최대용량
                encType, : 파일타입
                new DefaultFileRenamePolicy() :같은파일명이있는경우 이름변경
        */
        multi = new MultipartRequest(request, realFolder, maxSize, encType, new DefaultFileRenamePolicy());
        
        //Form의 파라미터 목록을 가져온다. 
        //getParameterNames: 파일과 관련없는 일반정보인 경우 추출방법
        //Enumeration : java.util : 데이터를 여러개 보관할수 있는객체 
        Enumeration params = multi.getParameterNames();

        //파라미터를 출력한다.
        while (params.hasMoreElements()) {
            //전송되는 파라미터이름
            String name = (String) params.nextElement();
            //전송되는 파라미터값
            String value = multi.getParameter(name);

            out.println(name + "=" + value + "<br>");

        }
        out.println("----------------------------------------------<br/>");

        //전송할 파일 정보를 가져와 출력한다.
        //getFileNames : 파일과 관련있는 정보인 경우의 추출방법
        Enumeration files = multi.getFileNames();

        //파일 정보가 있다면
        while (files.hasMoreElements()) {

            //input태그 속성이 file 인 태그의 name속성값 : 파라미터 이름
            String name = (String) files.nextElement();

            //서버에 저장된 파일 이름
            String filename = multi.getFilesystemName(name);

            //전송전 원래의 파일이름
            String original = multi.getOriginalFileName(name);

            //전송된 파일의 내용타입
            String type = multi.getContentType(name);

            //전송된 파일 속성이  file인 태그의 name 속성값을 이용해 파일 객체 생성
            //용량을 알아내기 위해서 : file.length();
            File file = multi.getFile(name);

            out.println("파라미터 이름 : " + name + "<br/>");
            out.println("실제 파일 이름 : " + original + "<br/>");
            out.println("저장된 파일 이름 : " + filename + "<br/>");
            out.println("파일 타입 : " + type + "<br/>");

            if (file != null) {
                out.println("크기 : " + file.length());
                out.println("<br/>");
            }
        }
    } catch (IOException ioe) {
        System.out.println(ioe);
    } catch (Exception ex) {
        System.out.println(ex);
    }
%>



다중업로드

방명록



create table guestbook(
num number primary key,
register date NOT NULL,
name varchar2(20) NOT NULL,
email varchar2(40),
passwd varchar2(10) NOT NULL,
content varchar2(4000) NOT NULL);

create sequence guestbook_seq;



글번호 num


insert into GUESTBOOK (num,register,name,email,passwd,content) values(guestbook_seq.nextval,?,?,?,?,?)


오라클 sequence guestbook_seq.curval 현재번호

          sequence guestbook_seq.nextval 다음번호


테이블작성




select * from(
       //시스템에서 제공하는 행번호 rownum의 별칭 rnum : 명시적 행번호 호출
       //a.* =  num,register,name,email,.... a아래있는 모든 컬럼이다. (a: 테이블에 대한 별칭)
select a.*, rownum rnum 
from(
//서브쿼리
select * 
from GUESTBOOK
order by num desc
)a//테이블 별칭
) where rnum >=1 and rnum <=10  //행번호 1~10 까지



모델1:


guestbook

              com.guestbook.domain

                                             Guestbook.java

              com.guestbook.dao

                                             GuestbookDao.java


WebContent

             docs

                   guestbook.spl

             view

                   delete.jsp

                   deleteForm.jsp

                   list.jsp

                   update.jsp

                   updateForm.jsp                  

                   write.jsp

                   writeForm.jsp

             META-INF

                   context.xml

             WEB-INF

                    lib

                        jar파일 3개 (commons-collections-3.1.jar,commons-dbcp-1.2.1.jar,commons-pool-1.2.jar)


 guestbook.war




제작페턴!!!!

1. 목록 (ArrayList+ 자바빈[레코드])

2. 상세정보 (자바빈, ex> select * from guestbook value num=? )

3. insert

4. update (1. 인증 2. update)
   delete (1. 인증 2. delete)

=============================================================

모델 1. 방식
1. Oracle [JDBC Driver]
2. 경로 1 JDK/jre/lib/ext/ojdbc14.jar
    경로 2 Tomcat/lib/ojdbc14.jar
    경로 3 Project/WebContet/WEB-INF/lib/ojdbc.jar
3. DB설계 (Table 생성)  ex>회원 관리,방명록
4. 자바빈을 만들고 (컬럼명과 일치시켜주는것이 좋다.)
    DAO(Data Acess Object 를 만든다. (DB 연동)


1. 목록
2. 생성  
3. insert
4. select,ArrayList, upload ,delete, 인증



자바빈 src/com.guestbook.domain/Guestbook.java
package com.guestbook.domain;

import java.sql.Timestamp;

public class Guestbook {
    
    private int num;
    private Timestamp register;
    private String name;
    private String email;
    private String passwd;
    private String content;
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public Timestamp getRegister() {
        return register;
    }
    public void setRegister(Timestamp register) {
        this.register = register;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}


DAO src/com.guestbook.domain/Guestbook.java
package com.guestbook.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.guestbook.domain.Guestbook;

public class GuestbookDao {
  private static GuestbookDao instance =new GuestbookDao();
    
    public static GuestbookDao getInstance(){
        return instance;
    }
    private GuestbookDao(){}
    
    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 insert(Guestbook book) throws Exception{
        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql="";
        //바인드문자 ?의 순서
        int cnt = 0;        
        
        try{
            conn= getConnection();
            sql = "insert into GUESTBOOK (num,register,name,email,passwd,content) " +
                    "values(guestbook_seq.nextval,?,?,?,?,?)";
            //sql ="insert into GUESTBOOK values(guestbook_seq.nextval,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(++cnt, book.getRegister());
            pstmt.setString(++cnt, book.getName());
            pstmt.setString(++cnt, book.getEmail());
            pstmt.setString(++cnt, book.getPasswd());
            pstmt.setString(++cnt, book.getContent());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //글의 총갯수
    public int getCount() throws Exception{
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        int count =0;
        String sql =null;
        
        try{
            conn=getConnection();
            // 갯수를 구하는 sql 함수 count(*) :레코드의 총수는
            sql="select count(*) from GUESTBOOK";
            pstmt =conn.prepareStatement(sql);
            rs =pstmt.executeQuery();
            if (rs.next()){
                //1: 컬럼의 순서 (가상의 컬럼 count(*))
                //getInt(count(*))도 가능
                count =rs.getInt(1);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }            
        return count;
    }
    
    //글 목록 
    public List<Guestbook> getList(int startRow, int endRow)throws Exception{
        
        Connection conn= null;
        PreparedStatement pstmt =null;
        ResultSet rs= null;
        List<Guestbook>list =null;
        String sql="";
        
        try{
            conn =getConnection();
            //새글이 위로 올라오게 내림차순
            //sql ="select * from GUESTBOOK order by num desc";
            // select(select 서브쿼리)
            sql ="select * from(select a.*, rownum rnum from(select * from GUESTBOOK order by num desc)a) where rnum >=? and rnum <=?";
            pstmt =conn.prepareStatement(sql);
            
            pstmt.setInt(1, startRow);
            pstmt.setInt(2, endRow);
            
            //sql문 반영
            rs=pstmt.executeQuery();
            
            //데이터가 있는가없는가 확인
            if(rs.next()){
                //있으면
                list= new ArrayList<Guestbook>();
                //if문에서 이미 커서가 첫번째 행을 가리키기 때문에 첫번째 행 부터 뽑기위해 do while 문
                do{
                    Guestbook book =new Guestbook();
                    book.setNum(rs.getInt("num"));
                    book.setRegister(rs.getTimestamp("register"));
                    book.setName(rs.getString("name"));
                    book.setEmail(rs.getString("email"));
                    book.setPasswd(rs.getString("passwd"));
                    book.setContent(rs.getString("content"));
                    list.add(book);
                }while(rs.next());
            }else{
                //없으면
                //데이터가 없는 경우 비어있는 List 생성
                list = Collections.EMPTY_LIST;
            }            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return list;
    }
    
    //수정 폼에 보여질 한건의 레코드 정보
    public Guestbook getGuestBook(int num)throws Exception{
        Connection conn =null;
        PreparedStatement  pstmt= null;
        ResultSet rs = null;
        Guestbook book=null;
        String sql=null;
        
        try{
            conn=getConnection();
            sql ="select * from GUESTBOOK where num = ? ";
            
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                book=new Guestbook();
                book.setNum(rs.getInt("num"));
                book.setRegister(rs.getTimestamp("register"));
                book.setName(rs.getString("name"));
                book.setEmail(rs.getString("email"));
                book.setPasswd(rs.getString("passwd"));
                book.setContent(rs.getString("content"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return book;
    }
    
    //인증
    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 GUESTBOOK 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;
    }
    
    //글수정
    public void update(Guestbook book)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        int cnt =0;
        String sql = null;
        
        try{
            conn =getConnection();
            sql = "update GUESTBOOK set name=?,email=?, content=? where num=?";
            pstmt =conn.prepareStatement(sql);
            
            pstmt.setString(++cnt, book.getName());
            pstmt.setString(++cnt, book.getEmail());
            pstmt.setString(++cnt, book.getContent());    
            pstmt.setInt(++cnt, book.getNum());
            
            pstmt.executeUpdate();
            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }        
    }
    
    //글삭제
    public void delete(int num)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt=null;
        String sql=null;        
        
        try{            
            conn= getConnection();
            
            sql="delete from GUESTBOOK where num=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            pstmt.executeUpdate();

        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }        
        return ;
    }    
    
    //자원정리
    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){}
    }    
}




WebContent/view/deleteForm.jsp
<%@ page contentType = "text/html; charset=euc-kr" %>
<%@ page import = "com.guestbook.dao.GuestbookDao" %>
<%@ page import = "com.guestbook.domain.Guestbook" %>
<%
    int num = Integer.parseInt(request.getParameter("num"));
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>글삭제</title></head>
<body>
<form action="delete.jsp" method="post">
<input type="hidden" name="num" value="<%= num %>">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td>암호</td>
    <td><input type="password" name="passwd" size="10"><br>
    글을 쓸때 입력한 암호와 동일해야 글이 삭제됩니다.</td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글삭제하기"></td>
</tr>
</table>
</form>
</body>
</html>

WebContent/view/delete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>    
<%@ page import = "com.guestbook.dao.GuestbookDao" %>
<%@ page import = "com.guestbook.domain.Guestbook" %>
<%
    request.setCharacterEncoding("utf-8");
    int num =Integer.parseInt(request.getParameter("num"));
    String passwd =request.getParameter("passwd");
    
    GuestbookDao manager =GuestbookDao.getInstance();
    int check =manager.userCheck(num,passwd);
    
    if(check ==1){
        manager.delete(num);
%>
<script type="text/javascript">
alert("글을 삭제하였습니다.");
location.href ="list.jsp";
</script>
<%
    }else{
%>
<script type="text/javascript">
alert("암호가 다릅니다.");
history.go(-1);
</script>
<%
    }
%>    


WebContent/view/list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="com.guestbook.dao.GuestbookDao" %>   
<%@ page import ="com.guestbook.domain.Guestbook" %>   
<%@ page import ="java.util.List" %>   
<%@ page import ="java.text.SimpleDateFormat" %>
<%! //pageSize: 페이지당 출력되는 글의 갯수를 조정할 값
    int pageSize =1;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
%>    


<%  //getparameter("String"):pageNum 누르는 페이지번호
    String pageNum =request.getParameter("pageNum");
    if (pageNum ==null){
        pageNum ="1";
    }

    //String => Int
    int currentPage=Integer.parseInt(pageNum);
    //맨앞번호 1페이지면 1, 2페이지면 11 ,...
    int startRow = (currentPage -1)*pageSize+1;
    //맨뒷번호  1페이지면 10, 2페이지면 20 ,...
    int endRow = currentPage * pageSize;
    int count =0;
    
    List<Guestbook> bookList =null;
    GuestbookDao manager =GuestbookDao.getInstance();
    count =manager.getCount();
      
    if(count >0){
        bookList = manager.getList(startRow, endRow);
    }
%>    
<!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>
</head>
<body>
<table width="100%">
    <tr><td>
    <a href ="writeForm.jsp">글쓰기</a>
    </td></tr>
</table>
<%
    if(count==0){
%>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td bgcolor ="e9e9e9">방명록에 글이 없습니다.</td>
</tr>
</table>
<%
    }else{
%>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<!-- 목록 출력시작  -->
<% 
    for (int i=0;i<bookList.size();i++){
        Guestbook book = bookList.get(i);
%>     
<tr>
    <td bgcolor ="#e9e9e9">
    <b><%=book.getName()%>(<%=(book.getEmail()==null)?"":book.getEmail() %>)</b>
    
    -<font size="2">
    <%=formatter.format(book.getRegister()) %>
    <a href="updateForm.jsp?num=<%=book.getNum() %>">[수정]</a>
    <a href="deleteForm.jsp?num=<%=book.getNum() %>">[삭제]</a>        
    </font>
    
    </td>
    </tr>
    <tr>
    <td><%=book.getContent() %></td>
    </tr>
<% }%>        
<!-- 목록 출력 끝 -->
</table>
<% }%> 
<!-- 페이징 처리 시작  -->
<div align="center">
<%
    if(count > 0){
        //pageBlock : 페이지 번호가 보여지는 구간의 갯수의값
        int pageBlock =10;
    
        //pageCount: 전체페이지의 숫
        int pageCount = (count -1) / pageSize +1;
        //startPage : pageBlock 첫번호
        int startPage =((currentPage -1 )/pageBlock)* pageBlock+1;
        //endPage : pageBlock 마지막번호
        int endPage = startPage +pageBlock -1;
        
        //예측 예외처리
        if(endPage> pageCount) endPage = pageCount;
        
        //
        if (startPage>pageBlock){ 
            %>
                <a href="list.jsp?pageNum=<%=startPage -1 %>">[이전]</a>
            <%}
                for(int i=startPage ; i <=endPage ; i++){
                    //현재페이지인경우만 링크안걸기
                    if(i==currentPage){
            %>
                <font size = "2" color ="#666666">[<%=i %>]</font>
            <%    }else{ %>
                <a href="list.jsp?pageNum=<%=i %>">[<%=i %>]</a>
            <% }}
                //PageBlock의 마지막보다 전체페이지 숫자가 큰경우 :남은 글이 있는경우 다음을 표기.
                if(endPage<pageCount){
            %>
                <a href="list.jsp?pageNum=<%=startPage+pageBlock %>">[다음]</a>
    <%    }}  %>
</div>
<!-- 페이징 처리 끝-->
</body>
</html>


WebContent/view/update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="com.guestbook.dao.GuestbookDao" %>   
<%@ page import ="com.guestbook.domain.Guestbook" %>   
<%@ pate import ="java.sql.Timestamp" %>
<%
    request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="book" class="com.guestbook.domain.Guestbook">
    <jsp:setProperty name="book" property="*"/>
</jsp:useBean>
<%
    GuestbookDao manager=GuestbookDao.getInstance();
    int check = manager.userCheck(book.getNum(),book.getPasswd());
    
    if(check==1){
        manager.update(book);
%>
<<script type="text/javascript">
alert("글을 수정하였습니다.")
location.href ="list.jsp";
</script>      
<%    
    }else{
%>
<<script type="text/javascript">
alert("암호가 다릅니다.");
history.go(-1);
</script>
<%    
    }
%>

WebContent/view/updateForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="com.guestbook.dao.GuestbookDao" %>   
<%@ page import ="com.guestbook.domain.Guestbook" %>   
<%
    int num = Integer.parseInt(request.getParameter("num"));
    GuestbookDao manager = GuestbookDao.getInstance();
    Guestbook book = manager.getGuestBook(num);
    if(book.getEmail()==null){
        book.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.name.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="update.jsp" method="post"  name="userinput"  onSubmit="return checkIt()">  
<input type="hidden" name="num" value="<%=num%>">
<table width ="100%" border ="1" cellpadding="0" cellspacing="0">

<tr>
    <td>암호</td>
    <td><input type="password" name ="passwd" size="10"><br/>
    글을 쓸때 입력한 암호와 동일해야 글이 수정됩니다.</td>
</tr>

<tr>
    <td>이름</td>
    <td><input type="text" name="name" value="<%=book.getName() %>" size="10"></td>
</tr>

<tr>
    <td>이메일</td>
    <td><input type="text" name="email" value="<%=book.getEmail() %>" size="10"></td>
</tr>

<tr>
    <td>내용</td>
    <td><textarea name="content" rows="5" cols="50"><%=book.getContent() %></textarea></td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글수정하기"></td>
</tr>
</table>    
</form>  
</body>
</html>

WebContent/view/write.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import = "com.guestbook.dao.GuestbookDao" %> <%@ page import = "java.sql.Timestamp" %> <% request.setCharacterEncoding("utf-8"); %> <jsp:useBean id="book" class="com.guestbook.domain.Guestbook"> <jsp:setProperty name="book" property="*"/> </jsp:useBean> <% book.setRegister(new Timestamp(System.currentTimeMillis())); GuestbookDao manager = GuestbookDao.getInstance(); manager.insert(book); %> <script type="text/javaScript"> alert("방명록에 글을 등록하였습니다."); location.href="list.jsp"; </script>


WebContent/view/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 checkIt() {
        var user = document.userinput;
               
        if(!user.name.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;
        }
       return true;
    }
//-->
</script>
</head>
<body>
<center>
<form name="userinput" action="write.jsp" method="post" onsubmit="return checkIt()">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
    <td>이름</td>
    <td><input type="text" name="name" size="10"></td>
</tr>
<tr>
    <td>암호</td>
    <td><input type="password" name="passwd" size="10"></td>
</tr>
<tr>
    <td>이메일</td>
    <td><input type="text" name="email" size="30"></td>
</tr>
<tr>
    <td>내용</td>
    <td><textarea name="content" rows="5" cols="50"></textarea></td>
</tr>
<tr>
    <td colspan="2"><input type="submit" value="글남기기"></td>
</tr>
</table>
</form>
</center>
</body>
</html>




글쓰기 테스트


writeForm.jsp




List 확인 :  list.jsp



글수정하기 테스트

updateForm.jsp



update.jsp


암호가 다를경우

암호가 맞을경우

list.jsp



삭제테스트



페이징 테스트

list.jsp



※실무에서도 DAO와 자바빈은 무조건 생성하게 된다. 중요하다.





member.war




테이블 생성
create table member(
id varchar2(12) primary key,
passwd varchar2(12) NOT NULL,
name varchar2(10) NOT NULL,
jumin1 varchar2(6) NOT NULL,
jumin2 varchar2(7) NOT NULL,
email varchar2(30),
blog varchar2(50),
reg_date date NOT NULL);




Java Resources/src/com.dao/MemberDao.java

package com.dao;

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

import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;

import com.domain.Member;

public class MemberDao {
    
        
/*    @싱글턴 패턴
    생성자의 접근지정자는 private으로 지정
    static한 getInstance()를  메소드를 사용
    객체의 주소를 보관하는 static 참조변수 사용 
    //참조변수 instance에 객체 주소할당
    //객체를 한번생성해서 계속가지고있슴 (변경에관한게 아무것도없슴)
    객체를 하나만 생성해서 공유하고자 싱글턴 패턴 구현
    @멤버변수가 있는 경우에는 절대로 싱글턴 패턴을 구현하면 안된다.
    //멤버변수를 공유시켜버리면 여러사용자가 멤버변수를 같이 변경하게됨    */
    private static MemberDao instance =new MemberDao();
    
    public static MemberDao getInstance(){
        return instance;
    }

    //생성자 인데 private 외부에서는 생성못하게 막아둔거
    //메소드를 static 하게만들어  메서드를  이용해서 
    //Member.getInstance();
    private MemberDao(){
    }
    
    //커네션풀로 부터 커넥션을 할당 받는 메소드
    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 insertMember(Member member)throws Exception{
        Connection conn= null;
        PreparedStatement pstmt = null;
        String sql="";
        int cnt = 0;
        
        try{
            //커넥션 풀로 부터 커넥션 할당
            conn= getConnection();
            sql ="insert into MEMBER values(?,?,?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getId());
            pstmt.setString(++cnt, member.getPasswd());
            pstmt.setString(++cnt, member.getName());
            pstmt.setString(++cnt, member.getJumin1());
            pstmt.setString(++cnt, member.getJumin2());
            pstmt.setString(++cnt, member.getEmail());
            pstmt.setString(++cnt, member.getBlog());
            pstmt.setTimestamp(++cnt, member.getReg_date());
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //회원 아이디 , 비밀번호 체크
    public int userCheck(String id, String passwd)throws Exception{
        
        Connection conn= null;
        PreparedStatement pstmt = null;
        ResultSet rs =null;
        String sql="";
        String dbpasswd="";
        int x = -1;
        
        try{
            conn =getConnection();
            sql ="select passwd from MEMBER where id = ?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                dbpasswd =rs.getString("passwd");
                if(dbpasswd.equals(passwd))
                    x=1; //인증성공
                else
                    x=0; //비밀번호 틀림
            }else
                x=-1; //해당 아이디 없음
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return x;
    }
    
    //회원 상세정보 
    public Member getMember(String id)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Member member=null;
        String sql="";
        try{
            conn=getConnection();
            sql="select * from MEMBER where id= ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs= pstmt.executeQuery();
            
            if(rs.next()){
                member=new Member();
                member.setId(rs.getString("id"));
                member.setPasswd(rs.getString("passwd"));
                member.setName(rs.getString("name"));
                member.setJumin1(rs.getString("jumin1"));
                member.setJumin2(rs.getString("jumin2"));
                member.setEmail(rs.getString("email"));
                member.setBlog(rs.getString("blog"));
                member.setReg_date(rs.getTimestamp("reg_date"));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }
        return member;
    }
    
    //회원정보 수정
    public void updateMember(Member member)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        int cnt =0;
        try{
            conn =getConnection();
            sql = "update MEMBER set passwd=?,name=?,email=?, blog=? where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(++cnt, member.getPasswd());
            pstmt.setString(++cnt, member.getName());
            pstmt.setString(++cnt, member.getEmail());
            pstmt.setString(++cnt, member.getBlog());
            pstmt.setString(++cnt, member.getId());
            
            pstmt.executeUpdate();
            
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }   
    
    //회원탈퇴 , 회원정보 삭제
    public void deleteMember(String id)throws Exception{
        Connection conn=null;
        PreparedStatement pstmt =null;
        String sql = null;
        try{
            conn =getConnection();
            sql = "delete from MEMBER where id=?";
            pstmt =conn.prepareStatement(sql);
            pstmt.setString(1, id);
            pstmt.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            execClose(null,pstmt,conn);
        }
    }
    
    //ID 중복 체크
    public int confirmId(String id)throws Exception{
        Connection conn =null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql="";
        int x=-1;
        try{
            conn=getConnection();
            sql="select * from MEMBER where id= ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs= pstmt.executeQuery();    
            
            if(rs.next())
                x=1; //해당아이디 있음
            else
                x=-1;//해당아이디 없음
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            execClose(rs,pstmt,conn);
        }        
        return x;
    }
    
    //자원 정리를 위한 메소드
    //계란노른자
    //Connection 를통해서 PreparedStatement 를생성하고 
    //PreparedStatement 를 통해서 ResultSet 를 생성하기때문에
    //종료할때는 ResultSet=>PreparedStatement=>Connection 와같이 생성순서의 역순으로 close 해줘야한다
    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){}
    }
}

Java Resources/src/com.domain/Member.java

자바빈 : getter setter 이클립스 기능으로 생성

package com.domain;
import java.sql.Timestamp;

//자바빈
public class Member {
    //프로퍼티
    private String id;
    private String passwd;
    private String name;
    private String jumin1;
    private String jumin2;
    private String email;
    private String blog;
    private Timestamp reg_date;
    
    //getter
    public String getId() {
        return id;
    }
    //setter
    public void setId(String id) {
        this.id = id;
    }
    public String getPasswd() {
        return passwd;
    }
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJumin1() {
        return jumin1;
    }
    public void setJumin1(String jumin1) {
        this.jumin1 = jumin1;
    }
    public String getJumin2() {
        return jumin2;
    }
    public void setJumin2(String jumin2) {
        this.jumin2 = jumin2;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getBlog() {
        return blog;
    }
    public void setBlog(String blog) {
        this.blog = blog;
    }
    public Timestamp getReg_date() {
        return reg_date;
    }
    public void setReg_date(Timestamp reg_date) {
        this.reg_date = reg_date;
    }
    
    @Override
    public String toString() {
        return "Member [id=" + id + ", passwd=" + passwd + ", name=" + name
                + ", jumin1=" + jumin1 + ", jumin2=" + jumin2 + ", email="
                + email + ", blog=" + blog + ", reg_date=" + reg_date + "]";
    }    
}


WebContent/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>

WebContent/view/confirmId.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "com.dao.MemberDao" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>ID 중복확인</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<%
    request.setCharacterEncoding("utf-8");

    String id = request.getParameter("id");
    MemberDao manager = MemberDao.getInstance();
    int check= manager.confirmId(id);
%>
<body>
<%
    if(check == 1) {
%>
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr> 
    <td height="39" ><%=id%>이미 사용중인 아이디입니다.</td>
  </tr>
</table>
<form name="checkForm" method="post" action="confirmId.jsp">
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <td align="center"> 
       다른 아이디를 선택하세요.<p>
       <input type="text" size="10" maxlength="12" name="id"> 
       <input type="submit" value="ID중복확인">
    </td>
  </tr>
</table>
</form>
<%
    } else {
%>
<table width="270" border="0" cellspacing="0" cellpadding="5">
  <tr> 
    <td align="center"> 
      <p>입력하신 <%=id%> 는 사용하실 수 있는 ID입니다. </p>
      <input type="button" value="닫기" onclick="setid()">
    </td>
  </tr>
</table>
<%
    }
%>
</body>
</html>
<script type="text/javascript">
<!--
  function setid()
    {        
        opener.document.userinput.id.value="<%=id%>";
        self.close();
        }
//-->
</script>

WebContent/view/deletePro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% 
   if(session.getAttribute("memId") == null){
       response.sendRedirect("main.jsp");
   }else{
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>회원탈퇴</title>
</head>
<body>
<form name="myform" action="deletePro.jsp" method="post">
아이디 : <input type=password name="id"  size="15" maxlength="12"><br/>
비밀번호 : <input type=password name="passwd"  size="15" maxlength="12"><br/>
      
<input type=submit value="회원탈퇴"> 
<input type="button" value="취  소" onclick="location.href='main.jsp'">
</form>
</body>
</html>
<%}%>

WebContent/view/deleteForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="com.dao.MemberDao" %>
<% //로그인이 되었이어야  보여지도록 검증
    if(session.getAttribute("memId")==null){
        response.sendRedirect("main.jsp");
    }else{
%>  
<%
    String id =request.getParameter("id");
    String passwd = request.getParameter("passwd");
    
    MemberDao manager = MemberDao.getInstance();
    int check= manager.userCheck(id, passwd);
    
    if(check==1){
        manager.deleteMember(id);
        session.invalidate();        
%>      
<!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>
</head>
<body>
<h4>회원 정보 삭제</h4>
<div align="center">
회원정보가 삭제되었습니다.<br/>
<input type= "button" value="확인" onClick="location.href='main.jsp'">
</div>
</body>
</html>
<%}else{%>
    <!-- 무엇이 틀렸는지 안알려준다  보안! -->
    <script>
        alert("id 또는 비밀번호가 맞지 않습니다.");
        history.go(-1);
    </script>
<%}}%>



WebContent/view/inputForm.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>회원가입</title>

<script type="text/javascript">
/* 하나라도 걸리면 경고창과 포커스를 처리한후 false를  반환한다.  */
    function checkIt(){    
        var userinput=document.userinput;
        if(!userinput.id.value){
            alert("ID를 입력하세요");
            userinput.id.focus();
            return false;
        }
        if(!userinput.passwd.value){
            alert("비밀번호를 입력하세요");
            userinput.passwd.focus();
            return false;
        }
        /*     if(userinput.passwd.value != userinput.passwd2.value){
            alert("비밀번호를 동일하게 입력하세요");
            userinput.passwd2.focus();
            return false;
        } 우리는 비번한개*/
        if(!userinput.name.value){
            alert("사용자 이름을 입력하세요");
            userinput.name.focus();
            return false;
        }
        if(!userinput.jumin1.value){
            alert("주민등록번호를 입력하세요");
            userinput.jumin1.focus();
            return false;
        }
        if(!userinput.jumin2.value){
            alert("주민등록번호를 입력하세요");
            userinput.jumin2.focus();
            return false;
        }
        return true;
    }
    //아이디 중복 여부를 판단
    function openConfirmid(userinput){
        //아이디를 입력했는지 검사
        if(userinput.id.value==""){
            alert("아이디를입력하세요");
            userinput.id.focus();
            return;
        }
        //url과 사용자 입력 id를 조합합니다.
        url="confirmId.jsp?id="+userinput.id.value;
        
        //새로운 윈도우를 엽니다.
        open(url,"confirm","toolbar=no,location=no,status=no,menubar=no,scrllbar=no,resizable=no,width=300,height=200");
    }
</script>
</head>
<body>
<table align="center">
<tr><td>
<!-- 
onSubmit="return checkIt()"  : checkIt() 리턴값이 true면  Submit을 실행
                                                 false면 실행안함(자바스크립트에서경고창 포커스처리)
-->
<form method="post" action="inputPro.jsp" name="userinput" onSubmit="return checkIt()">
사용자 ID : <input type="text" name ="id" size="10" maxlength="12">
    <input type="button" name="confirm_id" value="ID중복확인" onClick="openConfirmid(this.form)"><br/>
비밀번호 : <input type="password" name ="passwd" size="15" maxlength="12"><br/>
사용자이름 : <input type="text" name ="name" size="15" maxlength="10"><br/>
주민등록번호 : <input type="text" name ="jumin1" size="7" maxlength="6">
            - <input type="text" name ="jumin2" size="7" maxlength="7"><br/>
E-Mail : <input type="text" name ="email" size="40" maxlength="30"><br/>
Blog : <input type="text" name ="blog" size="60" maxlength="50"><br/>
<input type="submit" value="등   록">
<input type="reset" value="다시 입력">
</form>
</td></tr>
</table>
</body>
</html>

WebContent/view/inputPro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="com.dao.MemberDao" %>
<%@ page import ="java.sql.Timestamp" %>
    
<%
    request.setCharacterEncoding("utf-8");
%>  

<jsp:useBean id="member" class="com.domain.Member">
    <jsp:setProperty name ="member" property="*"/> 
</jsp:useBean>

<%
    member.setReg_date(new Timestamp(System.currentTimeMillis()));
    MemberDao manager = MemberDao.getInstance();
    manager.insertMember(member);
%>      
<script>
alert("축하");
location.href="main.jsp";
</script>  


WebContent/view/login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% //로그인이 되었이어야  보여지도록 검증
   if(session.getAttribute("memId") == null){
       response.sendRedirect("main.jsp");
   }else{
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>메인입니다..</title>
</head>
<body>
       <table width="500" cellpadding="0" cellspacing="0"  align="center" border="1" >
         <tr>
           <td width="300" height="20">하하하</td>

           <td rowspan="3" align="center">
             <%=session.getAttribute("memId")%>님이 <br>
             방문하셨습니다
             <form  method="post" action="logout.jsp">  
             <input type="submit"  value="로그아웃">
        <!-- javascript:window.location='modifyForm.jsp' => location.href-->
             <input type="button" value="회원정보변경" onclick="location.href='modifyForm.jsp'">
             <input type="button" value="회원탈퇴" onclick="location.href='deleteForm.jsp'">
             </form>
         </td>
        </tr>
       <tr > 
         <td rowspan="2" width="300" >메인입니다.</td>
      </tr>
     </table>
 </body>
</html>
<%}%>

WebContent/view/loginForm.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>
</head>
<body>
<h3>회원로그인</h3>
<form action="loginPro.jsp" method="post">
 아이디 : <input type="text" name="id" size="15" maxlength="12"><br/>
비밀번호 : <input type="password" name="passwd"  size="15" maxlength="12"><br/>
<input type=submit value="로그인"> 
<input type=reset value="다시입력">
<input type="button" value="회원가입" onclick="location.href='inputForm.jsp'">
</form>
</body>
</html>

WebContent/view/loginPro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="com.dao.MemberDao" %>
    
<%
    request.setCharacterEncoding("utf-8");

    String id =request.getParameter("id");
    String passwd =request.getParameter("passwd");
    
    MemberDao manager =MemberDao.getInstance();
    int check=manager.userCheck(id, passwd);
    
    //userCheck에서 x를 return 받아서 로긴체크 
    //history.go(-1); : 전페이지로 (입력창)
    if(check==1){
        //로그인 성공
        session.setAttribute("memId",id);
        response.sendRedirect("main.jsp");
        
    }else if(check==0){    
%>  
    <script>
        alert("비밀번호가 맞지 않습니다.");
        history.go(-1);        
    </script>
<%}else{ %>
    <script>
        alert("아이디가 맞지 않습니다.");
        history.go(-1);        
    </script>
<%} %>


WebContent/view/logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
 session.invalidate();
 response.sendRedirect("main.jsp");
%> 

WebContent/view/main.jsp

<%@ page  contentType="text/html; charset=UTF-8"%>
<% 
   if(session.getAttribute("memId")==null){%>
<jsp:forward page="loginForm.jsp" />
     <%}else{%> 
<jsp:forward page="login.jsp" />
 <%} %>

WebContent/view/modifyForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import ="com.dao.MemberDao,com.domain.Member" %>
<%  //로그인 체크
    if(session.getAttribute("memId")==null){
        response.sendRedirect("main.jsp");
    }else{
%>
<!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>
</head>
<%
    String memId =(String)session.getAttribute("memId");
    MemberDao manager= MemberDao.getInstance();
    Member c = manager.getMember(memId);
    
    //Email Blog null값일때 공백처리
    if(c.getEmail()==null){
        c.setEmail("");
    }
    if(c.getBlog()==null){
        c.setBlog("");
    }
%>
<body>
<form method="post" action="modifyPro.jsp" name="userinput">
<h3>회원정보 수정</h3>
사용자ID : <%=c.getId() %><br/>
비밀번호 : <input type="password" name="passwd" size="10" maxlength="10" value="<%=c.getPasswd()%>"><br/>
사용이름 : <input type="text" name="name" size="15" maxlength="20" value="<%=c.getName()%>"><br/>
주민등록번호 : <%=c.getJumin1() %>-<%=c.getJumin2()%><br/>
E-Mail : <input type ="text" name ="email" size="40" maxlength="30" value="<%=c.getEmail() %>"><br/>
Blog : <input type ="text" name ="blog" size="60" maxlength="50" value="<%= c.getBlog() %>"><br/>

<input type="submit" name="modify" value="수   정">
<input type="button" value="취   소" onclick="location.href='main.jsp'">
</form>
</body>
</html>
<%}%>

WebContent/view/modifyPro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="com.dao.MemberDao" %>
<% 
    if(session.getAttribute("memId")==null){
        response.sendRedirect("main.jsp");
    }else{
        request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="member" class="com.domain.Member">
    <jsp:setProperty name="member" property="*"/>
</jsp:useBean>
<%
    member.setId((String)session.getAttribute("memId"));

    MemberDao manager = MemberDao.getInstance();
    manager.updateMember(member);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Refresh" content="5; url=main.jsp; charset=UTF-8">
<title>회원정보 수정</title>
</head>
<body>
<h3>회원정보 수정</h3>
<div align="center">회원정보가 정상적으로 수정되었습니다</div>
</body>
</html>
<%}%>

WebContent/WEB-INF/lib

commons-collections-3.1.jar / commons-dbcp-1.2.1.jar  /  commons-pool-1.2.jar



회원가입,로그인 테스트

입력폼 : inputForm.jsp 정보입력


등록 : inputPro.jsp 알림창


Oracle SQL Developer : 등록확인


로그인 테스트 : main.jsp (loginForm.jsp)


로그인 성공 login.jsp //로그아웃 버튼누르면 다시 main.jsp



회원탈퇴 삭제 테스트

회원탈퇴폼 deleteForm.jsp


회원삭제 deletePro.jsp


삭제후 메인페이지 main.jsp(loginForm.jsp)




회원정보 수정테스트

회원정보 수정 폼  modifyForm.jsp


변경전


수정값입력 후 수정

수정완료 : modifyPro.jsp


변경확인


5초후 리플레쉬 대면서 메인으로 이동



회원가입 빈칸체크  modifyForm.jsp ->modifyPro.jsp -> MemberDao





아이디 중복체크   inputForm.jsp -> confirmId.jsp ->MemberDao


=======================================================

커넥션 생성과 close 문제점


수영장 튜브 대여소 


1. 생성 : 줄서서 한명씩 바람넣는거 기달리고 입장

2. 반환 : 줄서서 한명씩 바람빼는거 기달리고 입장


==문제 해결 ==> 커넥션 풀


1. 생성 : 미리 일정갯수의 튜브를 미리 바람을 넣어둠

    2. 전부사용을하면 다시 일정갯수의 튜브에 바람을 넣어둠

3. 반환 : 바람안빼고 반환받아둠

    4. 다시 그걸 대여해줌 => 재활용

=======================================================


 

자카르타DBCP.doc


커넥션 풀


일정갯수의 커넥션을 만들어둬서 사용자가 요청을하면 보내줌

사용자가 생성해둔 커넥션을 전부 받아가면 다시 또 일정갯수의 커넥션을 만들어둔다.

하지만 너무많은 커넥션을 생성하면 부하의 원인이 되므로

정책을 사용해서 총 커넥션의 갯수를 지정해 초과시 대기시키도록 설정할수있다.

생성과 ,


1. 데이터베이스 연동 프로그램의 문제점 



데이터베이스에 연결하기 위해서 매번 커넥션(Connection) 객체를 생성할 때는 많은 시스템 자원이 요구됨. (객체 메모리 적재시 메모리에 객체를 할당할 자리 생성, 초기화 작업, 객체 미사용시 객체를 삭제하는 작업 등등) 


2. 커넥션 풀(Connection Pool) 이란? 


데이터베이스와 연결된 커넥션을 미리 만들어서 풀(pool) 속에 저장해 두고 있다가 필요할 때에 커넥션을 풀(pool)에서 가져다 쓰고 다시 풀(pool)에 반환하는 기법을 의미


3. 커넥션 풀의 장점 


1) 풀 속에 미리 커넥션이 생성되어 있기 때문에 커넥션을 생성하는데 시간이 소비되지 않음


2) 커넥션을 재사용하기 때문에 생성되는 커넥션 수가 많지 않음


3) 커넥션을 생성하고 제거하는데 필요한 시간이 소요되지 않아 어플리케이션의 실행 속도가 빨라지며  한번에 생성


    될 수 있는 커넥션 수를 제어하기 때문에 동시 접속자 수가 많아도 웹 어플리케이션이 쉽게 다운되지 않음



4. 자카르타 DBCP API 와 DataSource:커넥션을 할당받는역활 (아파치그룹에서 만듬)


1) 컨넥션 풀을 사용하기 위해 아파치 그룹에서 제공하는 자카르타 DBCP 이용. 자카르타의 DBCP는 커넥션 풀링 기능을 제공하고 사용되지 않는 커넥션을 해제시켜주는 기능도 포함.  


2) DataSource : javax.sql.DataSource 데이터베이스에 접근하기 위한 표준 인터페이스, 특히 DBCP를 이용하기 위한 표준방식




5 JNDI (Java Naming and Directory Interface) : 사용자가 원하는 리소스/서비스를 등록하고 찾기 위한 방법


DBCP API를 이용한 커넥션 풀을 구성할 때 데이터 베이스 커넥션에 대한 정보를 자바코드에 직접 하드 코딩하는 것 보다 외부파일에 실제 정보를 기록해 두고 자바코드에는 그 정보를 읽어올 수 있는 name(이름값)만을 기록해두면 데이터 베이스에 대한 정보가 변경된다 하더라도 모든 자바코드를 수정하는 것이 아니라 해당 정보를 기록해 놓은 외부파일만 수정하면 되기 때문에 간편하게 사용할 수 있다.




6. Eclipse Dynamic Web Project 에서 DBCP API를 이용한 커넥션 풀 설정


1) 자카르타(Jakarta) DBCP API 관련 jar 파일 설치 (jakarta.apache.org)


commons-collections-3.1.jar


commons-dbcp-1.2.1.jar


commons-pool-1.2.jar


commons-collections-3.1.jar commons-dbcp-1.2.1.jar commons-pool-1.2.jar



설치 위치 :작업하고 있는 프로젝트>WEB-INF>lib 에 상기 jar파일을 설치함


2)  데이터베이스 설정 및 컨넥션 풀 설정 정보 기록


설치 위치 : 컨텍스트>META-INF 에 context.xml 생성


<?xml version="1.0" encoding="UTF-8"?>


<Context >


 <Resource name="jdbc/java"


  auth="container"


  type="javax.sql.DataSource"


  username="scott"


  password="tiger"


  driverClassName="oracle.jdbc.driver.OracleDriver"


  factory=”org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory;


url="jdbc:oracle:thin:@localhost:1521:orcl"


  maxActive="100"

     maxIdle="10" />


</Context>



3) web.xml 파일에 추가 될 내용  


  컨텍스트>WEB-INF/web.xml 파일을 열어 web-app의 하위 요소로 아래와 같이 추가 기재


   <web-app>


      <resource-ref>


      <description>DB Connection</description>


      <res-ref-name>jdbc/java</res-ref-name>


      <res-type>javax.sql.DataSource</res-type>


      <res-auth>Container</res-auth>


     </resource-ref>


   </web-app>



7. 코딩 예


Context initCtx = new InitialContext(); 


Context envCtx = (Context) initCtx.lookup("java:comp/env");


DataSource ds = (DataSource)envCtx.lookup("jdbc/java");


Connection conn = ds.getConnection();


또는


Context initCtx = new InitialContext(); 


DataSource ds = (DatSource) initCtx.lookup("java:comp/env/ jdbc/java ");


Connection conn = ds.getConnection();


 

============복습============
JDBC프로그램의 일반적인 실행 순서는 다음과 같다.
 1. JDBC 드라이버 로딩
 2. 데이터베이스 커넥션 구함
 3. 쿼리 실행을 위한 Statement 객체 생성
 4. 쿼리 실행
 5. 쿼리 실행 결과 사용
 6. Statement 종료
 7. 데이터베이스 커넥션 종료


============================================================



DB생성

SQLite
DB 생성 => id부여 => table 생성

Orcle 
일반계정 생성(ex:hr, scott) : DB생성이된거
명시적 DB생성을 안해도 계정생성시 같이 생성됨
 => table 생성

Form(입력창) => JSP => 자바빈 => 자바 클래스(DAO: Data Access Object) <=> DB 

오라클을 사용할때. 작업들가기전 확인해야될것.

제어판 관리도구 서비스 에서  Listener 와 ORCL 시작확인






insertTestForm.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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>레코드 삽입 (추가 ) 예제</title>
</head>
<body>
<h2>member1 테이블에 레코드 삽입(추가)예제</h2>
<form method="post" action="insetTest.jsp">
아이디: <input type="text" name="id"><br/>
패스워드: <input type="password" name="passwd"><br/>
이름: <input type="text" name="name"><br/>
    <input type="submit" value="보내기">
</form>
</body>
</html>

insertTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
    request.setCharacterEncoding("utf-8");
     
    //전송된 데이터 처리
    String id =request.getParameter("id");
    String passwd =request.getParameter("passwd");
    String name =request.getParameter("name");
    
    //전송되지 않은 데이터를 jsp에서 생성함(날짜/시간)
    Timestamp register= new Timestamp(System.currentTimeMillis());
    
    Connection conn=null;
    PreparedStatement pstmt=null;
    
    try{
            String jdbcUrl="jdbc:oracle:thin:@localhost:1521:orcl";
            String dbId="hr";
            String dbPass="hr";
            
        //JDBC 패턴을 아는것이 중요하다.
        //JDBC 수행1단계 : JDBC driver 로드
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //JDBC 수행2단계 : Connection 객체 생성
        conn=DriverManager.getConnection(jdbcUrl,dbId,dbPass);            

        //String sql ="insert into member1(id,passwd) values(?,?)";//특정 컬럼일경우 명시해야함    
        //String sql ="insert into member1(id,passwd,name,register) values(?,?,?,?)";//컬럼명을 명시해야하지만 전체입력이라 생략
        //? : 바인드 문자
        String sql ="insert into member1 values(?,?,?,?)";
            
        
        //JDBC 수행3단계 : PreparedStatement 객체 생성
        //conn.prepareStatement : 에 sql문장 보관
        pstmt=conn.prepareStatement(sql);
        //각각의 바인드 문자에 매칭시킴
        pstmt.setString(1, id);
        pstmt.setString(2, passwd);
        pstmt.setString(3, name);
        pstmt.setTimestamp(4, register);
        
        //JDBC 수행4단계 : SQL문 실행
        pstmt.executeUpdate();
        
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        //자원정리
        if(pstmt !=null) try{pstmt.close();}catch(SQLException sqle){}
        if(conn !=null) try{conn.close();}catch(SQLException sqle){}
    }
%>
<!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>
</head>
<body>
    member1 테이블에 새로운 레코드를 삽입 (추가) 했습니다.
</body>
</html>



selectTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%> 
<%@ page import="java.sql.*" %>
<!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>
    <h2>member1 테이블의 레코드를  화면에 표시하는 예제</h2>
    <table width="550" border="1">
    <tr>
        <td width="100">아이디</td>
        <td width="100">패스워드</td>
        <td width="100">이름</td>
        <td width="100">가입일자</td>
    </tr>
<%
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    
    try{
        String jdbcUrl="jdbc:oracle:thin:@localhost:1521:orcl";
        String dbId="hr";
        String dbPass="hr";
        
        //JDBC 수행1단계 : JDBC driver 로드
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //JDBC 수행2단계 : Connection 객체 생성
        conn=DriverManager.getConnection(jdbcUrl,dbId,dbPass);
        
        String sql ="select * from member1";
        //JDBC 수행3단계 : PrepareStatement 객체생성
        pstmt=conn.prepareStatement(sql);
        //JDBC 수행4단계 : SQL문 실행
        //JDBC 수행5단계 : SQL문 실행으로 얻어진 모든 레코드를 담은 ResultSet 객체생성
        rs=pstmt.executeQuery();
        
        while(rs.next()){
            String id= rs.getString("id"); //(id)컬럼명 대신 숫자 1,2,3,4 등으로 사용가능 / 컬럼명 사용을추천
            String passwd= rs.getString("passwd");
            String name = rs.getString("name");
            //밀리세컨드까지 뽑을경우 Timestamp사용 ,그렇지 않으면 사용 할 필요없슴
            Timestamp register=rs.getTimestamp("register");
%>
    <tr>
        <td width="100"><%=id%></td>
        <td width="100"><%=passwd%></td>
        <td width="100"><%=name%></td>
        <td width="250"><%=register.toString()%></td>
    </tr>
<%        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        //자원정리
        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){}
    }
%>
    </table>
</body>
</html>


updateTestForm.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></head>
<body>
  <h2>member1 테이블의 레코드 수정예제</h2>
  <form method="post" action="updateTest.jsp">
    아이디 : <input type="text" name="id"><p>
    패스워드 : <input type="password" name="passwd"><p>
    변경할 이름:<input type="text" name="name"><p>
    <input type="submit" value="보내기">
  </form>
</body>
</html>

updateTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %>
<!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>
</head>
<body>
<%
    request.setCharacterEncoding("utf-8");
    
    String id =request.getParameter("id");
    String passwd =request.getParameter("passwd");
    String name =request.getParameter("name");
    
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    
    try{
        String jdbcUrl="jdbc:oracle:thin:@localhost:1521:orcl";
        String dbId="hr";
        String dbPass="hr";
        
        //JDBC 수행1단계 : JDBC driver 로드
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //JDBC 수행2단계 : Connection 객체 생성
        conn=DriverManager.getConnection(jdbcUrl,dbId,dbPass);
        
        String sql ="select id, passwd from member1 where id= ?";
        //JDBC 수행3단계 : PrepareStatement 객체생성
        pstmt=conn.prepareStatement(sql);
        //JDBC 수행4단계 : SQL문 실행
        //JDBC 수행5단계 : SQL문 실행으로 얻어진 모든 레코드를 담은 ResultSet 객체생성        
        pstmt.setString(1,id);
        rs=pstmt.executeQuery();
        
        
        //레코드를 읽어오는데 
        //re.next =true => 아이디에 맞는 레코드가 있다.
        //re.next =false => 아이디에 맞는 레코드가 없다.
        if(rs.next()){
            String rId=rs.getString("id");
            String rPasswd=rs.getString("passwd");
            //db에서 가져온 아이디 패스워드와  입력한  아이디패스워드가 같은가 조건체크
            if(id.equals(rId) && passwd.equals(rPasswd)){
                sql="update member1 set name=? where id=?";
                pstmt =conn.prepareStatement(sql);
                pstmt.setString(1,name);
                pstmt.setString(2,id);
                pstmt.executeUpdate();
%>
    member1 테이블 레코드를 수정했습니다.
<% 
            }else{
                out.println("패스워드가 틀렸습니다.");
            }
        }else{
            out.println("아이디가 틀렸습니다.");
        }        
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        //자원정리
        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){}
    }
%>
</body>
</html>



deleteTestForm.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></head>
<body>
  <h2>member1 테이블의 레코드 삭제예제</h2>
  <form method="post" action="deleteTest.jsp">
    아이디 : <input type="text" name="id"><p>
    패스워드 : <input type="password" name="passwd"><p>
    <input type="submit" value="보내기">
  </form>
</body>
</html>

deleteTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!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>
</head>
<body>

<%
    request.setCharacterEncoding("utf-8");
    
    String id =request.getParameter("id");
    String passwd =request.getParameter("passwd");
    
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    
    try{
        String jdbcUrl="jdbc:oracle:thin:@localhost:1521:orcl";
        String dbId="hr";
        String dbPass="hr";
        
        //JDBC 수행1단계 : JDBC driver 로드
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //JDBC 수행2단계 : Connection 객체 생성
        conn=DriverManager.getConnection(jdbcUrl,dbId,dbPass);
        
        String sql ="select id, passwd from member1 where id= ?";
        //JDBC 수행3단계 : PrepareStatement 객체생성
        pstmt=conn.prepareStatement(sql);
        //JDBC 수행4단계 : SQL문 실행
        //JDBC 수행5단계 : SQL문 실행으로 얻어진 모든 레코드를 담은 ResultSet 객체생성        
        pstmt.setString(1,id);
        rs=pstmt.executeQuery();
        
        if(rs.next()){
            String rId=rs.getString("id");
            String rPasswd=rs.getString("passwd");
            if(id.equals(rId) && passwd.equals(rPasswd)){
                sql="delete from member1 where id= ? ";
                pstmt=conn.prepareStatement(sql);
                pstmt.setString(1, id);
                pstmt.executeUpdate();

%>
    member1 테이블의 레코드를 삭제했습니다.
<%        
            }else{
                out.println("패스워드가 틀렸습니다.");
            }
        }else{
            out.println("아이디가 틀렸습니다.");
        }        
    }catch(Exception e){
        e.printStackTrace();
    }finally{       
//자원정리
        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){}
    }
%>    
</body>
</html>













+ Recent posts