Context Listener

28822 ワード

接続オブジェクトは、テンプレートごとに実行されません.
共有するメンバーdaoオブジェクトを作成することが望ましい
AppInitSerbeltを使用せずにListenerを変更する
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_3_1.xsd" version="3.1">
  <display-name>_12_JDBCServlet_ServletInitParam</display-name>
  
  
  <!-- 컨텍스트 초기화 매개변수(모든 서블릿에서 공유가능) -->

  	<context-param>
  		<param-name>driver</param-name>
  		<param-value>com.mysql.cj.jdbc.Driver</param-value>
  	</context-param>
  	<context-param>
  		<param-name>url</param-name>
  		<param-value>jdbc:mysql://localhost/studydb?serverTimezone=UTC</param-value>
  	</context-param>
  	<context-param>
  		<param-name>username</param-name>
  		<param-value>study</param-value>
  	</context-param>
  	<context-param>
  		<param-name>password</param-name>
  		<param-value>study</param-value>
  	</context-param>
  	
  	
  	<!-- 서블릿 선언 주소와 매핑하지 않는다. 외부에 의해서 호출되지 않고 시작하자마자 실행되는 서블릿이기 때문이다.  -->
  <!-- 	주소와 매핑을 안해서 브라우저 요청에 의해서 호출되는 것이 아니라 
  	웹어플리케이션이 시작하면 최초로 실행되는 서블릿이다. -->
<!--   	<servlet>
  		<servlet-name>AppInitServlet</servlet-name>
  		<servlet-class>spms.servlets.AppInitServlet</servlet-class>
  		
  		시작하면 1순위로 올려라. 1순위가 여러개면 위에서부터 아래 순서대로 호출 
  		<load-on-startup>1</load-on-startup>
  	</servlet>
 -->
 
<!-- 웹 어플리케이션 시작/종료 이벤트 리스너  -->

<listener>
	<listener-class>spms.listeners.ContextLoaderListener</listener-class>
</listener>


<!-- Servlet 2.4이전에는 '컨텍스트 초기화 매개변수' 다음에 위치해야 한다 
			 2.4 이상부터는 순서에 관계 없다  -->
  <!--  필터 설정  -->
  <filter>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<filter-class>spms.filters.CharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
 
 
 <!-- 모든 주소에 필터를 적용 --> 
  <filter-mapping>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<!-- 들어오는 모든 것에 이 필터를 적용 (특정 주소만 주면 그 주소만 ) -->
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  
  <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>
</web-app>
ContextLoaderListener
package spms.listeners;

import java.sql.Connection;
import java.sql.DriverManager;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import spms.dao.MemberDao;

public class ContextLoaderListener implements ServletContextListener {	
	Connection conn;
	
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		try {
			System.out.println("contextDestroyed");
		}catch(Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		try {
			System.out.println("contextInitialized");
			ServletContext sc = sce.getServletContext();
			Class.forName(sc.getInitParameter("driver"));
			
			conn = DriverManager.getConnection(
					sc.getInitParameter("url"),
					sc.getInitParameter("username"),
					sc.getInitParameter("password"));
			
			MemberDao memberDao = new MemberDao();
			memberDao.setConnection(conn);
			
			//conn객체 대신 memberDao 객체를 공유 
			sc.setAttribute("memberDao", memberDao);
											
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		
		
	}

}
すべてのservletコードを
package spms.servlets;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import spms.dao.MemberDao;

@SuppressWarnings("serial")
@WebServlet("/member/delete")
public class MemberDeleteServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			ServletContext sc = this.getServletContext();
			MemberDao memberDao = (MemberDao)sc.getAttribute("memberDao");

			memberDao.delete(Integer.parseInt(request.getParameter("no")));

			response.sendRedirect("list");

		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", e);
			RequestDispatcher rd = request.getRequestDispatcher("/Error.jsp");
			rd.forward(request, response);

		} 

	}
}