데이터베이스 드라이버 로드
Class.forName("오라클 이름");
액세스 db인 경우 : sun.jdbc.odbc.jdbcOdbcDriver
데이터베이스 연결
Connection con = DriverManager.getConnection(JDBC_url, "아이디", "비밀번호");
여기서, url과 아이디, 비밀번호는 각 Oracle 설치환경, 아이디 비밀번호가 다르므로 설정을 잘해줘야 한다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*" %>
<%
request.setCharacterEncoding("UTF-8");
Connection conn = null;
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
Boolean connect = false;
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, "hr", "hr");
connect = true;
conn.close();
} catch (Exception e)
{
connect = false;
e.printStackTrace();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test.jsp</title>
</head>
<body>
<% if(connect == true){%>
연결되었습니다.
<%} else if(connect == false){%>
연결되지 않았습니다..
<%}%>
<%
%>
</body>
</html>
일반 JSP에서 Oracle 연결을 해보았다면 이렇게 나오고.
성공적으로 연결 되었다면, "연결되었습니다."가 출력된다.
그러나 이렇게 되면, 나의 오라클 서버, ID, PASSWORD가 공개되는 단점이 생긴다.
그래서 이 점을 보안하기 위해서는 아래와 같이 다시 세분화를 시켜야 한다.
1. <META-INF> 안에 Context.xml을 만들어서 아래와 같이 코딩을 해 준 준다.
<Context>
<Resource name="jdbc/OracleDB"
auth="Container"
driverClassName="oracle.jdbc.driver.OracleDriver"
type="javax.sql.DataSource"
url="jdbc:oracle:thin:@localhost:1521:xe"
username="hr"
password="hr"
maxActive="20"
maxIdle="10"
maxWait="-1" />
</Context>
2. <WEB-INF> 안에 Web.xml을 수정한다.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>JdbcTest</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>
<resource-ref>
<description>Connection</description>
<res-ref-name>jdbc/OracleDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
위에 resource코드를 건드려서 resource를 생성한 후,
Context.xml에 맞춘 name은 동일하게 만들어준다.
3. JSP에서 아래와 같이 코드를 만든다.
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%
Connection conn = null;
try {
Context init = new InitialContext();
DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/OracleDB");
conn = ds.getConnection();
out.println("<h3>연결되었습니다.</h3>");
} catch (Exception e) {
out.println("<h3>연결에 실패하였습니다.</h3>");
e.printStackTrace();
}
%>
JSP에서 이렇게 만들면 연결이 되고 끝났음을 확인할 수가 있다.
아까보다 코드가 간결해지면서, 중요한 자료가 가려지는 것은 덤이다.
앞으로 Connect와 xml 설정만 있다면, 손쉽게 Oracle을 연결하기 간편해질 것이다.
반응형