2013년 8월 25일 일요일

JSP/Servlet을 기반으로한 MVC모델의 요청처리 - 2 (프로젝트 생성 및 Servlet 구현)

우선 웹 프로젝트를 생성하도록 한다.
Eclipse에서 File -> New -> Dynamic Web Project

프로젝트 명을 정하고 New Runtime을 눌러 구동 시킬 서버를 지정한다.






Apache Tomcat v7.0 을 선택하고 Next






Browse를 눌러 Apache Tomcat이 있는 디렉토리를 지정한 후 Finish






Finish를 눌러 프로젝트 생성



서블릿 클래스 구현
HttpServlet 클래스를 상속받아 init()메소드와 doGet(), doPost()메소드를 구현한다.
MyService는 인터페이스로 서비스를 처리할 클래스가 구현해야할 인터페이스이다.

MyServlet.java

  1 package com.jch;
  2 
  3 import java.io.IOException;
  4 import java.util.HashMap;
  5 
  6 import javax.servlet.RequestDispatcher;
  7 import javax.servlet.ServletException;
  8 import javax.servlet.http.HttpServlet;
  9 import javax.servlet.http.HttpServletRequest;
 10 import javax.servlet.http.HttpServletResponse;
 11 
 12 public class MyServlet extends HttpServlet {
 13     HashMap<String,MyService> hm = new HashMap<String,MyService>();
 14     
 15     @Override
 16     public void init() throws ServletException {
 17         // 초기화 함수
 18         // '/test' 요청을 처리내용을 구현한 TestImpl객체를 HashMap에 넣음
 19         // TestImpl은 MyService를 구현하였음
 20         hm.put("/test", new TestImpl());
 21     }
 22 
 23     @Override
 24     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
 25             throws ServletException, IOException {
 26         //Get 방식 요청 처리
 27         //doJob()으로 위임
 28         doJob(req, resp);
 29     }
 30 
 31     @Override
 32     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
 33             throws ServletException, IOException {
 34         //Post 방식 요청 처리
 35         //doJob()으로 위임
 36         doJob(req, resp);
 37     }
 38     
 39     public void doJob(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
 40         
 41         //요청이 제대로 들어왔는지 확인
 42         String command = req.getRequestURI();
 43         if(command.indexOf(req.getContextPath())==0){
 44             command = command.substring(req.getContextPath().length());
 45         }
 46         
 47         //HashMap에서 요청을 처리할 객체 얻어옴
 48         MyService service = hm.get(command);
 49         
 50         //execute() 메소드를 통해 서비스를 수행하고 view(jsp)리턴
 51         //hm.get()에서 command에 해당하는 Service가 없다면 널포인터익셉션이 발생함
 52         String view = service.execute(req, resp);
 53         
 54         //view이름의 jsp파일로 forward하기위함 foward를 하여 request를 그대로 가져간다.
 55         RequestDispatcher dispatcher = req.getRequestDispatcher(view);
 56         // view에 해당하는 페이지를 보여줌
 57         // ex) view="test.jsp"일때 화면에 test.jsp를 띄움
 58         dispatcher.forward(req, resp);
 59     }
 60 }
 
다음 장에서 MyService 인터페이스를 생성하고 그것을 구현한 TestImpl 클래스를 작성함 

댓글 없음:

댓글 쓰기