-
[Servlet] URL 맵핑, Servlet 객체, 생명주기back end 2022. 3. 3. 00:24
이번 포스팅의 내용
1. servlet과 jsp를 연동해서 url 맵핑 할 수 있다.
2. context, application, session, request, response, page 객체의 원리를 이해하고 속성 및 메시지 전달을 구현할 수 있다.
class = 속성 + 메세지
class = 필드 + 메소드 -> 클래스, 상속, 다형성(동적바인딩) -> 오버로드, 오버라이딩
3. 폼데이터를 http를 이용해서 값 전달 및 리턴하는 구조를 설계할 수 있다.
4. 객체 servlet, jsp 의 생명주기를 이해하고 설명할 수 있다.
=====================================================================================
이전의 project를 close 하고 새로운 프로젝트를 만든다.
New > Dynamic Web Project
> Context root: url 맵핑할 때 사용할 Context name을 적는다. 실제 프로젝트와 이름이 달라도 상관없다.
Content directory: 프로젝트 내에 servlet이 저장될 곳의 directory 이름을 적는다.

context path 이름 바꾸기 두 가지 방법이 있다.
1. Navigator 에서 바꾸기
상단 Window > Whow View > Navigator

> .settings > org.eclipse.wst.common.componenet 에서 바꾸기.
6번째줄의 value를 원하는 이름으로 바꿔준다.

프로젝트 이름을 Web03으로 했는데, 6번줄에 context root를 myweb으로 한다고 하면,
url을 입력할 때 http://localhost:8080/Web03 대신,
http://localhost:8080/myweb으로 접근한다.
2. properties > Web Project Settings 에서 바꾸기.


Servlet과 jsp를 연동해서 URL 맵핑하기
새로 만든 프로젝트를 http://localhost:8080/myweb/으로 요청해서 URL맵핑의 GET방식을 확인한다.
http://localhost:8080/myweb/
-> web.xml
-> index.jsp (index_jsp.java -> index_jsp.class)
-> /myinsert ( /myinsert를 가진 servlet인 MyTest.java ) 으로 이동한다.
-> MyTest.java에서 Override된 doGet 메서드를 실행한다.
(페이지 요청의 기본은 GET이다. 다른 메서드가 있어도 doGet이 실행된다.)
**Servlet에서 우클릭 Source > Override/Implement Methods를 들어가면, 조상 클래스의 메서드를 다 볼 수 있다.
Servlet은 다음과 같은 조상 클래스를 갖는다. (HttpServlet << GenericServlet << Object)

Method: GET/POST
GET: 주소줄에 정보를 노출한다. 보안이 취약함. (ex. http://localhost:8080/myweb/insert/id=123&pw=123)
POST: form 데이터 보낼때 hidden으로 보내서 보안이 강하다.
Servlet 객체 확인해보기
Servlet: 서블릿 프로그램이 반드시 구현해야하는 메서드를 선언하는 인터페이스
서블릿의 생명 주기를 가진다. 아래는 생명 주기를 구현하는 매서드.
init()_서블릿 초기화 -> service()_클라이언트의 요청처리 -> destroy()_서블릿 종료
Servlet API documentation로 확인하기
https://tomcat.apache.org/tomcat-9.0-doc/servletapi/javax/servlet/Servlet.html
Servlet (Servlet {servlet.spec.version} API Documentation - Apache Tomcat 9.0.59)
Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed. After the servlet con
tomcat.apache.org

GenericServlet : Servlet 인터페이스를 상속받아서 client/servlet 환경에서 필요한 기능을 구현하는 추상클래스
HttpServlet : GenericServlet을 상속받아서 http 프로토콜에 맞는 동작을 수행하도록 구현된 클래스
HttpServletRequest : 클라이언트가 서버에 요청할때 생성되는 객체, 요청 정보를 포함하는 메서드로 구성.
HttpServletResponse : 서버가 클라이언트에게 응답할 때 생성되는 객체, 응답 정보를 포함하는 메서드로 구성.
@WebServlet({"/sdelete", "/sinsert"}) public class MyScore extends HttpServlet { // 코드가 길어질 때를 대비해서 내부 함수 정의해서 protected void doMyInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("sinsert page : "); } protected void doMyDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("sdelete page : "); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(request.getRequestURI().endsWith("sinsert")) { //doMyInsert() doMyInsert(request, response); } if(request.getRequestURI().endsWith("sdelete")) { //doMyDelete() doMyDelete(request, response); }http://localhost:8080/myweb/insert 페이지를 요청하면,
myweb Context의 index.jsp로 간다.
sinsert 기능이 구현되어있는 servlet으로 간다.
페이지 요청이 있기 때문에 doGet이 먼저 실행된다.
만약 요청된 객체의 URI(/myweb/sinsert)가 'sinsert'로 끝난다면 doMyInsert를 실행한다. 이 때, request와 response 인자를 보낸다.
response 객체에 sinsert page : 를 추가해서 출력한다.
jsp 정적페이지에서 폼데이터를 get방식, post방식으로 action을 Servlet으로 맵핑해서 출력해보자. ((form 데이터 처리))
.jsp를 생성하고 body에 form을 만든다.
http://localhost:8080/myweb/myres?myid=123&mypw=123
<form action="/myweb/myres" method="GET"> ID : <input type="text" name="myid"/> <br> PW : <input type="text" name="mypw"/> <br> <input type="submit" value = "ok"/> <input type="reset" value = "reset"/> </form>server를 run하면 아래와 같은 화면이 나오고, id와 pw를 각각 입력하고 ok를 클릭하면,

주소창에 http://localhost:8080/myweb/myres?myid=123&mypw=123 라고 뜨면서,
myres가 맵핑된 servlet으로 이동해서 method가 GET이니까 doGet을 실행한다.
@WebServlet("/myres") public class MyRes extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("myid"); // name을 호출하면 value를 리턴한다. String pw = request.getParameter("mypw"); response.getWriter().append("id: " + id).append(" pw: " + pw).append(request.getQueryString()).append(request.getMethod()); } }
QueryString()메서드는 context path 뒤에 입력값을 리턴한다.
여기서 QueryString은 ?myid=123&mypw=123 이다.
만약, method가 POST였다면 doPost를 실행한다.
Servlet의 생명주기
init()_서블릿의 초기화
database 연결 코드를 줄 수도 있고, 파일오픈, 로그파일에 로딩된 서블릿 이름을 추가
ServletConfig 객체로 넘겨받은 초기값을 설정할 때, servlet 요청횟수
service()_클라이언트의 요청처리
클라이언트가 path를 요청할때마다 호출된다.
(요청할 때마다 하나의 thread를 생성한다.)
destroy()_서블릿 종료
서블릿의 초기화에서 할당된 객체들을 명시 소멸한다.
서블릿이 재컴파일될 때 호출된다.
@WebServlet("/myservlet") public class MyServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { System.out.println("init"); } public void destroy() { System.out.println("destroy"); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("service"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doGet"); } }위의 코드를 실행해보면 아래와 같이 나오는데
init은 처음 servlet을 요청했을 때 한 번 출력되고, service는 리로드할 때마다 출력되고, server를 종료하면 destroy가 출력된다.
이때, doGet이 출력되지 않고 init, service가 호출되는 이유는 init과 service는 선조인 Servlet의 메서드이기 때문이다!!
doGet은 자식클래스인 httpServlet의 메서드!

Eclipse에서 프로젝트를 통으로 import, export하는 방법
프로젝트 우클릭 > import, export > WAR file 로 한다. 끝!
서블릿 컨테이너와 서블릿 디렉토리
- 서블릿 컨테이너란 동적으로 로드되는 자바클래스인 서블릿을 인식할 수 있는 웹서버의 기능을 말하며,
서블릿 엔진(Servlet Engine)이라고도 말한다.
-서블릿 컨테이너는 웹 애플리케이션 상에서 서블릿이 존재하는 디렉토리에 작성된
.java 파일을 .class로 컴파일 되면서 웹서버의 메모리에 로드되어 실행된다.
- 서버를 구축방법에 상관없이 서블릿 수행을 요청 받을 때마다 스레드를 병렬로 기동하여 수행하게 되는데
이러한 과정을 구현해 주는 것이 바로 웹서버 기능을 가진 톰캣이다.
- 톰캣은 웹서버에 서블릿 클래스를 실행시킬 수 있는 자바 가상머신(JVM)을 수행할 수 있게 해주는
일련의 소프트웨어이며 서블릿 컨테이너에 웹서버 기능을 내장해서 지원해주는 독립 형 서블릿 엔진이다.
-톰캣은 "%CATALINA_HOME%\webapps"을 root로 인식해서 로컬로 웹 애플리케이션을
하나의 ServletContext로 매핑하고,
여러 개의 서블릿은 각각 하나의 ServletConfig 객체를 생성하며 로딩 된다.
-HTTP상에 작동되는 서블릿은 서블릿 컨테이너 의 클라이언트의 요청과 서버 응답에 대한
프로토콜 값을 가지고 동작되며 웹 애플리케이션 단위로 구성된다.
-하나의 웹 애플리케이션을 만들 때는 컨테이너가 설정된 구조와 위치대로 애플리케이션 디렉토리를
만들어 구현시키는데, 이러한 디렉토리 구조를 ‘Servlet Directory’ 라고 부른다.
'back end' 카테고리의 다른 글
[JSP] 내장객체 (0) 2022.03.05 [JSP] JSP 엔진, 지시어 (0) 2022.03.04 [Error] HTTP Status 404 - Not Found (0) 2022.03.01 [Web Application] JSP, Servlet eclipse에서 생성하기 (0) 2022.03.01 [Web Application] 내장객체, client와 server 연동 이론 (0) 2022.03.01