### : 목차 구분 기호
--- : 목차 내에 항목 구분 기호
@@@ : 태그 용도 
,,, : 같은 항목 내에 구분 기호

목차
1. 이론 및 정보
2. 설정 및 그 밖에
3. 소스코드 또는 실습
4. 과제

###################################
1. 이론 및 정보
-----------------------------------
* Enumeration 
열거형으로 자료를 배치
데이터를 순서대로 저장해 놓고
순서대로 뽑아다 쓰려는 목적
----------------------------------- 
* 절대경로 VS 상대 경로
~\JSP\ManualWork\ServletApp2\WEB-INF\web.xml 에서 
<url-pattern>/life.do</url-pattern>에 '/' 의 의미는 
http://localhost:8080/ServletApp2/ 까지의 경로를 의미하고

~.html에서 
<form action="/ServletApp2/life.do" method="post">
/ServletApp2/life.do의  맨처음 '/'는 http://localhost:8080/ 를 의미
그래서 ~\JSP\ManualWork\ServletApp2\html\index.html
에서 <url-pattern>/life.do</url-pattern> 로 가려면
../life.do  혹은 /ServletApp2/life.do 하면됨 
-----------------------------------
* HTTP 프로토콜의 특징
- 비연결지향성 : 연결이 되어있는 동안만 데이터를 유지, 요청했을때만 연결 되어 있음
-----------------------------------
###################################
2. 설정 및 그 밖에
-----------------------------------
~\JSP\ManualWork\ServletApp2 를 만듬
금일 수업 내용이 전부 들어 있음
----------------------------------- 
* 쿠키 확인 방법
IE : 개발자 도구 - 메뉴의 캐시 - 쿠키정보 보기 
크롬 : 개발자 도구 - Resource - Cookies - 도메인네임 
----------------------------------- 
###################################
3. 소스코드 또는 실습 
-----------------------------------
3-1
아래 내용을 수정
~\JSP\ManualWork\ServletApp1\WEB-INF\src\ServletTest4.java

package com.netsong7.servlet;

import javax.servlet.http.*;
import java.io.*;
public class ServletTest4 extends HttpServlet{
     protected void doGet(HttpServletRequest req, HttpServletResponse resp){
          //System.out.println("Get() Test...");
          doPost(req,resp);
     }
    
     protected void doPost(HttpServletRequest req, HttpServletResponse resp){
          //System.out.println("Post() Test...");
          /*
          try{
               resp.setCharacterEncoding("euc-kr");
               req.setCharacterEncoding("euc-kr");
               //req.setCharacterEncoding("utf-8");
              
               // text로 넘어온 값은 공백이라도 값이 전달 되어옴
               String[] singers = req.getParameterValues("singer");
              
               // checkbox는 넘어온 값이 공백이면 null이 전달됨
               String[] foods = req.getParameterValues("food");
               String[] cities = req.getParameterValues("city");
              
               PrintWriter out = resp.getWriter();
               out.println("<html><body>");
               out.println("<h2>당신이 좋아하는 가수입니다.</h2>");
               out.println("<ul>");
               for(int i=0;i < singers.length;i++){
                    out.println("<li>" + singers[i] + "</li>");
               }
               out.println("</ul>");
               out.println("<h2>당신이 좋아하는 음식 입니다.</h2>");
               out.println("<ul>");
              
               // 조건 처리가 안될 수도 있음, 이럴때에는 예외처리
               if(foods != null){
                    for(int i=0;i < foods.length;i++){
                         out.println("<li>" + foods[i] + "</li>");
                    }
               }
               out.println("</ul>");
               out.println("<h2>당신이 선택한 도시입니다.</h2>");
               out.println("<ul>");
               if(cities != null){
                    for(String str : cities){
                         out.println("<li>" + str + "</li>");
                    }
               }
               out.println("</ul>");
               out.println("</body></html>");
               out.close();
          }catch(IOException err){}
          */
         
          try{
               resp.setCharacterEncoding("euc-kr");
               req.setCharacterEncoding("euc-kr");
               java.util.Enumeration e = req.getParameterNames();
               PrintWriter out = resp.getWriter();
               out.println("<html><body>");
              
               while(e.hasMoreElements()){
                    // 전달 받은 변수를 전부 출력함
                    //System.out.println((String)e.nextElement());                   
                   
                    String param = (String)e.nextElement();
                    if(param != null){
                         String[] values = req.getParameterValues(param);
                         out.println("<h2>당신이 좋아하는 "+param+"입니다.</h2>");
                         out.println("<ul>");
                         for(String s : values){
                              out.println("<li>" + s + "</li>");
                         }
                         out.println("</ul>");
                    }
               }
              
               out.println("</body></html>");
               out.close();
          }catch(IOException err){}
     }
}

javac ServletTest4.java -d ../classes ServletTest4.java
----------------------------------- 
3-2
~\JSP\ManualWork\ServletApp2\WEB-INF\src\ServletTest1.java

package servlet.lifecycle;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class ServletTest1 extends HttpServlet{
     public void init(ServletConfig config){
          System.out.println("init() called");
     }
     
     public void service(ServletRequest req, ServletResponse res){
          System.out.println("service() called");
     }
     
     protected void doGet(HttpServletRequest req, HttpServletResponse resp){
          System.out.println("Get() Test...");
     }
     
     protected void doPost(HttpServletRequest req, HttpServletResponse resp){
          System.out.println("Post() Test...");
     }
}
javac -d ../classes ServletTest1.java
----------------------------------- 
3-3
~\JSP\ManualWork\ServletApp2\WEB-INF\src\ServletTest2.java

package servlet.lifecycle;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class ServletTest2 extends HttpServlet{
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          doPost(req,resp);
     }
     
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          PrintWriter out = resp.getWriter();
          out.println("<html><body>");
          out.println("method : "+req.getMethod()+"<br/>");
          out.println("request URI : "+req.getRequestURI()+"<br/>");
          out.println("protocol : "+req.getProtocol()+"<br/>");
          out.println("Path info : "+req.getPathInfo()+"<br/>");
          out.println("RemoteAddr : "+req.getRemoteAddr()+"<br/>");
          out.println("ContextPath : "+req.getContextPath()+"<br/>");
          out.println("ServletContext : "+req.getServletContext()+"<br/>");
          out.println("ServletPath : "+req.getServletPath()+"<br/>");
          out.println("</body></html>");
          out.close();
     }
}

javac -d ../classes *.java
----------------------------------- 
3-4
~\JSP\ManualWork\ServletApp2\WEB-INF\src\ServletTest3.java

package servlet.lifecycle;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class ServletTest3 extends HttpServlet{
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          doPost(req,resp);
     }
     
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          System.out.println("cookie Test...");
          
          resp.setCharacterEncoding("euc-kr");
          req.setCharacterEncoding("euc-kr");
          PrintWriter out = resp.getWriter();
          /*
          String name = req.getParameter("name");
          String addr = req.getParameter("addr");
          
          Cookie nameCookie = new Cookie("name",name);
          Cookie addrCookie = new Cookie("addr",addr);
          
          // 초 단위 저장
          nameCookie.setMaxAge(60 * 60 * 24);
          addrCookie.setMaxAge(60 * 60 * 24);
          
          resp.addCookie(nameCookie);
          resp.addCookie(addrCookie);
          */
          
          //내가 저장해 놓은 쿠키 전부 가져오기
          Cookie[] cooks = req.getCookies();
          out.println("<html><body>");
          for(int i=0;i<cooks.length;i++){
               Cookie c = cooks[i];
               out.println(c.getName()+", "+c.getValue()+"<br/>");
          }
          out.println("</body></html>");
          out.close();
     }
}
----------------------------------- 
3-5 
~\JSP\ManualWork\ServletApp2\WEB-INF\src\ServletTest4.java

package servlet.lifecycle;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class ServletTest4 extends HttpServlet{
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          doPost(req,resp);
     }
     
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          System.out.println("session Test...");
          
          resp.setCharacterEncoding("euc-kr");
          req.setCharacterEncoding("euc-kr");
          String name = req.getParameter("name");
          
          // 세션은 만들어 내는 것이 아니고, 사용자가 접속하면 자동으로 생성됨
          // 자동으로 생성된 세션의 정보를 가져오면 됨
          HttpSession session = req.getSession();
          
          // name이라는 이름으로 저장해서 서버 어디서든지 사용가능
          session.setAttribute("name",name);
          
          PrintWriter out = resp.getWriter();
          out.println("<html><body>");
          out.println("당신이 저장한 세션 값은 " + 
                         session.getAttribute("name")+" 이다.<br/>");
          out.println("접속 시간 : "+new java.util.Date(session.getCreationTime())+"<br/>");
          out.println("세션 ID : "+session.getId()+"<br/>");
          out.println("세션 만료 시간 : "+session.getMaxInactiveInterval()+"<br/>");
          if(session.isNew())
               out.println("처음 접속하셨군요<br/>");
          else
               out.println("최근에 접속하였습니다.<br/>");
          out.println("</body></html>");
          out.close();
     }
}
-----------------------------------  
3-6
아래 경로로 프로젝트 만들고 안에 폴더도 만듬, index 위치를 옮김
~\JSP\ManualWork\ServletApp2\html\index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome</h1>
<a href="http://127.0.0.1:8080/ServletApp2/life.do">서버에 요청</a><br/><br/>
<!-- 상대 경로 -->
<!-- <form action="../life.do" method="post"> -->
<!-- 절대 경로 -->
<form action="/ServletApp2/life.do" method="post">
     <input type="submit" value="요청"/><br/>
</form>
</body>
</html>
----------------------------------- 
3-7
~\JSP\ManualWork\ServletApp2\header.html

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome To My Site!!!</h1>
<form action="header.do" method="post">
     <input type="text" name="content"/><br/><br/>
     <input type="submit" value="전송"/><br/><br/>
</form>
</body>
</html>
----------------------------------- 
3-8
~\JSP\ManualWork\ServletApp2\cookie.html

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>전송버튼을 누르는 순간 이미 당신의 컴퓨터에는 내가 심어놓은 정보가 저장될 것이다.</h1>
<form action="cookie/cookie.action" method="post">
     이름 : <input type="text" name="name"/><br/><br/>
     주소 : <input type="text" name="addr"/><br/><br/>
     <input type="submit" value="전송"/><br/><br/>
</form>
</body>
</html>
----------------------------------- 
3-9
~\JSP\ManualWork\ServletApp2\session.html

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>세션 예제</h1>
<form action="session/session.action" method="post">
     이름 : <input type="text" name="name"/><br/><br/>
     <input type="submit" value="전송"/><br/><br/>
</form>
</body>
</html>
----------------------------------- 
3-10
~\JSP\ManualWork\ServletApp2\homework.html

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h1>과제</h1>
<h2>회원 가입 신청</h2>
<form action="homework.action" method="post">
     <table style="border:1px solid black">          
          <tr>
               <td>아이디 : </td>
               <td><input type="text" name="id"/></td>
          </tr>
          
          <tr>
               <td>패스워드 : </td>
               <td><input type="password" name="pw"/></td>
          </tr>

          <tr>
               <td>성별 : </td>
               <td>
               <input type="radio" name="gender" value="남성"/>남성
               &nbsp;&nbsp;
               <input type="radio" name="gender" value="여성"/>여성
               </td>
          </tr>     
          
          <tr>
               <td>취미 : </td>
               <td>
               <input type="checkbox" name="hobby" value="등산"/>등산<br/>
               <input type="checkbox" name="hobby" value="낚시"/>낚시<br/>
               <input type="checkbox" name="hobby" value="자전거"/>자전거<br/>
               <input type="checkbox" name="hobby" value="독서"/>독서<br/>
               </td>
          </tr>

          <tr>
               <td>직업 : </td>
               <td>
               <select name="job">
                    <option value="회사원">회사원</option>
                    <option value="농업">농업</option>
                    <option value="어업">어업</option>
                    <option value="광업">광업</option>
               </select>
               </td>
          </tr>

          <tr>
               <td>하고 싶은 말 : </td>
               <td>
                    <textarea row="5" cols="60" name="say"></textarea>
               </td>
          </tr>

          <tr >
               <td colspan="2" style="center">
                    <input type="submit" value="가입신청"/>&nbsp;&nbsp;
                    <input type="reset" value="취소"/>&nbsp;&nbsp;
               </td>
          </tr>                    
     </table>
     <input type="checkbox" value="cook"/>쿠키 여부
     <!-- 쿠키여부 체크 안했을 경우 - 다음 페이지에서 타이틀 -> 처음 가입을 환영 합니다 -->
     <!-- 쿠키여부 체크 했을 경우 - 다음 페이지에서 타이틀 -> 이미 가입된 회원입니다 -->
     <!-- submit을 눌렀을대 여기서 기록한 내용을 보여주도록 -->
</form>
</body>
</html>
----------------------------------- 
3-11
~\JSP\ManualWork\ServletApp2\WEB-INF\web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<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"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
  
  <servlet>
     <servlet-name>life</servlet-name>
     <servlet-class>servlet.lifecycle.ServletTest1</servlet-class>
  </servlet>  
  
  <servlet-mapping>
     <servlet-name>life</servlet-name>
     <url-pattern>/life.do</url-pattern>     
     <!-- http://localhost:8080/ServletApp2/life.do -->
  </servlet-mapping>
  
  <servlet>
     <servlet-name>header</servlet-name>
     <servlet-class>servlet.lifecycle.ServletTest2</servlet-class>
  </servlet>  
  
  <servlet-mapping>
     <servlet-name>header</servlet-name>
     <url-pattern>/header.do</url-pattern>     
     <!-- http://localhost:8080/ServletApp2/header.do -->
  </servlet-mapping>  
  
  <servlet>
     <servlet-name>cookie</servlet-name>
     <servlet-class>servlet.lifecycle.ServletTest3</servlet-class>
  </servlet>  
  
  <servlet-mapping>
     <servlet-name>cookie</servlet-name>
     <url-pattern>/cookie/cookie.action</url-pattern>     
     <!-- http://localhost:8080/ServletApp2/cookie/cookie.action -->
  </servlet-mapping>  
  
  <servlet>
     <servlet-name>session</servlet-name>
     <servlet-class>servlet.lifecycle.ServletTest4</servlet-class>
  </servlet>  
  
  <servlet-mapping>
     <servlet-name>session</servlet-name>
     <url-pattern>/session/session.action</url-pattern>     
     <!-- http://localhost:8080/ServletApp2/session/session.action -->
  </servlet-mapping>  
</web-app>

----------------------------------- 
3-12
~\apache-tomcat-8.0.21\conf\server.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
          
          <Context path="/TestApp3" docBase="F:\study\JSP\ManualWork\TestApp3" workDir="F:\study\JSP\ManualWork\TestApp3\work"/>
          <!-- http://localhost:8080/ 의 주소를 줄여서 '/' 슬래시로 표시 -->
          <Context path="/ServletApp1" docBase="F:\study\JSP\ManualWork\ServletApp1" workDir="F:\study\JSP\ManualWork\ServletApp1\work"/>          
          <Context path="/Test" docBase="F:\study\JSP\ManualWork\Test" workDir="F:\study\JSP\ManualWork\Test\work"/>
          <Context path="/ServletApp2" docBase="F:\study\JSP\ManualWork\ServletApp2" workDir="F:\study\JSP\ManualWork\ServletApp2\work"/>          
      </Host>
    </Engine>
  </Service>
</Server>
----------------------------------- 
###################################
4. 과제
-----------------------------------
4-1
~\JSP\ManualWork\ServletApp2\homework.html
----------------------------------- 
-----------------------------------
###################################
5. 과제 해결
-----------------------------------
-----------------------------------
###################################
6. 기타
----------------------------------- 

-----------------------------------


'OpenFrameWork' 카테고리의 다른 글

오픈프레임워크_Day41  (0) 2015.05.12
오픈프레임워크_Day40  (0) 2015.05.11
오픈프레임워크_Day38  (0) 2015.05.07
오픈프레임워크_Day37  (0) 2015.05.06
오픈프레임워크_Day36  (0) 2015.05.04
,