국비지원학원/HTML,JavaScript,jQ

90일차-JavaEE_popup/DBCP

초코맛 2019. 3. 12. 01:20
반응형
 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 접속자의 정보를 수집하는 코드(로그 분석) -->
<script type="text/javascript">
window.onload=function(){
     location.href="popup_cookie.do";/* href(뒤로가기됨) vs  replace(안됨) */
     /* .do를 주고,DD(web.xml)에.do로 하면 그렇게 뜨는것.. */
}//onload
</script>
</head>
<body>
</body>
</html>
package day0305;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class PopupBody extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        
          out.write("<!DOCTYPE html>\r\n");
          out.write("<html>\r\n");
          out.write("<head>\r\n");
          out.write("<meta charset=\"UTF-8\">\r\n");
          out.write("<title>Insert title here</title>\r\n");
          out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
          out.write("<style type=\"text/css\">\r\n");
          out.write("#wrap{ margin:0px auto; width:800px; height: 860px;  }\r\n");
          out.write("#header{  width:800px; height: 140px; background: #FFFFFF url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
          out.write("\t\t\tposition: relative; }\r\n");
          out.write("#headerTitle{ font-family: HY견고딕, 고딕; font-size: 30px; font-weight: bold;text-align: center;\r\n");
          out.write("\t\t\t\t\tposition: absolute; top:30px; left:290px}\r\n");
          out.write("#container{  width:800px; height: 600px; }\r\n");
          out.write("#footer{  width:800px; height: 120px; }\r\n");
          out.write("#footerTitle{ float:right; font-size: 15px; padding-top:20px; padding-right: 20px }\r\n");
          out.write("</style>\r\n");
          
          //쿠키가 존재 하고, 오늘 날짜와 같다면 팝업창을 띄우지 않는다.
          boolean popupFlag=false;
          
          //1.쿠키 읽기
          Cookie[] cookies=request.getCookies();
          if(cookies!= null) {//쿠키가 존재
              Cookie readCookie=null;
              for(int i=0; i<cookies.length; i++) {
                  readCookie=cookies[i];
                  
                  if("popup_date".equals(readCookie.getName())) {
                      String value=readCookie.getValue();
                      
                      String nowDate=new SimpleDateFormat("yyyyMMdd").format(new Date());
                      if(nowDate.equals(value)) {
                          popupFlag=true;
                      }//end if
                  }//end if
              }//end for
          }//end if
          
          
          out.println("<script type='text/javascript'>");
          out.println();
          out.println("window.onload=function(){");
          if(!popupFlag) {
              out.println("\twindow.open('day0305/popup.html','popup','width=725,height=550,top=100,left=50,right=10')");
          }//end if
          out.println("}//onload");
          out.println("</script>");
          
          out.write("</head>\r\n");
          out.write("<body>\r\n");
          out.write("<div\tid=\"wrap\">\r\n");
          out.write("\t<div id=\"header\">\r\n");
          out.write("\t\t<div id=\"headerTitle\">SIST Class4</div>\r\n");
          out.write("\t</div>\r\n");
          out.write("\t<div id=\"container\">\r\n");

          out.println("<h2>철권세상에 오셨습니다.</h2>");
          out.println("<img src='common/images/img.png' title='게임은 수업시간에 해야 제맛!!'><br/>");
          out.println("<h3>이번 주 정모는 강남역 지하 게임 센터에서 화요일 19:00시 부터 진행됩니다.</h3>");
          out.println("<h3>많은 참여 부탁 드립니다.</h3>");
          out.println("<img src='day0304/images/job.png'/>");
          
          
          
          
          out.write("\t</div>\r\n");
          out.write("\t<div id=\"footer\">\r\n");
          out.write("\t\t<div id=\"footerTitle\">copyright&copy; all right reserved. class 4 </div>\r\n");
          out.write("\t</div>\r\n");
          out.write("</div>\r\n");
          out.write("\r\n");
          out.write("</body>\r\n");
          out.write("</html>\r\n");
    
    }//doGet
}//class

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"  href="http://localhost:8080/html_prj/common/main_v190130.css"/>
<style type="text/css">
#wrap{margin:0px auto;width:725px; height:500px;}
#container{width:725px; height:470px; }
#footer{width:725px; height:30px; }
</style>
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
     $("#closeWin").click(function(){
           $("form").submit();
           //self.close();
     });//click
});//ready
</script>
</head>
<body>
<div id="wrap">
     <div id="container">
           <img src="../common/images/popup.jpg"/>
           <br/>
           3월 디잘잘배 철권대회 오픈!!<br/>
           일시 : 3월 8일 19:00시 부터 토너먼트 진행<br/>
           경품 : 1등-1일 사용 쿠폰, 2등-반나절  쿠폰, 3등-1시간 쿠폰<br/>
     </div>
     <div id="footer">
           <form action='../popup_close.do' name="frm">
           <input type="checkbox" name="popupFlag"/>오늘하루  그만보기
                <a href="#void" id="closeWin">닫기</a>
           </form>
     </div>
</div>
</body>
</html>
package day0305;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class PopupClose extends HttpServlet {
     protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           //checkbox에 value가 없을 때, 체크 박스를 선택하고  submit이 되면 "on"이
           //들어오고 체크박스를 선택하지 않고 submit되면 null이  입력된다.
           String  popupFlag=request.getParameter("popupFlag");//on/null
           //System.out.println(popupFlag);
           if(popupFlag != null) {//체크박스가 선텍된 경우 "on"
                
                //쿠키 심기 : 날짜를 가진 쿠키를 심어서 팝업창을  보여주지 않을 목적
                SimpleDateFormat sdf=new  SimpleDateFormat("yyyyMMdd");
                
                //1.쿠키 생성
                Cookie popupCookie=new Cookie("popup_date",  sdf.format(new Date()));
                //2.쿠키의 생존 시간
                popupCookie.setMaxAge(60*60*24);
                //3.쿠키 심기
                response.addCookie(popupCookie);
                
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out=response.getWriter();
                
                out.println("<script type='text/javascript'>");
                out.println("window.onload=function(){");
                out.println("self.close();");
                out.println("}//function");
                out.println("</script>");
                
           }//end if
     
     }//doGet
}//class

 

*init_param vs Context_param
: 둘다 DD에 설정하여 서블릿에 값을 전달하는 Node들 (web.xml에 정의)
장점 : 값이 클래스 밖에 있어 편의성/보안성 향상
(안에 있을땐 값이 변경되면 컴파일->deployee->Tomcat재실행 까지 해주어야 하지만) 값이 외부에 있으면 그냥 재실행(?)



*init_param
  • 특정 서블릿에만 값을 넣어 사용할 때 (정의한 부분에 만)
  • ServletConfig 객체를 사용하여 값을 얻는다.
  • 1.DD정의)
    • <servlet>
    •   <servlet-name>서블릿객체명</servlet-name>
    •   <servlet-class>패키지명.클래스명</servlet-class>
    •   <init-param>//이때 값은 String만 된다.
    •     <init-param> //(몇개든 만들 수 있다.)
    •       <param-name>이름</param-name>
    •       <param-value>값</param-value>
    •     </init-param>
    • </servlet>
  • 2.서블릿내에서 사용
    • 2-1.ServletConfig얻기
    • ServletConfig sc=getServletConfig();
    • //내가만든 Servlet은 ->HttpServlet->GenericServlet(부모)
    • 2-2.init-param이름을 얻기
    • Enumeration en =sc.getInitParameterNames();
    • while(en.hasMoreElements()){
    •     String name=en.nextElement();//이름을 얻을 수 있다.
    • }
    • 2-3.값 얻기
    • String value=sc.getInitParameter("이름");  //=>값은 String으로 
package day0305;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class UseInitParameter extends HttpServlet {
     protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out=response.getWriter();
           
           out.write("<!DOCTYPE html>\r\n");
           out.write("<html>\r\n");
           out.write("<head>\r\n");
           out.write("<meta charset=\"UTF-8\">\r\n");
           out.write("<title>Insert title here</title>\r\n");
           out.write("<link rel=\"stylesheet\"  type=\"text/css\"  href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
           out.write("<style type=\"text/css\">\r\n");
           out.write("#wrap{ margin:0px auto; width:800px;  height: 860px;  }\r\n");
           out.write("#header{  width:800px; height: 140px;  background: #FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
           out.write("\t\t\tposition: relative; }\r\n");
           out.write("#headerTitle{ font-family: HY견고딕, 고딕;  font-size: 30px; font-weight: bold;text-align: center;\r\n");
           out.write("\t\t\t\t\tposition: absolute; top:30px;  left:290px}\r\n");
           out.write("#container{  width:800px; height: 600px;  }\r\n");
           out.write("#footer{  width:800px; height: 120px;  }\r\n");
           out.write("#footerTitle{ float:right; font-size:  15px; padding-top:20px; padding-right: 20px }\r\n");
           out.write("</style>\r\n");
           out.write("</head>\r\n");
           out.write("<body>\r\n");
           out.write("<div\tid=\"wrap\">\r\n");
           out.write("\t<div id=\"header\">\r\n");
           out.write("\t\t<div id=\"headerTitle\">SIST  Class4</div>\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"container\">\r\n");
           //DD의 <init-param>에 설정된 값 얻기.
           //1.ServletConfig 얻기 (HttpServlet 으로 부터  얻는다.)=>코드의 재사용성
           ServletConfig sc=getServletConfig();
           //2.<init-param>의 모든 값들을 얻기
           Enumeration<String> en=sc.getInitParameterNames();
           out.println("<ul>");
           String nodeName="";
           while(en.hasMoreElements()) {
            nodeName=en.nextElement();
            out.print("<li> 노드명: <strong>");
            out.print(nodeName);
            out.print("</strong> 노드의 값 : ");
            out.print(sc.getInitParameter(nodeName));
            out.println("</li>");
           }//end while
           out.println("</ul>");
           
           
           out.println("<div  style='width:300px;height:200px;border:1px solid #333'>");
           //값 얻기
           out.print("<marquee>");
           out.print(sc.getInitParameter("name"));
           out.println("</marquee>");
           
           out.print("<strong>");
           out.print(sc.getInitParameter("addr"));
           out.println("</strong>");
           
           out.print("<mark>");
           out.print(sc.getInitParameter("birth"));
           out.println("</mark><br/>");
           
           out.println("<a href='use_dd_param'>init-param  정의하지 않은 서블릿</a>");
           out.println("</div>");
           
           
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"footer\">\r\n");
           out.write("\t\t<div  id=\"footerTitle\">copyright&copy; all right reserved. class 4  </div>\r\n");
           out.write("\t</div>\r\n");
           out.write("</div>\r\n");
           out.write("\r\n");
           out.write("</body>\r\n");
           out.write("</html>\r\n");
     }//doGet
}//class
package day0305;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class UseDDParam extends HttpServlet {
     protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out=response.getWriter();
           
           out.write("<!DOCTYPE html>\r\n");
           out.write("<html>\r\n");
           out.write("<head>\r\n");
           out.write("<meta charset=\"UTF-8\">\r\n");
           out.write("<title>Insert title here</title>\r\n");
           out.write("<link rel=\"stylesheet\"  type=\"text/css\"  href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
           out.write("<style type=\"text/css\">\r\n");
           out.write("#wrap{ margin:0px auto; width:800px;  height: 860px;  }\r\n");
           out.write("#header{  width:800px; height: 140px;  background: #FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
           out.write("\t\t\tposition: relative; }\r\n");
           out.write("#headerTitle{ font-family: HY견고딕, 고딕;  font-size: 30px; font-weight: bold;text-align: center;\r\n");
           out.write("\t\t\t\t\tposition: absolute; top:30px;  left:290px}\r\n");
           out.write("#container{  width:800px; height: 600px;  }\r\n");
           out.write("#footer{  width:800px; height: 120px;  }\r\n");
           out.write("#footerTitle{ float:right; font-size:  15px; padding-top:20px; padding-right: 20px }\r\n");
           out.write("</style>\r\n");
           out.write("</head>\r\n");
           out.write("<body>\r\n");
           out.write("<div\tid=\"wrap\">\r\n");
           out.write("\t<div id=\"header\">\r\n");
           out.write("\t\t<div id=\"headerTitle\">SIST  Class4</div>\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"container\">\r\n");
           //init-param : 다른 서블릿에서 사용할 수 없다.
           out.println("<div style='width:300px;  height:250px;border:1px solid #FF0000'>");
           out.println("<h2>다른 서블릿에 init-param사용</h2>");
           //1.ServletConfig 얻기
           ServletConfig sc=getServletConfig();
           out.print("<strong>이름</strong>");
           
           out.print("<mark>");
           out.print(sc.getInitParameter("name"));
           out.println("</mark><br/>");
           
           out.println("<a href='use_init_param'>init-param  정의 서블릿</a>");
           
           out.println("</div>");
           
           
           
           //context-param : 모든 서블릿에서 사용할 수 있다.
           out.println("<div style='width:300px;  height:250px;border:1px solid #0000FF'>");
           out.println("<h2>다른 서블릿에서  context-param사용</h2>");
           //1.ServletConfig 얻기
           ServletContext sc1=getServletContext();
           out.print("<strong>이름</strong>");
           out.print(sc1.getInitParameter("name"));
           out.println("<br/>");
           out.println("<a href='use_init_param'>다른  서블릿</a>");
           
           out.println("</div>");
           
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"footer\">\r\n");
           out.write("\t\t<div  id=\"footerTitle\">copyright&copy; all right reserved. class 4  </div>\r\n");
           out.write("\t</div>\r\n");
           out.write("</div>\r\n");
           out.write("\r\n");
           out.write("</body>\r\n");
           out.write("</html>\r\n");
           
     }//doGet
}//class


*Context_param
  • 모든 서블릿에서 값을 넣어 사용할 때(공통의 값)
  • ServletContext 객체를 사용하여 값을 얻는다.
  • DD정의)
    • <web-app> 내에 선언 (몇개든 만들 수 있다.)
    •   <context-param>
    •     <param-name>이름</param-name>
    •     <param-value>값</param-value>
    •   </context-param>
  • 서블릿 내에서 사용
    • 2-1. ServletContext
    • ServletContext sc=getServletContext();
    • 2-2. ContextParam 이름들 보기
    • Enumeration en =sc.getInitParameterNamess();
    • 2-3. 값 얻기
    • String value=sc.getInitParameter("이름");
//web.xml은 실행될때 주석을 지우기 때문에 쓰나 마나~~~
package day0305;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class UseContextParameter extends HttpServlet {
     protected void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException,  IOException {
           response.setContentType("text/html;charset=UTF-8");
           PrintWriter out=response.getWriter();
           
           out.write("<!DOCTYPE html>\r\n");
           out.write("<html>\r\n");
           out.write("<head>\r\n");
           out.write("<meta charset=\"UTF-8\">\r\n");
           out.write("<title>Insert title here</title>\r\n");
           out.write("<link rel=\"stylesheet\"  type=\"text/css\"  href=\"http://localhost:8080/servlet_prj/common/css/main_v190130.css\"/>\r\n");
           out.write("<style type=\"text/css\">\r\n");
           out.write("#wrap{ margin:0px auto; width:800px;  height: 860px;  }\r\n");
           out.write("#header{  width:800px; height: 140px;  background: #FFFFFF  url(http://localhost:8080/servlet_prj/common/images/header_bg.png) repeat-x;\r\n");
           out.write("\t\t\tposition: relative; }\r\n");
           out.write("#headerTitle{ font-family: HY견고딕, 고딕;  font-size: 30px; font-weight: bold;text-align: center;\r\n");
           out.write("\t\t\t\t\tposition: absolute; top:30px;  left:290px}\r\n");
           out.write("#container{  width:800px; height: 600px;  }\r\n");
           out.write("#footer{  width:800px; height: 120px;  }\r\n");
           out.write("#footerTitle{ float:right; font-size:  15px; padding-top:20px; padding-right: 20px }\r\n");
           out.write("</style>\r\n");
           out.write("</head>\r\n");
           out.write("<body>\r\n");
           out.write("<div\tid=\"wrap\">\r\n");
           out.write("\t<div id=\"header\">\r\n");
           out.write("\t\t<div id=\"headerTitle\">SIST  Class4</div>\r\n");
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"container\">\r\n");
           //모든 서블릿(이 프로젝트 내의!!)에서 사용할 수 있는  <context-param>의 사용
           //1.ServletContext 얻기
           ServletContext sc=getServletContext();
           //2.모든 이름 얻기
           Enumeration<String> en=sc.getInitParameterNames();
           
           out.println("<table border='1'>");
           out.println("<tr>");
           out.println("<th>파라메터 이름</th><th>파라메터  값</th>");
           out.println("</tr>");
           
           String nameNode="";
           while(en.hasMoreElements()) {
            nameNode=en.nextElement();
            out.println("<tr>");
            out.print("<td>");
            out.print(nameNode);
            out.println("</td>");
            out.print("<td>");
            out.print(sc.getInitParameter(nameNode));
            out.println("</td>");
            out.println("</tr>");
           }//end while
           out.println("</table>");
           out.println("<a href='use_dd_param'>다른  서블릿</a>");
           
           out.write("\t</div>\r\n");
           out.write("\t<div id=\"footer\">\r\n");
           out.write("\t\t<div  id=\"footerTitle\">copyright&copy; all right reserved. class 4  </div>\r\n");
           out.write("\t</div>\r\n");
           out.write("</div>\r\n");
           out.write("\r\n");
           out.write("</body>\r\n");
           out.write("</html>\r\n");
     
     }//doGet
}//class




*DBCP(DataBase Connection Pool)
  • JDBC의 불편함을 개선한 DB연동 방식//자동차를 가짐
  • JDBC의 불편함 : DB연동의 초기지연시간이 발생/Connection의 재사용성이 낮다.(장: 필요할 때만 연결을 유지(메모리 절약))////자동차 렌탈
          • =>사용자가 서비스를 받기 전에 들어가는 시간(1,2,3)
          • JDBC
          • 1.드라이버 로딩(.jar)->HDD
          • 2.Connection얻기  //가장 오래 걸림! DriverManager.getConnection(url,id,pass)->네트워크의 어딘가에 가서 커넥션을 물고 나와...
          • 3.쿼리문 실행 객체 얻기 //여기까지가 오래 걸린다->HDD
          • 4.쿼리문을 실행한 후 결과얻기 //사용자는 얘만 필요.
          • 5.연결 끊기 //진짜루 끊어짐->다음번엔 또 연결해야 함 (재사용성이 떨어짐)
  • 일정 갯수의 Connection을 미리 연결해 두고 필요할 때 꺼내서 사용하는 방식(초기 지연 시간이 줆->DB를 찾아가는 시간이 없기때문!)
  • 연결이 끊어진 Connection은 Pool로 들어가기 때문에 Connection의 재사용성이 향상된다.
  • 단점) DB연동을 사용하지 않아도 일정 갯수의 Connection을 연결하고 있기 때문에 메모리를 항상 사용한다.(근데 빨라
  • jar로 배포되는 경우와(찾아야) Container에서 제공하는 경우
            •  =>Tomcat기준
            • server.xml에 간단한 설정을 추가하여 사용할 수 있다.
  • 설정)  -DBCP가 필요한 Project의 <Context>에서 설정한다.
    • Context : HDD와 연결하게 해주는 Node??
    • <Context path="/브라우저에서 사용할 이름" docBase="HDD실제경로">
    •    <Resource name="jdbc/DBCP명".../>
    • //얘가 들어가면 tomcat이 만들어 준다 중요한건 name
    • </Context>
    • //Tomcat에 DBCP가 설정된다.
  • Java에서는 이름으로 객체를 찾아서 사용하는 JNDI(Java Naming & Directory Interface)기술이 사용 된다.
                • =>관련 클래스 : java.naming package에서 제공
                  • Context, InitialContext 사용
반응형