[WEB] 톰캣 설정파일을 사용한 DB연결

|
지금까지는 JSP를 처음으로 배울 때 사용했던 DB연결 방식만을 사용해왔다.

그때문에 pool.jocl을 사용한 연결방식과 최범균씨의 madvirus소스까지도 진행하는 프로젝트에 그대로

들어가게 되었다.

다른 방식의 DB연결을 해보고 싶었고, 검색을 하던 중 시도하기에 적절한 방법을 찾았다.

아직 몇가지의 연결방식이 존재하고 또 어떤 방식이 가장 효과적인지는 잘 모르겠다.

앞으로 여러 시도를 해보면서 찾아나가야지.

server.xml에 context라는 태그를 추가하여 사용하는 것인데, 현재 쓰는 톰캣 버전인 6.0에는

context.xml이 이미 존재하기에 여기에 해당하는 내용을 넣고 테스트 한 결과 연결이 잘 되었다.

<Context docBase="/webapps/getDB" path="/getDB">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
        <Resource 
                  name="jdbc/TestDB" 
                  auth="Container" 
                  type="javax.sql.DataSource"
                  maxActive="100" 
                  maxIdle="30" 
                  maxWait="10000"
                  username="root" 
                  password="" 
                  driverClassName="com.mysql.jdbc.Driver"
                  url="jdbc:mysql://127.0.0.1:3307/test2?autoReconnect=true"/>
</Context>


이것이 context 내부에 작성한 내용이다. 이전에는 pool.jocl에 이와 같은 내용이 들어가던 것을 이제는

서버 자체에 설정하고 사용한다.



다음은 web.xml에 설정한 내역이다.

  <resource-ref>
      <description>MySQL Datasource</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
 </resource-ref>


context에 적어준 resource명을 가져옴으로서 사용할 수 있다.




다음은 jsp 소스이다.

<%@ page import="javax.naming.*, javax.sql.*, java.sql.*"%>

<%@ page language="java" contentType="text/html; charset=EUC-KR" %>

<%

 

      Connection con   = null;

      PreparedStatement stmt  = null;

 

 

      Context   initCtx = new InitialContext();

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

// resource명과 res-ref-name과 일치하는 이름
      
DataSource   ds = (DataSource)envCtx.lookup("jdbc/TestDB");
 

 

 con    = ds.getConnection();

 String msg = "disconnection";

 if(con != null){

  msg = "connection";

 }

%>

 <html>

  <head>

    <title>DB Test</title>

  </head>

  <body>

  <h2>Results = <%=msg %></h2>

  </body>

</html>


이와 같은 JSP 페이지를 tomcat 서버를 스타트하여 실행하면, connection이라는 문자가 DB와 이상없이

연결되었음을 표시해준다.

다른 방법들도 더 찾아보고 실습을 통해 익혀나가야 겠다. 이번에 사용해본 방법도 이전의 pool.jocl에

비해 훨씬 더 간편하고 깔끔한 것 같은데 다른방법들도 기대가 된다.

'WEB' 카테고리의 다른 글

[WAS] DBCP resource파라미터의 의미 및 설정  (0) 2011.09.08
[WAS] 프로젝트별 server.xml 설정  (0) 2011.09.05
And
prev | 1 | ··· | 25 | 26 | 27 | 28 | next