--------------------------------------------/WEB-INF/CommandPro.properties 추가
/mvc2bbs/updateForm.do=my.action.UpdateFormAction

------------------------------------------------------------UpdateFormAction.java
package my.action;

import java.sql.ResultSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import my.board.BoardDBBean;
import my.board.BoardDataBean;

public class UpdateFormAction implements CommandAction {
    @Override
    public String requestPro(HttpServletRequest request,
                                          HttpServletResponse response)  throws Throwable
              {
        BoardDataBean article = null;      
        int num=Integer.parseInt(request.getParameter("num"));
        String pageNum=request.getParameter("pageNum");    
        BoardDBBean dbPro=  BoardDBBean.getInstance();         
        article = dbPro.updateGetArticle(num); 
        request.setAttribute("pageNum", new Integer(pageNum));
        request.setAttribute("article", article);          
        return "updateForm.jsp"; //해당뷰
    }

}//End
------------------------------------------------------------BoardDBBean.java
 public BoardDataBean updateGetArticle(int num) throws Exception
 {
    Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;         
    BoardDataBean article=null;
    try {
        conn=getConnection();
        String sql=" Select * From board Where num=? ";
        pstmt=conn.prepareStatement(sql);
        pstmt.setInt(1, num);
        rs = pstmt.executeQuery();                         
        if(rs.next()){
            article = new BoardDataBean();
            article.setNum(rs.getInt("num"));
                        article.setWriter(rs.getString("writer"));
                        article.setEmail(rs.getString("email"));
                        article.setSubject(rs.getString("subject"));
                        article.setPasswd(rs.getString("passwd"));
                        article.setReg_date(rs.getTimestamp("reg_date"));
                        article.setReadcount(rs.getInt("readcount"));
                        article.setRef(rs.getInt("ref"));
                        article.setRe_step(rs.getInt("re_step"));
                        article.setRe_level(rs.getInt("re_level"));
                        article.setContent(rs.getString("content"));
                        article.setIp(rs.getString("ip"));                 
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        if(rs!=null) try { rs.close(); } catch(SQLException e){}
        if(pstmt!=null) try { pstmt.close(); } catch(SQLException e){}
        if(conn!=null) try { conn.close(); } catch(SQLException e){}
    }
    return article;
 }//updateGetArticle
------------------------------------------------------------updateForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@include file="/view/color.jspf" %>

<!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=EUC-KR">
<title>게시판</title>

</head>
<body bgcolor="${bodyback_c }">
<center><b>글 수정</b></center>
<br/>
<form method="post"
          name="writeform"
          action="/mvc2bbs/updatePro.do?pageNum=${pageNum}"
          onSubmit="return writeSave()"   >

<table width="400" border="1"  cellspacing="0" cellpadding="0" align="center">
    <tr>
        <td width="70" bgcolor="${value_c }" align="center">이름</td>
        <td align="left" width="330" >
            <input type="text"  size="10" maxlength="10" name ="writer"  value="${article.writer }">
            <input type="hidden"  name ="num"  value="${article.num }">
        </td>
    </tr>
    <tr>
        <td width="70" bgcolor="${value_c }"  align="center">제목</td>
        <td align="left" width="330" >
            <input type="text" size="40" maxlength="50" name ="subject"  value="${article.subject}">
        </td>
    </tr>
    <tr>
        <td width="70" bgcolor="${value_c } " align="center">이메일</td>
        <td align="left" width="330" >
            <input type="text"  size="40" maxlength="30" name ="email" value="${article.email}">
        </td>
    </tr>
    <tr>
        <td width="70" bgcolor="${value_c }" align="center">내용</td>
        <td align="left" width="330" >
            <textarea  name ="content" rows="13" cols="40" >${article.content }</textarea>
        </td>
    </tr>
    <tr>
        <td width="70" bgcolor="${value_c } " align="center">비밀번호</td>
        <td align="left" width="330" >
            <input type="password"  size="8" maxlength="12" name ="passwd" >
        </td>
    </tr>
    <tr>
        <td colspan=2 bgcolor="${value_c }" align="center">
            <input type="submit" value="글수정">
            <input type="reset" value="다시작성">
            <input type="button" value="목록"
                                             onClick="document.location.href='/mvc2bbs/list.do?pageNum=${pageNum }'">
        </td>
    </tr>

</table>
</form>

</body>
</html>
--------------------------------------------/WEB-INF/CommandPro.properties 추가
/mvc2bbs/updatePro.do=my.action.UpdateProAction

------------------------------------------------------------UpdateProAction.java
package my.action;

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

import my.board.BoardDBBean;
import my.board.BoardDataBean;

public class UpdateProAction implements CommandAction {

    @Override
    public String requestPro(HttpServletRequest request,    HttpServletResponse response)
                                             throws Throwable
    {
        request.setCharacterEncoding("euc-kr");
        String pageNum = request.getParameter("pageNum");
           
            BoardDataBean article=new BoardDataBean();
           
            article.setNum(Integer.parseInt(request.getParameter("num")));
            article.setWriter(request.getParameter("writer"));
            article.setEmail(request.getParameter("email"));
            article.setSubject(request.getParameter("subject"));
            article.setContent(request.getParameter("content"));
            article.setPasswd(request.getParameter("passwd"));
           
            BoardDBBean dbPro=BoardDBBean.getInstance();
            int check = dbPro.updateArticle(article);
           
            request.setAttribute("pageNum", new Integer(pageNum));
            request.setAttribute("check", new Integer(check));
           
            return "updatePro.jsp";
    }

}//End
------------------------------------------------------------BoardDBBean.java추가
 public int updateArticle(BoardDataBean article) throws Exception
 {
              Connection conn=null;
    PreparedStatement pstmt=null;
    ResultSet rs=null;
    String dbpasswd="";
    String sql="";
    int x=-1;
    try{
       conn=getConnection();
       pstmt=conn.prepareStatement("select passwd from board where num=?");
       pstmt.setInt(1, article.getNum());
       rs = pstmt.executeQuery();
       if(rs.next()){
           dbpasswd = rs.getString("passwd");
           if(dbpasswd.equals(article.getPasswd()))   {
            sql="  Update board Set writer=?, email=?, subject=?, passwd=? ";
                sql+= "  ,content=? Where num=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, article.getWriter());
            pstmt.setString(2, article.getEmail());
            pstmt.setString(3, article.getSubject());
            pstmt.setString(4, article.getPasswd());
            pstmt.setString(5, article.getContent());
            pstmt.setInt(6, article.getNum());
            pstmt.executeUpdate();
            x=1;
               }else{
                x=0;
               }
       }//if                                   
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        if(rs!=null) try { rs.close(); } catch(SQLException e){}
        if(pstmt!=null) try { pstmt.close(); } catch(SQLException e){}
        if(conn!=null) try { conn.close(); } catch(SQLException e){}
    } 
    return x;
 }//updateArticle
------------------------------------------------------------updateProjsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
   
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:if test="${check==1 }">
        <meta http-equiv="Refresh" content="0;url=/mvc2bbs/list.do?pageNum=${pageNum}" >
</c:if>

<c:if test="${check==0 }">
         비밀번호가 다릅니다.
         <br/>
         <a href="javascript:history.go(-1)">[글 수정 폼으로 돌아가기]</a>
</c:if>

 

--------------------------------------------/WEB-INF/CommandPro.properties 추가
/mvc2bbs/content.do=my.action.ContentAction

 

-------------------------------------------------------------ContentAction.java
package my.action;

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

import my.board.BoardDBBean;
import my.board.BoardDataBean;

public class ContentAction implements CommandAction {
   public String requestPro(HttpServletRequest request,
                                      HttpServletResponse response) throws Throwable{
  //해당글번호
    int num=Integer.parseInt(request.getParameter("num"));
  //해당페이지번호
    String pageNum=request.getParameter("pageNum");
   
  //DB처리
    BoardDBBean dbPro=BoardDBBean.getInstance();
  //해당 글번호에 대한 해당 레코드
    BoardDataBean article=dbPro.getArticle(num);
   
    request.setAttribute("num",new Integer(num));
    request.setAttribute("pageNum",new Integer(pageNum));
    request.setAttribute("article",article);

    return "content.jsp";
   }
}

-------------------------------------------------------------BoardDBBean.java추가
//content 메소드

public class BoardDBBean{
   
    public BoardDataBean getArticle(int num) throws Exception{
        Connection conn=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        BoardDataBean article=null;
        try{
            conn=getConnection();
            String sql="Update board Set readcount=readcount+1 where num=?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            pstmt.executeUpdate();
           
            sql="Select * From board where num=?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, num);
            rs=pstmt.executeQuery();
            if(rs.next()){
                article=new BoardDataBean();
                article.setNum(rs.getInt("num"));
                article.setWriter(rs.getString("writer"));
                article.setEmail(rs.getString("email"));
                article.setSubject(rs.getString("subject"));
                article.setPasswd(rs.getString("passwd"));
                article.setReg_date(rs.getTimestamp("reg_date"));
                article.setReadcount(rs.getInt("readcount"));
                article.setRef(rs.getInt("ref"));
                article.setRe_step(rs.getInt("re_step"));
                article.setRe_level(rs.getInt("re_level"));
                article.setContent(rs.getString("content"));
                article.setIp(rs.getString("ip"));                 
            }            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(rs!=null) try { rs.close(); } catch(SQLException e){}
            if(pstmt!=null) try { pstmt.close(); } catch(SQLException e){}
            if(conn!=null) try { conn.close(); } catch(SQLException e){}
        }        
        return article;
    }

}

-----------------------------------------------------------content.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="/view/color.jspf" %>
<!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=EUC-KR">
<title>상세보기</title>
</head>
<body bgcolor="${bodyback_c }">
<center><b>글내용보기</b></center>
<br/>
<form>
<table border="1">
<tr>
 <td bgcolor="${value_c }">글번호</td>
 <td>${article.num }</td>
 <td bgcolor="${value_c }">조회수</td>
 <td>${article.readcount }</td>
</tr>
<tr>
 <td bgcolor="${value_c }">작성자</td>
 <td>${article.writer }</td>
 <td bgcolor="${value_c }">작성일</td>
 <td>${article.reg_date }</td>
</tr>
<tr>
 <td bgcolor="${value_c }">글제목</td>
 <td colspan=3>${article.subject }</td>
</tr>
<tr>
 <td bgcolor="${value_c }">글내용</td>
 <td colspan=3>${article.content }</td>
</tr>
<tr>
 <td colspan=4 bgcolor="${value_c }">
   <input type="button" value="글수정"
     onClick="document.location.href='/mvc2bbs/updateForm.do?num=${article.num}
                                                       &pageNum=${pageNum }'">
   <input type="button" value="글삭제"
     onClick="document.location.href='/mvc2bbs/deleteForm.do?num=${article.num}
                                                       &pageNum=${pageNum }'">
   <input type="button" value="답변"
     onClick="document.location.href='/mvc2bbs/writeForm.do?num=${article.num}
    &ref=${article.ref }&re_step=${article.re_step }$re_level=${article.re_level }'">
   <input type="button" value="목록"
     onClick="document.location.href='/mvc2bbs/list.do?pageNum=${pageNum }'">
 </td>
</tr>
</table>

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

--------------------------------------------/WEB-INF/CommandPro.properties 추가
/mvc2bbs/list.do=my.action.ListAction

----------------------------------------------------------------ListAction.java
package my.action;

import java.util.Collections;
import java.util.List;

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

import my.board.BoardDBBean;

public class ListAction implements CommandAction{
  public String requestPro(HttpServletRequest request,
          HttpServletResponse response) throws Throwable{
      String pageNum=request.getParameter("pageNum");
      if(pageNum==null){
          pageNum="1";
      }
      int pageSize=10;
      int currentPage=Integer.parseInt(pageNum);
      int startRow=(currentPage-1)*pageSize+1;
      int endRow=currentPage*pageSize;
      int count=0;
      int number=0;
     
      List articleList=null;
      BoardDBBean dbPro=BoardDBBean.getInstance();
      count=dbPro.getArticleCount();
     
      if(count>0){
          articleList=dbPro.getArticles(startRow, endRow);
      }
      else{
          articleList=Collections.EMPTY_LIST;
      }
     
      number=count-(currentPage-1)*pageSize;
     
      //request영역에 저장
      request.setAttribute("currentPage", new Integer(currentPage));
      request.setAttribute("startRow", new Integer(startRow));
      request.setAttribute("endRow", new Integer(endRow));
      request.setAttribute("count", new Integer(count));
      request.setAttribute("pageSize", new Integer(pageSize));
      request.setAttribute("number", new Integer(number));
      request.setAttribute("articleList", articleList);

      return "list.jsp";
  }
}

------------------------------------------------------------------------list.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="/view/color.jspf" %>
<!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=EUC-KR">
<title>글목록</title>
</head>
<body bgcolor="${bodyback_c }">
<center><b>글목록(전체 글:${count })</b></center>

<table width="700">
  <tr>
 <td bgcolor="${value_c}"><a href="/mvc2bbs/writeForm.do">글쓰기</a></td>
  </tr>
</table>

<c:if test="${count==0 }">
  <table width="700">
  <tr>
 <td>게시판에 글 없음!!</td>
  </tr>
  </table>
</c:if> 

<c:if test="${count>0 }">
  <table border="1">
  <tr>
 <td>번호</td>
 <td>제목</td>
 <td>작성자</td>
 <td>작성일</td>
 <td>조회</td>
 <td>IP</td>
  </tr>
 
  <c:forEach var="article" items="${articleList }">
  <tr>
 <td>
   <c:out value="${number }"/>
   <c:set var="number" value="${number-1 }"/>
 </td>
 <td>
   <c:if test="${article.re_level>0 }">
     <img src="images/level.gif" border="0" width="${5*article.re_level }" height="16"/>
     <img src="images/re.gif">
   </c:if>
   <c:if test="${article.re_level==0 }">
     <img src="images/level.gif" border="0" width="${5*article.re_level }" height="16"/>
   </c:if>
   <a href="/mvc2bbs/content.do?num=${article.num }&pageNum=${currentPage }">
     ${article.subject }</a>
     <c:if test="${article.readcount>=20 }">
       <img src="images/hot.gif" border="0" height="16"/>
     </c:if>
 </td>
 <td><a href="mailto:${article.email}">${article.writer }</a></td>
 <td>${article.reg_date }</td>
 <td>${article.readcount }</td>
 <td>${article.ip }</td>
  </tr>
  </c:forEach>
  </table>
</c:if> 

<c:if test="${count>0 }">
  <c:set var="pageCount" value="${count/pageSize+(count%pageSize==0?0:1) }"/>
  <c:set var="startPage" value="${currentPage/pageSize+1 }"/>
  <c:set var="endPage"   value="${startPage+10 }"/>
 
  <c:if test="${endPage>pageCount }">
     <c:set var="endPage" value="${pageCount }"/>
  </c:if>
 
  <c:if test="${startPage>10 }">
     <a href="/mvc2bbs/list.do?pageNum=${startPage-10 }">[이전]</a>
  </c:if>
 
  <c:forEach var="i" begin="${startPage }" end="${endPage }">
     <a href="/mvc2bbs/list.do?pageNum=${i }">[${i}]</a>
  </c:forEach>
 
  <c:if test="${endPage<pageCount }">
     <a href="/mvc2bbs/list.do?pageNum=${startPage+10 }">[다음]</a>
  </c:if>
 
</c:if>

</body>
</html>

-------------------------------------------------------------BoardDBBean.java추가

public class BoardDBBean{
   
    //글갯수 구하기
    public int getArticleCount() throws Exception{
        Connection conn=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        int x=0;
        try{
            conn=getConnection();
            pstmt=conn.prepareStatement("SELECT count(*) FROM board");
            rs=pstmt.executeQuery();
            if(rs.next()){
                x=rs.getInt(1);            
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(rs!=null) try { rs.close(); } catch(SQLException e){}
            if(pstmt!=null) try { pstmt.close(); } catch(SQLException e){}
            if(conn!=null) try { conn.close(); } catch(SQLException e){}
        }
        return x;
    }//count
   
    //글목록 구하기
    public List getArticles(int start,int end) throws Exception{
        Connection conn=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        List articleList=null;
        String sql=" Select a.* ";
        sql+="       From ( ";
        sql+="             Select ROWNUM as RNUM, b.* ";
        sql+="             FROM ( ";
        sql+="                    Select * From board Order By ref desc,re_step ASC ";
        sql+="                  ) b ";
        sql+="             ) a ";
        sql+="             Where a.RNUM >=? AND a.RNUM<=? ";

        try{
            conn=getConnection();
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1, start);
            pstmt.setInt(2, end);
            rs=pstmt.executeQuery();
           
            if(rs.next()){
                articleList=new ArrayList(end);
                do{
                    BoardDataBean article=new BoardDataBean();
                    article.setNum(rs.getInt("num"));
                    article.setWriter(rs.getString("writer"));
                    article.setEmail(rs.getString("email"));
                    article.setSubject(rs.getString("subject"));
                    article.setPasswd(rs.getString("passwd"));
                    article.setReg_date(rs.getTimestamp("reg_date"));
                    article.setReadcount(rs.getInt("readcount"));
                    article.setRef(rs.getInt("ref"));
                    article.setRe_step(rs.getInt("re_step"));
                    article.setRe_level(rs.getInt("re_level"));
                    article.setContent(rs.getString("content"));
                    article.setIp(rs.getString("ip"));
                   
                    articleList.add(article);
                   
                }while(rs.next());
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(rs!=null) try { rs.close(); } catch(SQLException e){}
            if(pstmt!=null) try { pstmt.close(); } catch(SQLException e){}
            if(conn!=null) try { conn.close(); } catch(SQLException e){}
        }
        return articleList;
    }//end

}

 

  ---------------------------------------------------문제
 String word="write.do=my.board.WriteForm";
  int ch=word.indexOf("=");  
  String command=word.substring(0,ch);//write.do
  String classnm=word.substring(ch+1);//my.board.WriteForm  
  System.out.println(command);
  System.out.println(classnm);

 

  //command가 key, classnm이 value로
  //해시맵 hm객체에 추가

  HashMap hm=new HashMap();

  hm.put(command, classnm);

 

----------------------------------------------------문제

  HashSet list=new HashSet();
  list.add("list.do=my.board.ListAction");
  list.add("update.do=my.board.UpdateAction");
  list.add("delete.do=my.board.DeleteAction");
  
  HashMap map=new HashMap();
  // =앞의 문자열은 key값
  // =뒤의 문자열은 value값으로 map에 추가
  
  Iterator iter=list.iterator();
  while(iter.hasNext()){
   String word=(String)iter.next();
   int ch=word.indexOf("=");   
   String command=word.substring(0,ch);
   String classnm=word.substring(ch+1);
   map.put(command, classnm);
   System.out.println(map.get(command));
  }

 

'..열심히 공부하세.. > JAVA 문법' 카테고리의 다른 글

[Vector 예제] Buyer - 반품 refund() 메소드  (0) 2012.06.26
[35] JDBC  (0) 2012.05.15
[34] 제네릭 Generics  (0) 2012.05.08
[33] Java Collections Framework  (0) 2012.05.08
[32] Object 클래스  (0) 2012.05.04

 

package oop09;

import java.util.Vector;

class Product{
    int price;      //상품가격
    int bonusPoint; //보너스점수
    Product(){}  
    Product(int price){
        this.price=price;
        bonusPoint=(int)(price/10.0);
    }
}
//=====================
class SmartTV extends Product{
    SmartTV()
    {
        super(200); //price=200 bonusPoint=20
    }

    public String toString() {
        return "SmartTV";
    }   
}

//=====================
class Computer extends Product{
  Computer(){
      super(150); //price=150 bonusPoint=15
  }
  public String toString(){
      return "Computer";
  }  
}
//=====================
class Audio extends Product{
  Audio(){
      super(100); //price=100 bonusPoint=10
  }
  public String toString(){
      //객체를 호출했을때 toString()메소드 호출
      return "Audio";
  }
}
//====================
class Buyer{
    int money=1000;//사용가능한 총금액.
    int mileage=0;//누적된 마일리지점수 합계 
    //static Product[] item=new Product[10];//객체배열
    Vector item=new Vector();
 int idx=0;
 
 void buy(Product p){

  if(this.money<p.price){
            System.out.println("잔액이 부족하여 물건을 구입할수 없음!!");
            return;
  }
  this.money=this.money-p.price;
  this.mileage=this.mileage+p.bonusPoint;
  //item[this.idx++]=p;
  item.add(p);
  
  //System.out.print(p+" "+p.price);
  //System.out.println();
 }
 
 void refund(Product p){
  if(item.remove(p)){
   money+=p.price;//나의 총재산
   mileage-=p.bonusPoint;//마일리지 점수
   System.out.println(p+"반품!!");
  }
  else{
   System.out.println("반품할 품목 없음!!");
  }
 }
 
    void summary()
    {
        int n;
        int hap=0;
        int bonushap=0;
        String str="";
        //2)벡터를 이용했을경우
        if(item.isEmpty()){
         System.out.println("구입한 물건 없음");
         return;
        }
       
        for(n=0;n<item.size();n++){
   Product p=(Product)item.get(n);
   hap+=p.price;
   bonushap+=p.bonusPoint;
   str+=(n==0)?""+p:","+p;
  }
  System.out.println("구매하신 물품의 총금액은 "+hap+"만원");
  System.out.println("보너스점수 "+bonushap+"만원");
  System.out.println("구입하신제품은"+str+"입니다.");

        /*1)객체배열을 이용했을경우
        for(n=0; n<item.length; n++)
        {
            if(item[n]==null) break;
            hap=hap+item[n].price;
            bonushap=bonushap+item[n].bonusPoint;
            str=str+item[n]+" ";
        }
       
        System.out.println("구입하신 물품의 총 금액 :"+hap);
        System.out.println("구입하신 물품의 보너스 금액 :"+bonushap);
        System.out.println("구입하신 물품명 :"+str);
        */
    }

}
public class BuyEx {
 public static void main(String[] args) {
  SmartTV smarttv=new SmartTV();
  //Product()->SmartTV()->Product(200)
  //price=200 bonuspoint=20
  
  //System.out.println(smarttv);
  //System.out.println(smarttv.price);
  //System.out.println(smarttv.bonusPoint);
  
  Computer comp=new Computer();
  //Product()->Computer()->Product(150)
  //price=150 bonuspoint=15
  //System.out.println(comp);
  
  Audio audio=new Audio();
  //Product()->Audio()->Product(100)
  //price=100 bonuspoint=10
  //System.out.println(audio);
  
  //Product fa=new SmartTV();
  //System.out.println(fa.price);//200
  
  //SmartTV sm=new Product();오류
  
  
  //물건 구매
  Buyer kim=new Buyer();
  kim.buy(smarttv);
  kim.buy(comp);
  kim.buy(comp);
  kim.buy(audio);
  kim.summary();
  
  //물건 반품(나의 총액+, 보너스점수-
  kim.refund(audio);
  kim.summary();//총금액500 보너스점수 50
  
 }

}

'..열심히 공부하세.. > JAVA 문법' 카테고리의 다른 글

[예제] set, map 예제  (0) 2012.06.26
[35] JDBC  (0) 2012.05.15
[34] 제네릭 Generics  (0) 2012.05.08
[33] Java Collections Framework  (0) 2012.05.08
[32] Object 클래스  (0) 2012.05.04

 

 

* 정부에서 지원하는 IT 취업을 위한 국비 과정은 주변에 많이 있다.

* 각각의 자격요건이 다르므로, 꼼꼼히 살펴보고 선택하자

  

1) 노동부 국비지원 과정 (계좌제)

    - 대상 : 누구나

    - 수강료 : 국비지원 80% + 개인부담 20%

    - 교육수당 : 약11만원

    - 절차 : 주소지의 고용지원센터에서 내일배움카드(계좌제)를 발급받아야 한다

 

2) 교과부 국비지원 과정 (이공계전문기술연수) 

    - 나이 : 만32세 미만 (해마다 달라짐)

    - 학력 : 전문대졸 이상 이공계관련 졸업생

    - 수강료 : 무료

    - 교육수당 : 약30만원

 

3) 중소기업청 인력채용패키지 과정

    - 소속은 중기청이나 관리감독은 노동부 관할에 있으므로 노동부 규정을 따른다

    - 무료/유료 혼재되어 있으니 정보수집을 정확히 해야 한다.

 

 

* 위의 취업대비 IT 국비지원과정을 수료하였다면 취업에 성공하기 위해서는 전략이 필요하다

* 다음의 아래의 단계는 교육과정 수료 2~3주전에 진행하기를 추천한다.

 

1단계 - 구인사이트 적극 활용하기

           . 잡코리아, 사람인, 워크넷에 이력서 작성하기

           . 대충 적지말고 구체적인 사항을 꼼꼼히 작성한다

           . 이력서 사진도 정장차림의 반명함판으로 올린다 (남자-면T, 여자-화려한 액서서리 불가)

 

 

2단계 - 구인사이트 이력서 공개

           . 면접은 무조건 OK
           .블랙리스트 정보 탐색
           .학습효과를 위해서라도 2-3군데 필히 면접볼것을 추천

 

3단계 - 입사지원서 제출
           .회사 주소 유심히 살펴볼것

           .본인이 가고자 하는 분야를 미리 정하지 말것 (금융, 보안등등~~)
           .프로그램 개발을 하다보면 자연스럽게 본인이 관심이 가고자 하는 것이 정해지지 않을까??

           .경력1년을 채우기 전까지는 회사 규모나 연봉에  너무 연연하지 않으면...
           .그래봤자~~~200-300수준
           .경력을 쌓을 수 있도록 일을 하는 것이 중요

           .신입으로 좋은 직장을 취업하는 것도 중요하지만
           .자신이 내공을 쌓은 후 원하는 회사에서 오래 버티는 것이 더 나은 방법일수도...

 

※ 과정 수료한 후 배움이 모자랐다고 생각되는 경우
    또다시 국비무료과정을 재수강하는 일은 없었으면...
    WHY?
    차라리 회사에 짤리더라도 실무를 빨리 접하는 것이 천만배정도는 훨 낫다

 

 

 

 

 

 

 

 

 

 

[DataBase Connection Pool]

 

사용DB : 오라클 XE

 

>>>>>>>>>>>>>>데이터베이스 커넥션 풀 작성>>>>>>>>>>>>>>>

 

-------------------------------------------라이브러리 3개파일 다운 및 압축 풀기
http://commons.apache.org/collections/download_collections.cgi
commons-collections-3.2.1-bin.zip

http://commons.apache.org/dbcp/download_dbcp.cgi
commons-dbcp-1.4-bin.zip

http://commons.apache.org/pool/download_pool.cgi
commons-pool-1.6-bin.zip

-------------------------------------------------------------/WEB-INF/lib/ 복사
commons-collections-3.2.1.jar
commons-dbcp-1.4.jar
commons-pool-1.6.jar

--------------------------------------------------------톰캣서버/conf/server.xml
46행 추가
        <Resource auth="Container"
                  driverClassName="oracle.jdbc.driver.OracleDriver"
                  factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
                  name="jdbc/oracle"
                  username="hr"
                  password="hr"
                  type="javax.sql.DataSource"
                  url="jdbc:oracle:thin://@127.0.0.1:1521:xe"
                  maxActive="20"
                  maxIdle="2"
                  removeAbandoned="true"/>

 

</GlobalNamingResources>

 

마지막 줄 </Host> 앞에  추가
   <Context path="" docBase="D:\JAVA_Green\workspace" reloadable="true" debug="0"/>
   <Context path="/mvc2bbs" docBase="D:\JAVA_Green\workspace\mvc2bbs"
                                                      reloadable="true" debug="0"/>

---------------------------------------------------------톰캣서버/conf/context.xml
34행 추가
       <Resource  auth="Container"
                  driverClassName="oracle.jdbc.driver.OracleDriver"
                  factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
           name="jdbc/oracle"
           username="hr"
           password="hr"
           type="javax.sql.DataSource"
           url="jdbc:oracle:thin://@127.0.0.1:1521:xe"
           maxActive="20"
                  maxIdle="2"
                  removeAbandoned="true"/>

----------------------------------------------------------------/WEB-INF/web.xml
  <resource-ref>
      <description>Connection</description>
      <res-ref-name>jdbc/oracle</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

-------------------------------------------------------my.board.BoardDBBean.java
package my.board;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

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

public class BoardDBBean{

    private BoardDBBean(){}
    private static BoardDBBean instance=new BoardDBBean();
    public static BoardDBBean getInstance(){
        return instance;
    }
   
    private Connection getConnection() throws Exception{
        Context initCtx=new InitialContext();
        DataSource ds  =(DataSource)initCtx.lookup("java:comp/env/jdbc/oracle");
        return ds.getConnection();
    }

 
       //아래 영역에 DB관련 메소드 작성

}

>>>>>>>>>>>>>DB연결 끝>>>>>>>>>>>>>>>>>>>>>


 

Dynamic Web Project : mvc2bbs

 

라이브러리 복사
/WEB-INF/lib/ojdbc14.jar
                    jstl.jar
                   standard.jar 복사

 

-------------------------------------------------------------게시판 테이블 생성
create table board(
    num number NOT NULL,
    writer varchar2(20) NOT NULL,
  email varchar2(30),
 subject varchar2(50) NOT NULL,
 passwd varchar2(10) NOT NULL,
 reg_date date NOT NULL,
 readcount number default 0,
 ref number NOT NULL,
 re_step number NOT NULL,
 re_level number NOT NULL,
 content varchar2(100) NOT NULL,
 ip varchar2(20) NOT NULL,
 PRIMARY KEY(num) 
);

create sequence board_seq;

-------------------------------------------------------------BoardDataBean.java
package my.board;

import java.sql.Timestamp;

public class BoardDataBean {
 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 int ref;
 private int re_step;
 private int re_level;

        setter와 getter를 생성
}
--------------------------------------------------------------------결과확인방법
http://localhost:9090/mvc2bbs/writeForm.do


------------------------------------------------------------------------호출순서
서버실행->*.do             
              (writeForm.do)

->ControllerAction
              CommandPro.properties 파일 읽어옴

-> init()
              my.action.WriteFormAction 생성 (CommandAction 구현)

-> doGet()
              http://localhost:9090/mvc2bbs/writeForm.do

-> requestPro()
             com= /mvc2bbs/writeForm.do -> WriteFormAction.java -> writeForm.jsp

 

--------------------------------------------------/WEB-INF/CommandPro.properties
/mvc2bbs/writeForm.do=my.action.WriteFormAction

-------------------------------------------------------/WEB-INF/web.xml 매핑하기
  <servlet>
    <servlet-name>ControllerAction</servlet-name>
    <servlet-class>my.controller.ControllerAction</servlet-class>
    <init-param>
      <param-name>propertyConfig</param-name>
      <param-value>D:/JAVA_Green/workspace/mvc2bbs/WebContent/WEB-INF
                                           /CommandPro.properties</param-value>
    </init-param>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>ControllerAction</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

---------------------------------------------my.controller.ControllerAction.java
package my.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;

import my.action.CommandAction;

public class ControllerAction extends HttpServlet {
  private Map commandMap=new HashMap();
  
  @Override
    public void init(ServletConfig config) throws ServletException {
        String props=config.getInitParameter("propertyConfig");
        Properties pr=new Properties();
        FileInputStream f=null;
        try{
            f=new FileInputStream(props);
            pr.load(f);
        }catch(IOException e){
            throw new ServletException(e);
        }finally{
            if(f!=null){
               try{
                   f.close();
               }catch(IOException e){}
            }
        }
       
        Iterator keyiter=pr.keySet().iterator();
        while(keyiter.hasNext()){
            String command=(String)keyiter.next();
            String className=pr.getProperty(command);
            try{
                Class commandClass=Class.forName(className);
                Object commandinstance=commandClass.newInstance();
                commandMap.put(command, commandinstance);
            }catch(ClassNotFoundException e){
                throw new ServletException(e);             
            }catch(InstantiationException e){
                throw new ServletException(e);
            }catch(IllegalAccessException e){
                throw new ServletException(e);
            }
        }
    }//end
 
  @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
       
        requestPro(req,resp);
    }//end
 
  @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        requestPro(req,resp);
    }//end
 
    private void requestPro(HttpServletRequest request,HttpServletResponse response)
            throws ServletException, IOException {
        String view=null;
        CommandAction com=null;
        try{
            String command=request.getRequestURI();
            if(command.indexOf(request.getContextPath())==0){}
            System.out.println(command);
            com=(CommandAction)commandMap.get(command);//다형성
            view=com.requestPro(request, response);
            System.out.print(view);
        }catch(Throwable e){
            throw new ServletException(e);         
        }
        RequestDispatcher dispatcher=request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
       
    }//end
}

-------------------------------------------------------------my.action.CommandAction.java
package my.action;

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

public interface CommandAction {
    public String requestPro(HttpServletRequest request,
                             HttpServletResponse response) throws Throwable;
}

------------------------------------------------my.action.WriteFormAction.java
package my.action;

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

public class WriteFormAction implements CommandAction {
    @Override
    public String requestPro(HttpServletRequest request,
            HttpServletResponse response) throws Throwable {
        int num=0,ref=1,re_step=0,re_level=0;
        try{
            if(request.getParameter("num")!=null){
                num=Integer.parseInt(request.getParameter("num"));
                ref=Integer.parseInt(request.getParameter("ref"));
                re_step=Integer.parseInt(request.getParameter("re_step"));
                re_level=Integer.parseInt(request.getParameter("re_level"));           
            }
        }catch(Exception e){e.printStackTrace();}
        request.setAttribute("num", new Integer(num));
        request.setAttribute("ref", new Integer(ref));
        request.setAttribute("re_step", new Integer(re_step));
        request.setAttribute("re_level", new Integer(re_level));
       
        return "writeForm.jsp";
    }
}

-------------------------------------------------------/WebContent/writeForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="/view/color.jspf" %>

<!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=EUC-KR">
<title>글쓰기</title>
</head>
<body bgcolor="${bodyback_c}">
<center><b>글쓰기</b></center>
<br>
<form method="post" name="writeform" action="/mvc2bbs/writePro.do">
<input type="hidden" name="num" value="${num}">
<input type="hidden" name="ref" value="${ref}">
<input type="hidden" name="re_step" value="${re_step}">
<input type="hidden" name="re_level" value="${re_level}">

<table width="400" border="1">
<tr>
 <td align="right" colspan=2 bgcolor="${value_c}">
     <a href="/mvc2bbs/list.do">글목록</a></td>
</tr>
<tr>
 <td bgcolor="{$value_c}">이름</td>
 <td><input type="text" name="writer"></td>
</tr>
<tr>
 <td bgcolor="{$value_c}">제목</td>
 <td><input type="text" name="subject"></td>
</tr>
<tr>
 <td bgcolor="{$value_c}">이메일</td>
 <td><input type="text" name="email"></td>
</tr>
<tr>
 <td bgcolor="{$value_c}">내용</td>
 <td><textarea name="content" rows="" cols=""></textarea></td>
</tr>
<tr>
 <td bgcolor="{$value_c}">비밀번호</td>
 <td><input type="password" name="passwd"></td>
</tr>
<tr>
 <td colspan=2 bgcolor="{$value_c}">
 <input type="submit" value="글쓰기">
 <input type="reset" value="취소">
 <input type="button" value="목록보기"
                           onClick="window.location='/mvc2bbs/list.do'">
 </td>
</tr>
</table>
</form>
</body>
</html>

-----------------------------------------------------/WebContent/view/color.jspf
<c:set var="bodyback_c" value="#e0ffff"/>
<c:set var="back_c" value="#8fbc8f"/>
<c:set var="title_c" value="#5f9ea0"/>
<c:set var="value_c" value="#b0e0e6"/>
<c:set var="bar" value="#778899"/>

 

[커맨드패턴]


- 서블릿에서 사용자의 요청을 명령어 전달

- 사용자가 어떤 요청을 했는지 판단하기 위한 가장 일반적인 방법이 명령어로 사용자의 요청을 전달하는 것이다.
  예를 들어, 글목록 명령, 글삭제 명령

- 요청 파라미터로 명령어를 전달하는 방법
  http://localhost:9090/mvc/servlet/Controller?command=Message

- 요청 URI자체을 명령어로 사용하는 방법
  http://localhost:9090/mvc/control/test.do


예제)

/ch1/loginForm.jsp--------------
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
 
<!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=EUC-KR">
<TITLE> ch1/loginForm.jsp</TITLE>
</HEAD>

<BODY>

<form name="frm" method="post" action="../control.do">
   아이디 : <input type="text" name="id" /><br/>
   비번 : <input type="password" name="pw" /><br/>
   <input type="submit" value="확인" />
</form>

</BODY>
</HTML>


ControllerServlet.java----------
package ch1;

import java.io.IOException;
import java.io.PrintWriter;

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

public class ControllerServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
       
        String id=HangulConversion.toKor(req.getParameter("id"));       
        String pw=HangulConversion.toKor(req.getParameter("pw"));       
        resp.setContentType("text/html;charset=euc-kr");
        PrintWriter out=resp.getWriter();
        out.write("<html>");
        out.write("<body>");
        out.write("아이디 :"+id);
        out.write("<br/>");
        out.write("비번 : "+pw);
        out.write("</body>");       
        out.write("</html>");
        out.close();
               
    }
}


/WEB-INF/web.xml------------
  <servlet>
    <servlet-name>control</servlet-name>
    <servlet-class>ch1.ControllerServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
     <servlet-name>control</servlet-name>
     <url-pattern>/control.do</url-pattern>
  </servlet-mapping>


한글처리))))
HangulConversion.java---------
package ch1;

public class HangulConversion {
    public static String toEng (String ko)  {
        if (ko == null) {
            return null;
        }
       
        try {
            return new String(ko.getBytes("euc-kr"),"8859_1");
        } catch(Exception e) {
            return ko;
        }
    }

    public static String toKor (String en) {
        if (en == null) {
            return null;
        }
        try {
                return new String (en.getBytes("8859_1"), "euc-kr");
        } catch(Exception e) {
            return en;
        }
    }
}

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

예제)))
http://localhost:9090/mvc/form.do 명령어에 의해  loginForm.jsp 호출

FormController.java-------------
package ch2;

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 FormController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
       
        RequestDispatcher dispatcher=req.getRequestDispatcher("ch2/loginForm.jsp");
        dispatcher.forward(req, resp);
    }
}


/ch2/loginForm.jsp--------------
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
 
<!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=EUC-KR">
<TITLE> ch2/loginForm.jsp</TITLE>
</HEAD>

<BODY>

<form name="frm" method="post" action="read.do">
   아이디 : <input type="text" name="id" /><br/>
   비번 : <input type="password" name="pw" /><br/>
   <input type="submit" value="확인" />
</form>

</BODY>
</HTML>

web.xml-------------------------
  <servlet>
    <servlet-name>form</servlet-name>
    <servlet-class>ch2.FormController</servlet-class>
 </servlet>
 
 <servlet-mapping>
   <servlet-name>form</servlet-name>
   <url-pattern>/form.do</url-pattern>
 </servlet-mapping>

 

ReadController.java----------------
package ch2;

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 ch1.HangulConversion;

public class ReadController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
       
        String id=HangulConversion.toKor(req.getParameter("id"));       
        String pw=HangulConversion.toKor(req.getParameter("pw"));
       
         RequestDispatcher dispather=
                 req.getRequestDispatcher("ch2/read.jsp");
         req.setAttribute("id", id);
         req.setAttribute("pw", pw);
         dispather.forward(req, resp);
    }
}

/ch2/read.jsp------------------------
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
 
<!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=EUC-KR">
<TITLE> ch2/read.jsp</TITLE>
</HEAD>

<BODY>

<p>당신의 아이디 : ${requestScope.id} 입니다</p>
<p>당신의 비번 : ${requestScope.pw} 입니다</p>

</BODY>
</HTML>


예제))))로그아웃
/ch2/loginForm.jsp-------------
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
 
<!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=EUC-KR">
<TITLE> ch2/loginForm.jsp</TITLE>
</HEAD>

<BODY>
<!--
<form name="frm" method="post" action="read.do">
 -->
 
 <form name="frm" method="post" action="login.do">
   아이디 : <input type="text" name="id" /><br/>
   비번 : <input type="password" name="pw" /><br/>
 <input type="submit" value="확인" />
</form>

</BODY>
</HTML>


LoginProController.java----------------
package ch2;

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 LoginProController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
       
        RequestDispatcher dispather=req.getRequestDispatcher("ch2/logout.jsp");
        String id=req.getParameter("id");
        String pw=req.getParameter("pw");
        if(id.equals("user") && pw.equals("1234")){
            req.setAttribute("id", id);
            req.setAttribute("pw", pw);
            dispather.forward(req,resp);
        }else{
            resp.sendRedirect("ch2/loginForm.jsp");
        }
       
    }
}

/ch2/logout.jsp----------------------
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
 
<!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=EUC-KR">
<TITLE> /ch2/logout.jsp</TITLE>
</HEAD>

<BODY>

<p>${requestScope.id} 님 로그아웃</p>

</BODY>
</HTML>


web.xml-----------------------
<servlet>
  <servlet-name>login</servlet-name>
  <servlet-class>ch2.LoginProController</servlet-class>
</servlet>

<servlet-mapping>
 <servlet-name>login</servlet-name>
 <url-pattern>/login.do</url-pattern>
</servlet-mapping>

 

 

 

 

 

 

 

 

-------------------------------------------------[모델 1]
- 웹브라우저의 요청(request)을 받아들이고, request.getParameter()
   웹브라우저에 응답(response)해 주는 처리에 대해 단독으로 처리하는 구조
- 간단한 웹어플리케이션을 구축할 때 적당하다
- 장점:단순한 페이지 흐름으로 인해 개발 기간이 단축된다
- 단점:웹어플리케이션이 복잡해 질수록 유지 보수가 힘들다
- 모델1방식에서 서블릿을 이용해서 웹페이지를 구축할 수 있으나
   사용방식 복잡하기 때문에 활용도가 많이 낮았다.
   javax.servlet.http.HttpServlet;
   javax.servlet.http.HttpServletRequest;
   javax.servlet.http.HttpServletResponse;
   method=get   : doGet()
   method=post  : doPost()

- 서블릿의 방식이 복잡하기 때문에 개발자가 웹에서 쉽게 접근할수 있도록
   별도로 고안된 서버스크립트언어(.jsp)가 만들어 졌다.

 

-----------------------------------------------------[모델2]
- 컨트롤 컴포넌트 : 요청(request)처리, 데이터접근, 비지니스 로직
- 뷰 컴포넌트 : 뷰는 어떠한 처리 로직도 포함하고 있지 않다.
- 사용자의 요청의 진입점은 컨트롤러의 역할을 하는 서블릿이 담당하고
   모든 흐름을 통제한다.
- 장점:비즈니스 로직과 뷰의 분리로 인해 어플리케이션이 명료해 지고,
          유지보수와 확장이 용이하다
- 단점:MVC구조에 대한 개발자들의 이해가 필요해서
          개발자의 높은 수준이 요구된다.
- 유지보수와 확장을 용이하게 하기위해서 새로운
   MVC2기반의 기술(프레임워크)이 계속 출시되고 있다.
   예를들어) spring, myBatis, struts2, struts1 (기본MVC방식과 거의 동일)

 


예제) 서블릿을 이용해서 사용자가 요청한 자료 처리하기

 

RequestDispatcher
- 클라이언트로부터 요청(request)을 받고, 그것을 서버상의
   어떤 리소스(Servlet, HTML, JSP 페이지)로 보내는 작업을 할때 사용한다.
- 사용자의 원래 요청을 다른 서블릿이나 JSP페이지 등과
   같은 다른 동적 웹 자원으로 전달한다.


* 작성순서
1) MessageController.java
2) WebContent/control/messageView.jsp

 

* 결과확인
http://localhost:9090/mvc2Test/servlet/part.control.MessageController

http://localhost:9090/mvc2Test/servlet/part.control.MessageController?message=happy

http://localhost:9090/mvc2Test/servlet/part.control.MessageController?message=base

http://localhost:9090/mvc2Test/servlet/part.control.MessageController?message=sky

 

-----------------------------------------------------[커맨드패턴]
- 명령어 유형
- 서블릿에서 사용자의 요청을 명령어 전달
- 사용자가 어떤 요청을 했는지 판단하기 위한
   가장 일반적인 방법이 명령어로 사용자의 요청을 전달하는 것이다.
   예를 들어, 글목록 명령, 글삭제 명령
- 1) 요청 파라미터로 명령어를 전달하는 방법
      http://localhost:9090/mvc/servlet/Controller?command=Message
- 2) 요청 URI자체을 명령어로 사용하는 방법
       http://localhost:9090/mvc/control/write.do
       http://localhost:9090/mvc/control/list.do
       http://localhost:9090/mvc/control/update.do
       http://localhost:9090/mvc/control/delete.do


예제) 요청 파라미터로 명령어를 전달하는 방법
        http://localhost:9090/mvc2Test/servlet/Controller?command=Message

 

----------------------------------------------------작성순서
1) 명령어의 목록 파일 작성하기
    /WEB-INF/Command.properties

2) CommandProcess.java 작성
  - 인터페이스. 명령어 메뉴 나열. 매니저 클래스역할
  - 서블릿으로부터 명령어의 처리를 지시받아 해당 명령에 대한 작업을 처리하고
     작업결과를 서블릿으로 리턴한다.
  - 실제로 작업을 처리하는 것은 구현클래스가 수행

3) MessageProcess.java
  - 명령어 처리 클래스

4) Controller.java
  - 비지니스 로직 부분

5) web.xml
  <!-- 서블릿 매핑하기 -->
  <servlet>
    <servlet-name>해당클래스 네임스페이스</servlet-name>
    <servlet-class>패키지명을포함한 클래스명</servlet-class>
   
    <init-param>
       <param-name>명령어 목록 파일 네임스페이스</param-name>
       <param-value>명령어 목록 파일(물리적이름 절대경로)</param-value>
    </init-param>
  </servlet>

6) /control/process.jsp

 

 

'..열심히 공부하세.. > MVC' 카테고리의 다른 글

[07] MVC2패턴 게시판 - ① 쓰기  (0) 2012.06.26
[06] 서블릿 요청 커맨드 패턴 (~~~.do)  (0) 2012.06.23
[04] 서블릿 작동원리 및 기초  (0) 2012.06.20
[03] 커스텀태그  (0) 2012.06.19
[02] JSTL  (0) 2012.06.19

+ Recent posts