본문 바로가기

Programing/Struts

Struts 환경에서 DBCP 사용하기와 Model사용하기

이제는 직접 Database와 연결하는 프로그램을 작성해 보자!

그러기 위해서는 다음과 같은 환경 설정이 필요하다

1) http://commons.apache.org/

위로 접속하여 jakarta에서 제공하는 DBCP pool, Collections를 차례로 다운 받은 후 압축을 풀어 commons-dbcp-X.X.X.jarcommons-pool-X.X.jar, commons-collections-X.X.jar라는 파일들을 사용하는 Context/lib에 복사해 두자!

 

2) struts-config.xml문서에 있는 <data-sources/> 부분을 다음과 같이 수정하자

   <data-sources>

<data-source key="oracle" type="org.apache.commons.dbcp.BasicDataSource">

<set-property property="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

             <set-property property="username" value="scott" />

             <set-property property="password" value="tiger" />

             <set-property property="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />

             <set-property property="maxActive" value="50" />

             <set-property property="maxIdle" value="10000" />

             <set-property property="maxWait" value="100" />

             <set-property property="defaultAutoCommit" value="true" />

</data-source>

  </data-sources>

 

3) 다음은 Action요소 추가

  <action path="/db" forward="/dbForm.jsp"/>

<action path="/dbTest" type="st1.DB_Action"/>

 

4) dbForm.jsp문서 작성

  <%@ page contentType="text/html;charset=utf-8"%>

<HTML>

<HEAD>

             <TITLE> New Document </TITLE>

             <style type="text/css">

                           input,textarea,select {background-color:#ffd700;border:1 solid #d2691e;color:#4b0082};

                           .ff{background-color:#ffcc33};

                           .fa{background-color:#fae78b};

             </style>

</HEAD>

 

<BODY>

             <form method="post" action="dbTest.st">

                           <table width="450" cellspacing="0" cellpadding="4" border="1"

                                        bordercolordark="#cc9900" bordercolorlight="#ffff66">

                                        <tr>

                                                     <td width="25%" align="center" class="ff">

                                                                  <font size="2"><b>이름</b></font>

                                                     </td>

                                                     <td class="fa">

                                                                  <input type="text" name="name">

                                                     </td>

                                        </tr>

                                        <tr>

                                                     <td align="center" class="ff">

                                                                  <font size="2"><b>ID</b></font>

                                                     </td>

                                                     <td class="fa">

                                                                  <input type="text" name="id">

                                                     </td>

                                        </tr>

                                        <tr>

                                                     <td align="center" class="ff">

                                                                  <font size="2"><b>Password</b></font>

                                                     </td>

                                                     <td class="fa">

                                                                  <input type="password" name="pwd" maxlength="12" size="15">

                                                     </td>

                                        </tr>

                                        <tr>

                                                     <td width="25%" align="center" class="ff">&nbsp;</td>

                                                     <td class="fa">

                                                                  <input type="submit" value="정보 보내기">

                                                                  <input type="reset" value="다시 입력">

                                                     </td>

                                        </tr>

                           </table>

             </form>

</BODY>

</HTML>

 

5) Action작성

package st1;

import! org.apache.struts.action.*;

import! javax.servlet.http.*;

import! javax.sql.*;

import! java.sql.*;

public class DB_Action extends Action{

             public ActionForward execute(ActionMapping mapping,

               ActionForm form,

               HttpServletRequest req,

               HttpServletResponse response) throws Exception{

                          

                           DataSource dataSource = null;

                           Connection con = null;

                           PreparedStatement pst = null;

 

                           String s_name = req.getParameter("name");

                           String s_id = req.getParameter("id");

                           String s_pwd = req.getParameter("pwd");

                           try {

                                        dataSource = getDataSource(req,"oracle");

                                        con = dataSource.getConnection();

 

                                        pst = con.prepareStatement("insert into strutsTest1_T values(?,?,?)");

 

                                        pst.setString(1,s_name);

                                        pst.setString(2,s_id);

                                        pst.setString(3,s_pwd);

                                        pst.executeUpdate();

 

                           } catch (Exception e) {

                                        e.printStackTrace();

                           } finally {

                                        try {

                                           if(pst != null)

                                                        pst.close();

                                           if(con != null)

                                                        con.close();

                                        } catch (SQLException e) {}

                           }

                           return null;

             }

}

6) 오라클에서 테이블 생성

 SQL> create table strutsTest1_T(

  2  name varchar2(10),

  3  id varchar2(10),

  4  pwd varchar2(10));

 

 

 

2) Model 적용

다음은 스트럿츠 환경에는 사실 들지 않지만 개발력에 있어 절대 그냥 넘어가지 못하는 Model구조를 적용하여

예제를 만들어 보자!

DB작업과 같은 비즈니스 로직 또는 정보의 유지를 위한 Persistence계층을 묶어 우린 모델 영역이라 한다.


사용자 삽입 이미지

위의 그림은 모델을 활용하는 Struts의 간단한 흐름도이다. 자~~~~이제

예제로 익혀보자!

 

 

1) 입력 페이지 in_data.jsp

 

<%@ page contentType="text/html;charset=utf-8"%>

<HTML>

<HEAD>

             <TITLE> New Document </TITLE>

             <style type="text/css">

             input,textarea,select{background-color:#ffd700;border:1 solid #d2691e;color:#4b0082};

             .ff{background-color:#ffcc33};

             .fa{background-color:#fae78b};

             </style>

</HEAD>

 

<BODY>

             <form method="post" action="insert.st">

                           <table width="450" cellspacing="0" cellpadding="4" border="1"

                             bordercolordark="#cc9900" bordercolorlight="#ffff66">

                                        <tr>

                                                     <td width="25%" align="center" class="ff">

                                                                  <font size="2"><b>이름</b></font>

                                                     </td>

                                                     <td class="fa">

                                                                  <input type="text" name="name">

                                                     </td>

                                        </tr>

                                        <tr>

                                                     <td align="center" class="ff">

                                                                  <font size="2"><b>ID</b></font>

                                                     </td>

                                                     <td class="fa">

                                                                  <input type="text" name="id">

                                                     </td>

                                        </tr>

                                        <tr>

                                                     <td align="center" class="ff">

                                                                  <font size="2"><b>Password</b></font>

                                                     </td>

                                                     <td class="fa">

                                                                  <input type="password" name="pwd" maxlength="12" size="15">

                                                     </td>

                                        </tr>

                                        <tr>

                                                     <td width="25%" align="center" class="ff">&nbsp;</td>

                                                     <td class="fa">

                                                                  <input type="submit" value="정보 보내기">

                                                                  <input type="reset" value="다시 입력">

                                                     </td>

                                        </tr>

                           </table>

             </form>

</BODY>

</HTML>

 

 

2) 성공시 표현될 페이지 result_succ.jsp

 

<%@ page contentType="text/html;charset=utf-8" %>

입력성공!!

 

 

3) 실패시 표현될 페이지 result_fail.jsp

 

<%@ page contentType="text/html;charset=utf-8" %>

입력실패!!

 

 

4) ActionForm객체

 

package st1;

import! org.apache.struts.action.*;

public class DataForm extends ActionForm {

             private String name,id,pwd;

 

             public void setName(String n){

                           name = n;

             }

             public void setId(String n){

                           id = n;

             }

             public void setPwd(String n){

                           pwd = n;

             }

 

             public String getName(){

                           return name;

             }

             public String getId(){

                           return id;

             }

             public String getPwd(){

                           return pwd;

             }

}

 

 

5) Action객체

 

package st1;

import! org.apache.struts.action.*;

import! javax.servlet.http.*;

import! javax.sql.*;

import! java.sql.*;

public class InsertAction extends Action{

             static DataSource dataSource;

             public ActionForward execute(ActionMapping mapping,

               ActionForm form,

               HttpServletRequest req,

               HttpServletResponse response) throws Exception{

                          

                           if(dataSource == null)

                                        dataSource = getDataSource(req,"oracle");

 

                           DataForm d = (DataForm)form;

                           DB_Manager manager = DB_Manager.getInstance();

                          

                           if(manager.doInsert(d, dataSource))

                                        return mapping.findForward("success");

                           else

                                        return mapping.findForward("fail");

             }

}

 

 

6) 모델 객체(일단 저장 기능만..)

 

package st1;

 

import! java.sql.*;

import! javax.sql.*;

import! java.util.*;

import! javax.servlet.http.*;

 

public class DB_Manager {

             private static DB_Manager db_m;

            

             public static synchronized DB_Manager getInstance() {

        if ( db_m == null )

            db_m = new DB_Manager();

       

        return db_m;

    }

 

             public boolean doInsert( DataForm b,DataSource ds) throws Exception {

        Connection con = null;

        PreparedStatement pst = null;

               

        try {

                                        con = ds.getConnection();

 

                                        pst = con.prepareStatement("insert into strutsTest1_T values(?,?,?)");

 

                                        pst.setString(1,b.getName());

                                        pst.setString(2,b.getId());

                                        pst.setString(3,b.getPwd());

                                        pst.executeUpdate();

                                        return true;

                           } catch (Exception e) {

                                        e.printStackTrace();

                           } finally {

                                        try {

                                           if(pst != null)

                                                        pst.close();

                                           if(con != null)

                                                        con.close();

                                        } catch (SQLException e) {}

                           }

                           return false;

    }

}

 

 

7) struts-congif.xml 수정

 

  <form-beans>

    <form-bean name="data_form" type="st1.DataForm"/>  ß추가 부분

</form-beans>

그리고 action-mappings 부분에서 다음과 같이 추가

<action path="/in_d" forward="/in_data.jsp"/>

        <action         

            path="/insert"

            type="st1.InsertAction"

            name="data_form"                       

            validate="false">

            <forward name="success" path="/result_succ.jsp" redirect="false"/>

            <forward name="fail" path="/result_fail.jsp" redirect="false"/>

        </action>

 

테이블 스키마는 앞선 예제의 strutsTest1_T를 그대로 사용하였다.

'Programing > Struts' 카테고리의 다른 글

하나의 Context에서 여러개의 Struts환경 구현하기  (0) 2008.07.29
한글처리  (0) 2008.07.29
ActionServlet과 ActionForm을 알아보자!  (1) 2008.07.29
Action에 대하여  (0) 2008.07.29
Struts환경 설정 및 예제1  (2) 2008.07.29