ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2. 웹 애플리케이션과 서블릿 이해
    개발자 수업/JSP 2021. 11. 24. 13:54

    1. 서블릿이란?
        1) 서버 쪽에서 실행되면서 클라이언트의 요청에 따라 동적으로 서비스를 제공하는 자바 클래스

    2. 서블릿 특징
        1) 서버 쪽에서 실행되면서 기능을 수행함
        2) 기존의 정적인 웹 프로그램의 문제점을 보완하여 동적인 여러 기능 제공함
        3) 스레드 방식으로 실행됨
        4) 자바로 만들어져 객체 지향 특성 가짐
        5) 컨테이너에서 실행
        6) 웹 브라우저에서 요청 시 기능을 수행

    3. 서블릿 API 기능
        1) GenericServlet 추상클래스 : Servlet, ServletConfig 인터페이스를 구현함
        2) GenericServlet : 여러 통신 프로토콜에 대한 서블릿 기능을 구현함
        3) HttpServlet : GenericServlet 추상클래스를 상속 받음
                         HTTP 프로토콜을 사용하는 서블릿 기능을 수행함
            - protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                - 서블릿이 GET request를 수행하기 위해 호출됨
        
    4. 서블릿 Life Cycle 메서드
        1) init()       초기화 - 서블릿 요청 시 맨 처음 한 번만 호출됨. 초기화 작업 수행
        2) doGet()      작업수행 - 서블릿 요청 시 매번 호출됨
           doPost()               실제로 클라이언트가 요청하는 작업을 수행함
        3) destroy()    종료 - 메모리에서 소멸될 때 호출됨. 마무리 작업을 주로 수행
        -> init() 메서드와 destroy() 메서드는 생략 가능. doXXX() 메서드는 반드시 구현해야 함

    5. 서블릿 매핑하기
        1) http://localhost:8080/chap02_Servlet/first
                    주소   포트번호 프로젝트명  패키지명이 포함된 클래스명
            - 클래스 이름이 길어지면 불편함
            - 클래스 이름이 사용되면 보안에도 좋지 않음
                -> 서블릿 클래스에 대응하는 서블릿 매핑 이름으로 요청함(web.xml)
        2) 브라우저에서 서블릿 요청하기
            - http://IP주소:포트번호/프로젝트명(컨텍스트명)/서블릿매핑이름

        3) 다수의 서블릿 매핑하기
            - 일반적인 웹 애플리케이션은 각 기능에 대한 서블릿을 따로 만들어서 서비스를 제공함

    6. 어노테이션(annotation)을 이용한 서블릿 매핑
        1) web.xml에 여러 서블릿 매핑 설정 시 복잡해짐
        2) 가독성이 좋아짐
        3) @WebServlet을 이용해서 서블릿 매핑을 구현
        4) 어노테이션으로 설정한 맵핑명을 다른 맵핑명과 중복되면 안 됨

    7. HTTP 요청과 응답
        1) HttpServletRequest의 메서드
            - http://localhost:8080/chap02_Servlet/RequestInfo?year=2021&month=11&day=23
                http : getScheme()
                localhost : getServerName()
                chap02_Servlet : getContextPath()
                RequestInfo : getServletPath()
                year=2021&month=11&day=23 : getQueryString()
                http://localhost:8080/chap02_Servlet/RequestInfo : getRequestURL()
                chap02_Servlet/RequestInfo : getRequestURI()

     

     

    package kr.co.ezenac;
    
    import java.io.IOException;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    public class FirstServlet extends HttpServlet {		//HttpServlet을 상속받음
    	private static final long serialVersionUID = 1L;
    
    	
    	public void init(ServletConfig config) throws ServletException {
    		System.out.println("init 메서드 호출");
    	}
    
    	
    	public void destroy() {
    		System.out.println("destroy 메서드 호출");
    	}
    
    	//브라우저의 요청을 처리함
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		System.out.println("doGet 메서드 호출");
    	}
    
    }
    <?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_4_0.xsd" id="WebApp_ID" version="4.0">
      <display-name>chap02_Servlet</display-name>
      <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>
      
      <servlet>
      	<servlet-name>ezenac</servlet-name>
      	<servlet-class>kr.co.ezenac.FirstServlet</servlet-class>
      </servlet>
      
      <servlet>
      	<servlet-name>ezenac02</servlet-name>
      	<servlet-class>kr.co.ezenac.SecondServlet</servlet-class>
      </servlet>
      
      <servlet-mapping>
      	<servlet-name>ezenac</servlet-name>
      	<url-pattern>/first</url-pattern>
      </servlet-mapping>
      
      <servlet-mapping>
      	<servlet-name>ezenac02</servlet-name>
      	<url-pattern>/second</url-pattern>
      </servlet-mapping>
    </web-app>

    package kr.co.ezenac;
    
    import java.io.IOException;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    public class SecondServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	public void init(ServletConfig config) throws ServletException {
    		System.out.println("init 메서드 호출>>>");
    	}
    
    	public void destroy() {
    		System.out.println("destroy 메서드 호출>>>");
    	}
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		System.out.println("doGet 메서드 호출>>>");
    	}
    
    }

    package kr.co.ezenac;
    
    import java.io.IOException;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    @WebServlet("/third")
    public class ThirdServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	
    	public void init(ServletConfig config) throws ServletException {
    		System.out.println("ThirdServlet init 메서드 호출");
    	}
    
    	
    	public void destroy() {
    		System.out.println("ThirdServlet destroy 메서드 호출");
    	}
    
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		System.out.println("ThirdServlet doGet 메서드 호출");
    	}
    
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		System.out.println("ThirdServlet doPost 메서드 호출");
    	}
    
    }

    package kr.co.ezenac;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    @WebServlet("/RequestInfo")
    public class RequestInfo extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8"); 		//클라이언트가 요청한 파라미터 값들을 인코딩 해주는 코드
    		System.out.println("request.getCharacterEncoding() = " + request.getCharacterEncoding());
    		System.out.println("request.getContentLength() = " + request.getContentLength());	//요청 내용길이. 알 수 없을 때는 -1
    		System.out.println("request.getContentType() = " + request.getContentType());		//요쳥 내용타입. 알 수 없을 때는 null
    		
    		System.out.println("request.getMethod() = " + request.getMethod());					//요청 방법
    		System.out.println("request.getProtocol() = " + request.getProtocol());				//프로토콜의 종류와 버전
    		System.out.println("request.getScheme() = " + request.getScheme());					//프로토콜
    		
    		System.out.println("request.getServerName() = " + request.getServerName());			//서버이름 또는 ip주소
    		System.out.println("request.getServerPort() = " + request.getServerPort());			//서버 포트
    		System.out.println("request.getRequestURL() = " + request.getRequestURL());			//요쳥 URL(Uniform Resource Locator)
    		System.out.println("request.getRequestURI() = " + request.getRequestURI());			//요쳥 URI(Uniform Resource Identifier)
    		
    		System.out.println("request.getContextPath() = " + request.getContextPath());		//context path
    		System.out.println("request.getServletPath() = " + request.getServletPath());		//servlet path
    		System.out.println("request.getQueryString() = " + request.getQueryString());		//쿼리스트링
    		
    		String year = request.getParameter("year");
    		String month = request.getParameter("month");
    		String day = request.getParameter("day");
    		
    		System.out.println("year = " + year + ", month = " + month + ", day = " + day);
    	}
    
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    	}
    
    }

     

    '개발자 수업 > JSP' 카테고리의 다른 글

    6. 회원정보 등록, 삭제하기  (0) 2021.11.27
    5. JDBC 연동과 관련객체  (0) 2021.11.27
    4. 서블릿 비즈니스 로직 추가  (0) 2021.11.25
    3. 서블릿  (0) 2021.11.24
    1. 웹 프로그래밍 소개  (0) 2021.11.22

    댓글