1. 웹 어플리케이션 구동 시 JDBC 드라이버 로딩하기

Class.forName(jdbcDriverClass);

: 톰캣과 같은 웹 컨테이너가 시작될 때 자동으로 JDBC 드라이버를 로딩하도록 지정하면 JSP 페이지에서 매번 JDBC 드라이버(상위)를 로딩할 필요가 없음 → 서블릿 클래스 사용

 

- MySQLDriverLoader

package jdbc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class MySQLDriverLoader extends HttpServlet {
	@Override
	public void init(ServletConfig config) throws ServletException {
		try {
			//1. jdbc 드라이버 로딩
			Class.forName("com.mysql.jdbc.Driver");
		} catch(Exception ex) {
			throw new ServletException(ex);
		}
	}
}

 

- web.xml

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

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
		http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
		version="3.1">

	<servlet>
		<servlet-name>mysqlDriverLoader</servlet-name>
		<servlet-class>jdbc.MySQLDriverLoader</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
</web-app>

+ Recent posts