1. ROOT 디렉토리 구조
* 디렉토리 설명
ROOT : / 디렉토리
src : java 소스 파일
classes : 클래스 파일 ( /servlet/ 폴더가 참조하는 곳)
2. applelet VS servlet 의미
- 애플릿(applet) : 브라우저에서 다운로드 되서 실행되는 java 프로그램
- 서브릿(servlet) : 서버에서 실행되는 java 프로그램
3. 간단한 HelloServlet 소스 작성하기
import javax.servlet.*; // servlet-api.jar 에 들어있다.
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// 웹브라우저가 보여줄 내용의 타입(Content Type, Mime Type) 설정
res.setContentType("text/html");
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// 웹브라우저가 보여줄 내용의 타입(Content Type, Mime Type) 설정
res.setContentType("text/html");
// 웹브라우저와 연결하여 쓰기 작업을 할 스트림을 할당받는다. / 브라우저와 스트림 연결
PrintWriter pw = res.getWriter();
// ServletOutputStream os = res.getOutputStream(); // 1 바이트 기반
PrintWriter pw = res.getWriter();
// ServletOutputStream os = res.getOutputStream(); // 1 바이트 기반
pw.println("<html><body>");
pw.println("<h1>Hello Servlet!</h1>");
pw.println("<img src='/tomcat.gif'>");
pw.println("</body></html>");
// 스트림 자원 반납 , 연결 끊기
pw.close();
} // doGET().......
}
pw.println("<h1>Hello Servlet!</h1>");
pw.println("<img src='/tomcat.gif'>");
pw.println("</body></html>");
// 스트림 자원 반납 , 연결 끊기
pw.close();
} // doGET().......
}
컴파일 방법 : class 파일은 WEB-INF 하위에 classes 폴더에 저장한다.
javac -d ../classes *.java
한글처리를 위해서는 charset=EUC-KR 을 설정해 주어야 한다.
res.setContentType("text/html;charset=EUC-KR");
4. 서블릿(servlet) 실행하기
웹브라우서를 이용해서 실행 : http://localhost:9090/servlet/(클래스명)
혹시 나오지 않는다면 tomcat 을 재시작한뒤 다시 요청해 본다.
아직까지 servlet 이란 개념은 잡기는 힘들지만 HelloServlet 을 통해서 간단한 servlet 을 작성해 보았다.
참고> http://localhost:9090/hello.html
webapps\ROOT <----- 컨텍스트(Context)
+--- *.html, *.jsp, *.js, *.css, *.gif, *.jpg .. 등을 파일을 /(root) 에 배치가능
+---WEB-INF
+--- src : *.java[HelloServlet.java]
+--- classes : *.class[HelloServlet.class]
+--- lib
+--- web.xml
+--- *.html, *.jsp, *.js, *.css, *.gif, *.jpg .. 등을 파일을 /(root) 에 배치가능
+---WEB-INF
+--- src : *.java[HelloServlet.java]
+--- classes : *.class[HelloServlet.class]
+--- lib
+--- web.xml
** webapps/ROOT/ --> http://IP:PORT/
** http://localhost:9090/servlet/ : WEB-INF -> classes 디렉토리를 alias 한 것이다.