<repo_name>Kibaek/Java_project<file_sep>/zJavaProject/src/main/java/java63/servlets/london/ProductListServlet.java
package java63.servlets.london;

import java.io.IOException;
import java.io.PrintWriter;
import java63.servlets.london.dao.ProductDao;
import java63.servlets.london.domain.Product;

import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/london/bookmark/list")
public class ProductListServlet extends GenericServlet {
  private static final long serialVersionUID = 1L;

  static final int PAGE_DEFAULT_SIZE = 3;
  
  
  @Override
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
  	
    int pageNo = 0;
    int pageSize = 0;
    
    
    
    if (request.getParameter("pageNo") != null) {
      pageNo = Integer.parseInt(request.getParameter("pageNo"));
      pageSize = PAGE_DEFAULT_SIZE;
    }
    
    if (request.getParameter("pageSize") != null) {
      pageSize = Integer.parseInt(request.getParameter("pageSize"));
    }
    
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    
    RequestDispatcher rd = 
        request.getRequestDispatcher("/common/header");
    rd.include(request, response);
    
    out.println("<html>");
    out.println("<head>");
    
    //out.println("<meta charset='UTF-8'>");
    out.println("<link rel='stylesheet' href='../../css/bootstrap.min.css'>");
    out.println("<link rel='stylesheet' href='../../css/bootstrap-theme.min.css'>");
    out.println("<link rel='stylesheet' href='../../css/common.css'>");
    out.println("<script src='../../js/jquery-1.11.1.js'></script>");
    out.println("<script src='../../js/bootstrap.min.js'></script>");
    out.println("<script src='../../js/jquery.animate-shadow.js'></script>");
    
    out.println("<title>JD_BookMark</title>");
    out.println("</head>");
    out.println("<body>");
    	out.println("<div class='container'>");
    	out.println("	<header>");
    	out.println("	<div id='headline'>");
    	out.println("<img src='https://pbs.twimg.com/profile_images/425962153103745024/9XJste4m.jpeg' width=200px>");
    	out.println("		</div>");
    		//	<!-- Add_Button trigger modal -->
    	
    	
    	
    	out.println("	</header>");

    	
    	out.println("	<div class='boxWrapper'>");
    	
    	out.println("<center>");
    	out.println("<form method=get action='http://www.google.co.kr/search' target='_blank' >");
    	out.println("  <table bgcolor='#FFFFFF'>");
    	out.println("    <tr>");
    	out.println("      <td>");
    	out.println("          <input type=text name=q size=50 maxlength=255 style='text-align:center' placeholder='검색어를 입력하세요!' />");
    	out.println("          <input type=hidden name=ie value=utf-8 />");
    	out.println("          <input type=hidden name=oe value=utf-8 />");
    	out.println("          <input type=hidden name=hl value=utf-8 />");
    	out.println("          <input type=submit name=btnG value='Search' />");
    	out.println("      </td>");
    	out.println("    </tr>");
    	out.println("  </table>");
    	out.println("</form>");
    	out.println("</center>");


    	ProductDao productDao = (ProductDao)this.getServletContext()
          .getAttribute("productDao");

    	for (Product product : productDao.selectList(pageNo, pageSize)) {
    		
    	out.println("		<div class='boxList'>");
    	out.println("			<div class='box' onclick=\"location.href='" + product.getUrl() + "'\" style='cursor:pointer;' \">");
    	out.println("				<h2>" +  product.getName()  + " </h2>");
    	out.println("			</div>");
    	out.println("			<div class='boxDetail'>");
    	out.println("<a href='view?dno=" + product.getDno() + "'> ShowDetail</a>");
    	//out.println("				<button type='button' class='btn btn-primary btn-xs' data-toggle='modal' data-target='#viewModal'>자세히보기</button>");
    	out.println("			</div>");
    	out.println("		</div>");
    			
    	}
    	
    	out.println("		<div class='boxList' height=250px>");
    	out.println("		<button type='button' class='btn btn-primary btn-sm'	data-toggle='modal' data-target='#myModal'>+</button>");
    	out.println("			</div>");
    	out.println("	</div>");
    	//	<!-- end of boxWrapper -->
    	out.println("</div>");
    	// <!-- end of container -->

    //<!-- Add_Modal -->
    	out.println("<div class='modal fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>");
    	out.println("<div class='modal-dialog'>");
    	out.println("<div class='modal-content'>");
    	out.println("<div class='modal-header'>");
    	out.println("<button type='button' class='close' data-dismiss='modal'>");
    	out.println("<span aria-hidden='true'>&times;</span><span class='sr-only'>Close</span>");
    	out.println("</button>");
    	out.println("<h3 class='modal-title' id='myModalLabel'>Bookmark_Add</h3>");
    	out.println("</div>");

    	out.println("<div class='modal-body'>");

    	out.println("<form class='form-horizontal' role='form' action='add'	method='post'>");
    	
    	
  
    	
    	

    	out.println("<div class='form-group'>");
    					out.println("<label for='name' class='col-sm-2 control-label'>Site_Name</label>");
    	out.println("<div class='col-sm-10'>");
    					out.println("<input type='text' class='form-control' id='name' name='name'	placeholder='이름을 입력해주세요. 예) java'>");
    	out.println("</div>");
    	out.println("</div>");
    	out.println("<div class='form-group'>");
    					out.println("<label for='url' class='col-sm-2 control-label'>URL</label>");
    	out.println("<div class='col-sm-10'>");
    					out.println("<input type='text' class='form-control' id='url' name='url' placeholder='주소를 입력해주세요. 예) http://www.java.com'>");
    	out.println("</div>");
    	out.println("</div>");
    	out.println("<div class='form-group'>");
    					out.println("<label for='info' class='col-sm-2 control-label'>Version</label>");
    	out.println("<div class='col-sm-10'>");
    					out.println("<input type='text' class='form-control' id='info' name='info'	placeholder='버전 정보를 입력해주세요. 예) Java SE 8'>");
    	out.println("</div>");
    	out.println("</div>");

    	out.println("<div class='form-group'>");
			    	out.println("<label for='memo' class='col-sm-2 control-label'>Comment</label>");
			    	out.println("<div class='col-sm-10'>");
			    	out.println("<input type='text' class='form-control' id='memo' name='memo' placeholder='메모를 남겨주세요. 예) JDK 7이상부터 switch는 string 가능'>");
    	out.println("</div>");

    	out.println("</div>");
    		//		out.println("</form>");
    	out.println("</div>");

    			//	out.println("<form class='form-horizontal' role='form' action='add' method='post'>");
    	out.println("<div class='modal-footer'>");
    				out.println("<button id='btnAdd' type='submit' class='btn btn-primary'>Add</button>");
    				out.println("<button id='btnCancel' type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button>");
    	out.println("</div>");
    				out.println("</form>");
    	out.println("</div>");
    	out.println("</div>");
    	out.println("</div>");
    	//<!-- end of Add_Modal -->
    	
    	
    //<!-- View_Modal -->
    	


    	



    	out.println("<script>");
    	out.println("$('#btnAdd').click(function() {");
    	out.println("if ($('#name').val().length == 0) {");
    	out.println("alert('이름은 필수 입력 항목입니다.');");
    	out.println("return false;");
    	out.println("}");

    	out.println("if ($('#url').val().length == 0) {");
    	out.println("alert('URL은 필수 입력 항목입니다.');");
    	out.println("return false;");
    	out.println("}");
    	out.println("});");
    	
    	


    out.println("</script>");



    out.println("</body>");
    out.println("</html>");
    System.out.println("service() 실행 완료");
    
    
    
    
    
    
    
    
    
  
    
    
    
    
    
  }
  
}<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test01/Test02.java
package java63.servlets.test01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/* 웹 브라우저에게 출력하기 
 *
 * 
 * ServletRequest => 요청 정보를 다루는 도구
 * ServletResponse => 응답 정보를 다루는 도구
 * 
 */

/*
 * 한글 출력할 때 깨지는 문제 해결
 * 
 * 이유 : 
 * ServletResponse가 준 출력 스트림은
 * 기본적으로 출력할 때 ISO-8859-1로 인코딩한다.
 * => 한글은 ISO-8859-1 문자집합에 없기 때문에 '?'로 대체하여 출력한다.
 * 
 * 해결책 : ServletResponse로부터 출력 스트림을 얻기 전에,
 * 출력할 내용의 타입과 문자집합을 설정한다.
 * => response.setContentType("text/plain;charset=UTF-8")
 * => response.setCharacterEncoding("UTF-8");
 * 
 * MIME => 콘텐츠의 타입을 표현
 */

@WebServlet("/test01/Test02")
public class Test02 extends GenericServlet{

	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {

		//1. ServletResponse 도구를 사용하여 출력 스트림을 준비한다.
		
		
		//3. 한글출력 할 수 있게하기
		//response.setCharacterEncoding("UTF-8");

		//4. 한글출력 할 수 있게하기
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		// 2. 출력 스트림을 사용하여 브라우저로 출력한다.
		out.println("아하~~안녕하세여?, 곤니찌와");
	} 

}
<file_sep>/zJavaProject/src/main/java/java63/servlets/london/HtmlFooterServlet.java
package java63.servlets.london;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/* Include에 사용할 서블릿 
 * => HTML 페이지의 권리 안내문 출력을 맡는다.
 */

@WebServlet("/common/footer")
public class HtmlFooterServlet extends GenericServlet {
  private static final long serialVersionUID = 1L;

  @Override
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    
    /* HTML Entity => HTML의 상수
     * &amp; => &
     * &lt;  => <
     * &gt;  => >
     * &copy; => (C)
     * &reg;  => (R)
     * &yen;  => 엔화
     */
    out.println("<address class='copyright'>Copyright&copy;Java63</address>");
  }

}











<file_sep>/projectLondon01/src/main/java/java63/servlets/test/DbmListServlet.java
package java63.servlets.test;

import java.io.IOException;
import java.io.PrintWriter;
import java63.servlets.test.dao.DbmDao;
import java63.servlets.test.domain.Dbm;

import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/test/dbm/list")
public class DbmListServlet extends GenericServlet {
  private static final long serialVersionUID = 1L;

  static final int PAGE_DEFAULT_SIZE = 3;
  
  @Override
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
  	System.out.println("service() 실행 시작");
    int pageNo = 0;
    int pageSize = 0;
    
    if (request.getParameter("pageNo") != null) {
      pageNo = Integer.parseInt(request.getParameter("pageNo"));
      pageSize = PAGE_DEFAULT_SIZE;
    }
    
    if (request.getParameter("pageSize") != null) {
      pageSize = Integer.parseInt(request.getParameter("pageSize"));
    }
    
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
   
    out.println("<head>");
    // 다른 서블릿을 실행 => 실행 후 제어권이 되돌아 온다.
    //RequestDispatcher rd =
    	//	request.getRequestDispatcher("/common/header");
    //rd.include(request, response); // 자기가 받은 리퀘스트와 리스판스를 넘겨줘서 돌아갈 수 있게 만들어 준다.
    //out.println("</head>");
    
    
    
    out.println("</head>");
    out.println("<body>");
    out.println("<div class='container'>");
    out.println("<h1>개발자 맵</h1>");
    out.println("<p><a href='dbm-form.html' class='btn btn-primary'>맵추가</a></p>");
    out.println("<table class='table table-hover'>");
    out.println("<tr>");
    out.println("  <th>#</th><th>이름</th><th>url</th><th>정보</th><th>메모</th>");
    out.println("</tr>");
    
    //for (Product product : AppInitServlet.productDao.selectList(pageNo, pageSize)) {
    //for (Product product : ContextLoaderListener.productDao.selectList(pageNo, pageSize)) {
    
    // ProductDao를 ServletContext 보관소에서 꺼내는 방식을 사용
    // => 단점: 위의 방식보다 코드가 늘었다.
    // => 장점: 특정 클래스에 종속되지 않는다. 유지보수에서 더 중요!
    DbmDao dbmDao = (DbmDao)this.getServletContext()
                                         .getAttribute("DbmDao");
    for (Dbm dbm : dbmDao.selectList(pageNo, pageSize)) {
      out.println("<tr>");
      out.println("  <td>" + dbm.getName() + "</td>");
      out.println("  <td>" + dbm.getUrl() + "</td>");
      out.println("  <td>" + dbm.getInfo() + "</td>");
      out.println("  <td>" + dbm.getMemo() + "</td>");
      out.println("</tr>");
    }
    out.println("</table>");
    out.println("</div>");
    
    out.println("<script src='../../js/jquery-1.11.1.js'></script>");
    
    //다른 서블릿을 실행 => 실행 후 제어권이 되돌아 온다.
    //rd = request.getRequestDispatcher("/common/footer");
   // rd.include(request, response);
    
    out.println("</body>");
    out.println("</html>");
    System.out.println("service() 실행 완료");
  }
  
}












<file_sep>/zJavaWeb02/src/main/java/java63/assign01/domain/Product.java
/* Value Object
 * => Class 문법을 사용하여 사용자 정의 데이터 타입 만들기
 * 
 * 1) Serializable 인터페이스 구현
 *    => SerialVersionUID 스태틱 변수 선언
 * 
 * 2) 인스턴스 변수 선언
 * 
 * 3) setter/getter 생성
 * 
 * 4) 기본 생성자와 파라미터 값을 받는 생성자 선언
 * 
 * 5) equals()/hashCode() 메서드 오버라이딩
 * 
 * 6) toString() 오버라이딩
 */
package java63.assign01.domain;

import java.io.Serializable;

public class Product implements Serializable, Cloneable {
  private static final long serialVersionUID = 1L;
  
  protected int       no;
  protected String    name;
  protected int       quantity;
  protected int       makerNo;
  
  public Product() {}
  
  public Product(int no, String name, int quantity, int makerNo) {
    this.no = no;
    this.name = name;
    this.quantity = quantity;
    this.makerNo = makerNo;
  }

  @Override
  public Product clone() throws CloneNotSupportedException {
    return (Product) super.clone();
  }
  
  @Override
  public String toString() {
    return "Product [no=" + no + ", name=" + name + ", quantity=" + quantity
        + ", makerNo=" + makerNo + "]";
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + makerNo;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + no;
    result = prime * result + quantity;
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Product other = (Product) obj;
    if (makerNo != other.makerNo)
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    if (no != other.no)
      return false;
    if (quantity != other.quantity)
      return false;
    return true;
  }

  public int getNo() {
    return no;
  }
  public void setNo(int no) {
    this.no = no;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getQuantity() {
    return quantity;
  }
  public void setQuantity(int quantity) {
    this.quantity = quantity;
  }
  public int getMakerNo() {
    return makerNo;
  }
  public void setMakerNo(int makerNo) {
    this.makerNo = makerNo;
  }
  
  
}













<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test03/ContextLoaderListener01.java
package java63.servlets.test03;

import java.io.InputStream;
import java63.servlets.test03.dao.ProductDao;

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

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/* ServletContextListener는 
 * 웹 애플리케이션이 시작하거나 종료하는 이벤트에 대해 작업 수행!
 * 
 * 컨텍스트 파라미터?
 * => 웹 애플리케이션에서 사용할 환경 변수 정의할 때 사용
 * => 모든 서블릿이 사용할 수 있다.
 * 
 * 설정 방법? web.xml에 다음과 같이 설정한다.
 * <context-param>
 *   <param-name>키</param-name>
 *   <param-value>값</param-value>
 * </context-param>
 * 
 * 사용 방법?
 * ServletContext의 getInitParameter(키) 호출
 * 
 */

//@WebListener
public class ContextLoaderListener01 implements ServletContextListener {
  public static ProductDao productDao;
  
  /* 웹 애플리케이션이 시작할 때 호출됨
   * => 서블릿이 사용할 공통 자원을 준비 
   */
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    try {
      ServletContext ctx = sce.getServletContext();
      InputStream inputStream = Resources.getResourceAsStream(
          ctx.getInitParameter("mybatisConfig"));
      SqlSessionFactory sqlSessionFactory = 
          new SqlSessionFactoryBuilder().build(inputStream);
      
      productDao = new ProductDao();
      productDao.setSqlSessionFactory(sqlSessionFactory);
      
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  /* 웹 애플리케이션이 종료할 때 호출됨
   * => 서블릿이 사용한 자원을 해제할 때 
   */
  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    

  }

}








<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test01/Test01.java
package java63.servlets.test01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/* 웹 브라우저에게 출력하기 
 *
 * 
 * ServletRequest => 요청 정보를 다루는 도구
 * ServletResponse => 응답 정보를 다루는 도구
 * 
 */

@WebServlet("/test01/Test01")
public class Test01 extends GenericServlet{

	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {

		//1. ServletResponse 도구를 사용하여 출력 스트림을 준비한다.
		PrintWriter out = response.getWriter();
		
		// 2. 출력 스트림을 사용하여 브라우저로 출력한다.
		out.println("아하~~안녕하세여?, 곤니찌와");
	} 

}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test03/AppInitServlet.java
package java63.servlets.test03;

import java.io.IOException;
import java.io.InputStream;
import java63.servlets.test03.dao.ProductDao;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/* 서블릿 생성
 * => 클라이언트가 요청했을 때 생성된다.
 * 
 * 클라이언트 요청이 없더라도 강제로 서블릿을 생성하는 방법
 * => 웹 애플리케이션을 시작할 때 생성된다.
 * => 배치 설정에 <load-on-startup>을 추가한다.
 *    이 태그에 주는 숫자는 실행 순서를 의미한다.
 *    여러 개의 서블릿이 있을 때 작은 수를 갖는 서블릿이 먼저 생성된다.
<servlet>
  <servlet-name>Hello</servlet-name>
  <servlet-class>java63.servlets.Hello</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
 *    
 */
/*
@WebServlet(
    loadOnStartup=1
)
*/
public class AppInitServlet extends GenericServlet {
  private static final long serialVersionUID = 1L;

  public static ProductDao productDao;
  
  public AppInitServlet() {
    System.out.println("AppInitServlet 생성됨.");
  }
  
  /* 외부 자원을 참조하는 경우, 
   * 가능한 하드 코딩하지 말고 설정 파일에서 읽어오는 방식으로 처리하라!
   * 
   * 설정 파일? web.xml
   * 
   * 설정하는 방법은?
   * <servlet>
   *   <servlet-name>...</servlet-name>
   *   <servlet-class>...</servlet-class>
   *   <init-param>
   *     <param-name>키</param-name>
   *     <param-value>값</param-value>
   *   </init-param>
   *   <init-param>
   *     <param-name>키</param-name>
   *     <param-value>값</param-value>
   *   </init-param>
   * </servlet>
   * 
   * 설정한 값을 꺼내는 방법?
   * => ServletConfig의 getInitParameter("키")
   */
  @Override
  public void init() throws ServletException {
    try {
      InputStream inputStream = Resources.getResourceAsStream(
          this.getInitParameter("mybatisConfig"));
      SqlSessionFactory sqlSessionFactory = 
          new SqlSessionFactoryBuilder().build(inputStream);
      
      productDao = new ProductDao();
      productDao.setSqlSessionFactory(sqlSessionFactory);
      
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  @Override
  public void service(ServletRequest req, ServletResponse res)
      throws ServletException, IOException {}

}








<file_sep>/zJavaWeb02/src/main/java/java63/assign01/servlets/HelpServlet.java
package java63.assign01.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/help")
public class HelpServlet extends GenericServlet{

	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		out.println("list");
    out.println("view 제품번호");
    out.println("add");
    out.println("delete 제품번호");
    out.println("update 제품번호");
    out.println();		
	}


}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test05/ErrorServlet.java
package java63.servlets.test05;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/common/error")
public class ErrorServlet extends GenericServlet {
  private static final long serialVersionUID = 1L;

  static final int PAGE_DEFAULT_SIZE = 3;
  
  @Override
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    
    // 다른 서블릿을 실행 => 실행 후 제어권이 되돌아 온다.
    RequestDispatcher rd = 
        request.getRequestDispatcher("/common/header");
    rd.include(request, response);
    
    out.println("</head>");
    out.println("<body>");
    out.println("<div class='container'>");
    out.println("<p>잠시 후 다시 시도하세요.</p>");
    
    // 다른 서블릿을 실행 => 실행 후 제어권이 되돌아 온다.
    rd = request.getRequestDispatcher("/common/footer");
    rd.include(request, response);
    
    out.println("</div>");
    out.println("</body>");
    out.println("</html>");
    
    //오류에 대한 자세한 정보는 콘솔창에 출력하라! (사용자에게는 비밀^^)
    Exception e = (Exception)request.getAttribute("error");
    e.printStackTrace();
    
  }
  
}












<file_sep>/zJavaWeb02/src/main/java/java63/assign01/servlets/ProductAddServlet.java
package java63.assign01.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import java63.assign01.dao.ProductDao;
import java63.assign01.domain.Product;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/product/add")
public class ProductAddServlet extends GenericServlet{

	
	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {

		ProductDao productDao = null;

		try {
			productDao = new ProductDao();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
	    try {
	      Product product = new Product();
	      product.setName((String)request.getParameter("name"));
	      product.setQuantity(Integer.parseInt((String)request.getParameter("qty")));
	      product.setMakerNo(Integer.parseInt((String)request.getParameter("mkno")));
	      
	      productDao.insert(product);
	      out.println("저장하였습니다.");
	      out.println();
	      
	    } catch (Exception e) {
	      e.printStackTrace();
	      out.println("서버가 바쁩니다. 잠시 후 다시 시도하세요.");
	      out.println();
	    }
		
		
	}

}
<file_sep>/zJavaWeb02/src/main/webapp/test02/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>도움말</h1>
<h2>제품관리</h2>
<p>
목록조회:<br>
예1) http://localhost:8080/product/list<br>
예2) http://localhost:8080/product/list?pageNo=페이지번호<br>
예3) http://localhost:8080/product/list?pageNo=페이지번호&pageSize=페이지당출력개수<br>
</p>
<p>
제품추가:Create<br>
http://localhost:8080/product/add?name=제품명&qty=수량&mkno=제조사번호
</p>
<p>
제품조회:Retrieve or Read<br>
http://localhost:8080/product/view?no=제품번호
</p>

<p>
제품변경:Update<br>
http://localhost:8080/product/update?no=제품번호&name=제품명&qty=수량&mkno=제조사번호
</p>

<p>
제품삭제:Delete<br>
http://localhost:8080/product/delete?no=제품번호
</p>
</body>
</html><file_sep>/zJavaWeb02/src/main/java/java63/servlets/test05/ProductViewServlet.java
package java63.servlets.test05;

import java.io.IOException;
import java63.servlets.test05.dao.ProductDao;
import java63.servlets.test05.domain.Product;

import javax.servlet.GenericServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebServlet("/test05/product/view")
public class ProductViewServlet extends GenericServlet {
  private static final long serialVersionUID = 1L;

  @Override
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    int no = Integer.parseInt(request.getParameter("no"));
    
    //스프링의 ContextLoaderListener가 준비한 
    //ApplicationContext 객체 꺼내기
    ApplicationContext appCtx =
        WebApplicationContextUtils.getWebApplicationContext(
            this.getServletContext());
    
    ProductDao productDao = (ProductDao)appCtx.getBean("productDao");
    Product product = productDao.selectOne(no);
    request.setAttribute("product", product);
    
    response.setContentType("text/html;charset=UTF-8");
    
    RequestDispatcher rd = 
        request.getRequestDispatcher("/test05/product/ProductView.jsp");
    rd.include(request, response);
  }
  
}












<file_sep>/projectLondon01/build.gradle
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'war'


compileJava{
	// 소스의 자바 버전 제한하기
	// => 지정된 버전의 문법이 아닌 경우 오류 출력한다.
	sourceCompatibility = 1.8
	options.encoding = 'UTF-8'
}

eclipse { // 이클립스 설정파일
	wtp {
		// 설정을 수행하는클로저를 넘긴다
		facet { // 함수를 넘긴다
			facet name:'jst.web', version:'3.0'
		}
	}
}

//의존 라이브러리를 받아올 서버 지정.
repositories {
	mavenCentral()
}

// 의존 라이브러리 지정
// 의존 라이브러리 검색 사이트 =>
//		 http://www.mvnrepository.com
dependencies {
	providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
	compile 'org.springframework:spring-jdbc:4.1.2.RELEASE'
	compile 'org.mybatis:mybatis-spring:1.2.2'
	compile 'org.springframework:spring-context:4.1.2.RELEASE'
	compile 'log4j:log4j:1.2.17'
	compile 'mysql:mysql-connector-java:5.1.34'
	compile 'org.reflections:reflections:0.9.9'
	compile 'org.mybatis:mybatis:3.2.8'
	//testCompile group: 'junit', name: 'junit', version: '4.+'
}<file_sep>/zJavaProject/src/main/webapp/js/jquery.animate-shadow.js
/**!
 * @preserve Shadow animation 1.11
 * http://www.bitstorm.org/jquery/shadow-animation/
 * Copyright 2011, 2013 <NAME> <<EMAIL>>
 * Contributors: <NAME>, <NAME> and <NAME>
 * Released under the MIT and GPL licenses.
 */

jQuery(function($, undefined) {
	/**
	 * Check whether the browser supports RGBA color mode.
	 *
	 * Author <NAME> <http://pioupioum.fr>
	 * @return {boolean} True if the browser support RGBA. False otherwise.
	 */
	function isRGBACapable() {
		var $script = $('script:first'),
		color = $script.css('color'),
		result = false;
		if (/^rgba/.test(color)) {
			result = true;
		} else {
			try {
				result = (color !== $script.css('color', 'rgba(0, 0, 0, 0.5)').css('color'));
				$script.css('color', color);
			} catch (e) {
			}
		}
		$script.removeAttr('style');

		return result;
	}

	$.extend(true, $, {
		support: {
			'rgba': isRGBACapable()
		}
	});

	/*************************************/

	// First define which property to use
	var styles = $('html').prop('style');
	var boxShadowProperty;
	$.each(['boxShadow', 'MozBoxShadow', 'WebkitBoxShadow'], function(i, property) {
		var val = styles[property];
		if (typeof val !== 'undefined') {
			boxShadowProperty = property;
			return false;
		}
	});

	// Extend the animate-function
	if (boxShadowProperty) {
		$['Tween']['propHooks']['boxShadow'] = {
			get: function(tween) {
				return $(tween.elem).css(boxShadowProperty);
			},
			set: function(tween) {
				var style = tween.elem.style;
				var p_begin = parseShadows($(tween.elem)[0].style[boxShadowProperty] || $(tween.elem).css(boxShadowProperty));
				var p_end = parseShadows(tween.end);
				var maxShadowCount = Math.max(p_begin.length, p_end.length);
				var i;
				for(i = 0; i < maxShadowCount; i++) {
					p_end[i] = $.extend({}, p_begin[i], p_end[i]);
					if (p_begin[i]) {
						if (!('color' in p_begin[i]) || $.isArray(p_begin[i].color) === false) {
							p_begin[i].color = p_end[i].color || [0, 0, 0, 0];
						}
					} else {
						p_begin[i] = parseShadows('0 0 0 0 rgba(0,0,0,0)')[0];
					}
				}
				tween['run'] = function(progress) {
					var rs = calculateShadows(p_begin, p_end, progress);
					style[boxShadowProperty] = rs;
				};
			}
		};
	}

	// Calculate an in-between shadow.
	function calculateShadows(beginList, endList, pos) {
		var shadows = [];
		$.each(beginList, function(i) {
			var parts = [], begin = beginList[i], end = endList[i];

			if (begin.inset) {
				parts.push('inset');
			}
			if (typeof end.left !== 'undefined') {
				parts.push(parseFloat(begin.left + pos * (end.left - begin.left)) + 'px '
				+ parseFloat(begin.top + pos * (end.top - begin.top)) + 'px');
			}
			if (typeof end.blur !== 'undefined') {
				parts.push(parseFloat(begin.blur + pos * (end.blur - begin.blur)) + 'px');
			}
			if (typeof end.spread !== 'undefined') {
				parts.push(parseFloat(begin.spread + pos * (end.spread - begin.spread)) + 'px');
			}
			if (typeof end.color !== 'undefined') {
				var color = 'rgb' + ($.support['rgba'] ? 'a' : '') + '('
				+ parseInt((begin.color[0] + pos * (end.color[0] - begin.color[0])), 10) + ','
				+ parseInt((begin.color[1] + pos * (end.color[1] - begin.color[1])), 10) + ','
				+ parseInt((begin.color[2] + pos * (end.color[2] - begin.color[2])), 10);
				if ($.support['rgba']) {
					color += ',' + parseFloat(begin.color[3] + pos * (end.color[3] - begin.color[3]));
				}
				color += ')';
				parts.push(color);
			}
			shadows.push(parts.join(' '));
		});
		return shadows.join(', ');
	}

	// Parse the shadow value and extract the values.
	function parseShadows(shadow) {
		var parsedShadows = [];
		var parsePosition = 0;
		var parseLength = shadow.length;

		function findInset() {
			var m = /^inset\b/.exec(shadow.substring(parsePosition));
			if (m !== null && m.length > 0) {
				parsedShadow.inset = true;
				parsePosition += m[0].length;
				return true;
			}
			return false;
		}
		function findOffsets() {
			var m = /^(-?[0-9\.]+)(?:px)?\s+(-?[0-9\.]+)(?:px)?(?:\s+(-?[0-9\.]+)(?:px)?)?(?:\s+(-?[0-9\.]+)(?:px)?)?/.exec(shadow.substring(parsePosition));
			if (m !== null && m.length > 0) {
				parsedShadow.left = parseInt(m[1], 10);
				parsedShadow.top = parseInt(m[2], 10);
				parsedShadow.blur = (m[3] ? parseInt(m[3], 10) : 0);
				parsedShadow.spread = (m[4] ? parseInt(m[4], 10) : 0);
				parsePosition += m[0].length;
				return true;
			}
			return false;
		}
		function findColor() {
			var m = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(shadow.substring(parsePosition));
			if (m !== null && m.length > 0) {
				parsedShadow.color = [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16), 1];
				parsePosition += m[0].length;
				return true;
			}
			m = /^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(shadow.substring(parsePosition));
			if (m !== null && m.length > 0) {
				parsedShadow.color = [parseInt(m[1], 16) * 17, parseInt(m[2], 16) * 17, parseInt(m[3], 16) * 17, 1];
				parsePosition += m[0].length;
				return true;
			}
			m = /^rgb\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*\)/.exec(shadow.substring(parsePosition));
			if (m !== null && m.length > 0) {
				parsedShadow.color = [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10), 1];
				parsePosition += m[0].length;
				return true;
			}
			m = /^rgba\(\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*,\s*([0-9\.]+)\s*\)/.exec(shadow.substring(parsePosition));
			if (m !== null && m.length > 0) {
				parsedShadow.color = [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10), parseFloat(m[4])];
				parsePosition += m[0].length;
				return true;
			}
			return false;
		}
		function findWhiteSpace() {
			var m = /^\s+/.exec(shadow.substring(parsePosition));
			if (m !== null && m.length > 0) {
				parsePosition += m[0].length;
				return true;
			}
			return false;
		}
		function findComma() {
			var m = /^\s*,\s*/.exec(shadow.substring(parsePosition));
			if (m !== null && m.length > 0) {
				parsePosition += m[0].length;
				return true;
			}
			return false;
		}
		function normalizeShadow(shadow) {
			if ($.isPlainObject(shadow)) {
				var i, sColor, cLength = 0, color = [];
				if ($.isArray(shadow.color)) {
					sColor = shadow.color;
					cLength = sColor.length;
				}
				for(i = 0; i < 4; i++) {
					if (i < cLength) {
						color.push(sColor[i]);
					} else if (i === 3) {
						color.push(1);
					} else {
						color.push(0);
					}
				}
			}
			return $.extend({
				'left': 0,
				'top': 0,
				'blur': 0,
				'spread': 0
			}, shadow);
		}
		var parsedShadow = normalizeShadow();

		while (parsePosition < parseLength) {
			if (findInset()) {
				findWhiteSpace();
			} else if (findOffsets()) {
				findWhiteSpace();
			} else if (findColor()) {
				findWhiteSpace();
			} else if (findComma()) {
				parsedShadows.push(normalizeShadow(parsedShadow));
				parsedShadow = {};
			} else {
				break;
			}
		}
		parsedShadows.push(normalizeShadow(parsedShadow));
		return parsedShadows;
	}
});<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test02/ProductDeleteServlet03.java
package java63.servlets.test02;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java63.servlets.test02.dao.ProductDao;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


/* Refresh하기
 * => <meta> 태그에 refresh 정보 넣기
 * 
 */

//@WebServlet("/test02/product/delete") // 서블릿으로 등록
public class ProductDeleteServlet03 extends GenericServlet {
	private static final long serialVersionUID = 1L;

	SqlSessionFactory sqlSessionFactory;
	ProductDao productDao;

	public ProductDeleteServlet03() {
		try {
			String resource = "java63/servlets/test02/dao/mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

			productDao = new ProductDao();
			productDao.setSqlSessionFactory(sqlSessionFactory);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {

		int no = Integer.parseInt(request.getParameter("no"));
		productDao.delete(no);

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		out.println("<html>");

			out.println("<head>");
			out.println("<meta http-equiv='Refresh' content='3:url=list'>;");
				out.println("<link rel='stylesheet' href='../../css/bootstrap.min.css'>");
				out.println("<link rel='stylesheet' href='../../css/bootstrap-theme.min.css'>");
				out.println("<link rel='stylesheet' href='../../css/common.css'>");
			out.println("</head>");
	
			out.println("<body>");
			
				out.println("<div class='container'>");
						out.println("<h1>삭제 결과</h1>");
						
						out.println("<p>삭제하였습니다.</p>");
						
				out.println("</div>");
				
				out.println("<script>");
				out.println("window.setTimeout(function(){");
				out.println("	window.location.href = 'list';");
				out.println("},1000);");
				out.println("</script>");
			
			out.println("</body>");
		out.println("</html>");
		
		
	}
}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test01/Test05.java
package java63.servlets.test01;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/*
 *  연산하기
 * 
 */

@WebServlet("/test01/Test05")
public class Test05 extends GenericServlet{

	@Override
	public void service(ServletRequest request, ServletResponse response)
			throws ServletException, IOException {
		
		int a = Integer.parseInt(request.getParameter("a"));
		int b = Integer.parseInt(request.getParameter("b"));
		String op = request.getParameter("op");
		
		int result = 0;
		
		switch(op) {
		case "+": result = a + b; break;
		case "-": result = a - b; break;
		case "*": result = a * b; break;
		case "/": result = a / b; break;
		}

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<body>");
		out.println("<p>" + a + " " + op + " " + b + " " + " = " + result + "</p>");
		out.println("</body>");
		out.println("</html>");
		
	} 

}
<file_sep>/zJavaWeb02/src/main/java/java63/servlets/test03/dao/ProductDao.java
package java63.servlets.test03.dao;

import java.util.HashMap;
import java.util.List;
import java63.servlets.test03.domain.Product;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ProductDao {
  @Autowired
  SqlSessionFactory sqlSessionFactory;
  
  public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
  }

  public ProductDao() {}

  public Product selectOne(int no) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    
    try {
      return sqlSession.selectOne(
        "java02.test19.server.ProductDao.selectOne", 
        no /* new Integer(no) */);
    } finally {
      sqlSession.close();
    }
  }
  
  public void update(Product product) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
      sqlSession.update(
        "java02.test19.server.ProductDao.update", product);
      sqlSession.commit();
    } finally {
      sqlSession.close();
    }
  }
  
  public void delete(int no) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
      sqlSession.delete(
        "java02.test19.server.ProductDao.delete", no);
      sqlSession.commit();
    } finally {
      sqlSession.close();
    }
  }
  
  public List<Product> selectList(int pageNo, int pageSize) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    
    HashMap<String,Object> paramMap = new HashMap<>();
    paramMap.put("startIndex", ((pageNo - 1) * pageSize));
    paramMap.put("pageSize", pageSize);
    
    try {
      return sqlSession.selectList(
        // 네임스페이스 + SQL문 아이디
        "java02.test19.server.ProductDao.selectList", 
        paramMap /* SQL문을 실행할 때 필요한 값 전달 */);
    } finally {
      sqlSession.close();
    }
  }
  
  public void insert(Product product) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
      sqlSession.insert(
        "java02.test19.server.ProductDao.insert", product);
      sqlSession.commit();
    } finally {
      sqlSession.close();
    }
  }
}


















<file_sep>/zJavaWeb02/src/main/java/README.TXT
과제
java03 프로젝트의 test21.server 패키지를
서블릿을 사용하여 바꿔라!

스프링을 사용하지 않고 만들라!

/help => java63.assign01.servlets.HelpServlet -
/product/list => java63.assign01.servlets.ProductListServlet -
/product/add => java63.assign01.servlets.ProductAddServlet -
/product/view => java63.assign01.servlets.ProductViewServlet -
/product/update => java63.assign01.servlets.ProductUpdateServlet
/product/delete => java63.assign01.servlets.ProductDeleteServlet
java63.assign01.dao.ProductDao
java63.assign01.domain.Product

java63.assign01.dao.ProductDao.xml
java63.assign01.dao.mybatis-config.xml









