2013년 8월 25일 일요일

JSP/Servlet을 기반으로한 MVC모델의 요청처리 - 3 (요청 처리 인터페이스작성과 구현 및 RequestMapping)


요청을 처리할 클래스가 구현할 인터페이스 작성

MyService.java

  1 package com.jch;
  2 
  3 import java.io.IOException;
  4 
  5 import javax.servlet.ServletException;
  6 import javax.servlet.http.HttpServletRequest;
  7 import javax.servlet.http.HttpServletResponse;
  8 
  9 public interface MyService {
 10     public String execute(HttpServletRequest req, HttpServletResponse resp) 
 11             throws ServletException, IOException;
 12 }


인터페이스 구현

TestImpl.java

  1 package com.jch;
  2 
  3 import java.io.IOException;
  4 
  5 import javax.servlet.ServletException;
  6 import javax.servlet.http.HttpServletRequest;
  7 import javax.servlet.http.HttpServletResponse;
  8 
  9 public class TestImpl implements MyService {
 10 
 11     @Override
 12     public String execute(HttpServletRequest req, HttpServletResponse resp)
 13             throws ServletException, IOException {
 14         
 15         //request에 content를 키로 하는 값 심기
 16         req.setAttribute("content", "요청 처리 완료");
 17         //view리턴
 18         return "test.jsp";
 19     }
 20 
 21 }


서블릿 구현과 요청을 처리할 클래스의 구현이 완료 되었다.

web.xml을 수정하여 서블릿에 RequestMapping을 하도록 한다.
RequestMapping이란 서블릿이 어느 요청을 처리할지 정의 하는 것이다.

WebContent/WEB-INF 디렉토리에 web.xml 파일 생성(프로젝트 생성 시 Generate web.xml deployment discriptor 옵션을 체크했다면 미리 생성되어있음)

web.xml

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  3     xmlns="http://java.sun.com/xml/ns/javaee" 
  4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
  5     id="WebApp_ID" version="3.0">
  6     
  7   <display-name>ExWebProject</display-name>
  8   
  9 <!-- 디폴트로 보여줄 페이지 -->
 10 <!-- 위에서 부터 아래순으로 페이지를 찾는다. -->
 11   <welcome-file-list>
 12     <welcome-file>index.html</welcome-file>
 13     <welcome-file>index.htm</welcome-file>
 14     <welcome-file>index.jsp</welcome-file>
 15     <welcome-file>default.html</welcome-file>
 16     <welcome-file>default.htm</welcome-file>
 17     <welcome-file>default.jsp</welcome-file>
 18   </welcome-file-list>
 19   
 20 <!-- 서블릿 등록 -->
 21   <servlet>
 22 <!-- 서블릿 명 -->
 23       <servlet-name>MyServlet</servlet-name>
 24 <!-- 서블릿 클래스 지정 -->
 25       <servlet-class>com.jch.MyServlet</servlet-class>
 26   </servlet>
 27   
 28 <!-- 서블릿 매핑 -->
 29   <servlet-mapping>
 30 <!-- 서블릿 명 -->
 31       <servlet-name>MyServlet</servlet-name>
 32 <!-- 요청을 처리할 패턴 지정 확장자가 MyServlet인 요청이 들어오면 처리 -->
 33       <url-pattern>*.MyServlet</url-pattern>
 34   </servlet-mapping>
 35   
 36 </web-app>

server.xml에 프로젝트 등록

이제 까지 프로젝트가 서버에 등록된 것은 아니었다. 프로젝트를 등록하게되면 서버가 구동될때
프로젝트를 server.xml 파일과 등록된 프로젝트의 web.xml파일을 읽고 필요한 클래스를 로드한다.

프로젝트 오른쪽 클릭 Run As -> Run on Server를 클릭한다. Apache Tomcat V7.0을 선택하고
Finish를 누르면 서버구동 server.xml에 프로젝트가 자동으로 등록된다.

수동으로 설정을 하려면 server.xml파일의 <Host></Host>사이에 <Context>앨리먼트를 추가하여 프로젝트를 등록한다.

댓글 없음:

댓글 쓰기