Search Results for '첫단추'

1 POSTS

  1. 2010.04.29 Spring MVC 따라하기 Step1.

Spring MVC 따라하기 Step1.

Posted 2010. 4. 29. 01:49

환경 : WinXP, JDK 1.6.0_15, eclipse galileo 3.5, Tomcat 6.0, SpringFramework 2.5, JUnit4.x
관련문서 : http://static.springsource.org/docs/Spring-MVC-step-by-step/part1.html

A. jsp 구동테스트
1. eclipse에서 새로운 프로젝트 생성(Dynamic Web Project)한다.
 프로젝트명은 Springapp, 폴더구조는 src, WebContent
2. WebContent/WEB-INF/web.xml에서 welcome-file 을 index.jsp로 수정
2.1 WebContent 폴더밑에 index.jsp 생성.
3. eclipse Server를 Tomcat6으로 연결. 포트는 기본포트인 8080으로 한다.
4. Add and Remove를 클릭하여 생성한 Springapp추가.
5. 시작하고 http://localhost:8080/Springapp/index.jsp 호출해서 화면 나오면 성공.

B. Spring 모듈추가 테스트
1. 다운받은 Spring 관련 jar중에 spring.jar, spring-webmvc.jar, commons-logging.jar를 WebContent/lib 에 추가
2. web.xml파일에 DispatcherServlet 등록

 <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

3. 같은 위치에 web.xml에서 정의한 servlet-name과 같은 이름-servlet.xml 파일명으로 xml 파일 생성.
 이 파일은 DispatherServlet에서 이용되는 모든 bean관련 설정내용이 포함한다. 웹애플리케이션과 관련된 컴포넌트를 모두 이 DispatherServlet을 거치게 된다.

  <bean name="/hello.do" class="springapp.web.HelloController"/>


4. springapp.web.HelloController.java 파일 생성, 당연히 WebContent/hello.jsp 생성.
 public class HelloController implements Controller {
    protected final Log logger = LogFactory.getLog(getClass());
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info("Returning hello view");
        return new ModelAndView("hello.jsp");
    }
}

5. 여기까지 설정하고 바로 브라우저에서 http://localhost:8080/springapp/hello.do  호출해서 테스트해도 되지만 JUnit 으로 테스트 한번 해보자. 일단 lib 폴더에 junit4.x.jar를 받는다. 그리고 HelloControllerTest 클래스 생성.

 public class HelloControllerTest extends TestCase{
 public void testHandleRequestView() throws Exception{  
        HelloController controller = new HelloController();
        ModelAndView modelAndView = controller.handleRequest(null, null);  
        assertEquals("hello.jsp", modelAndView.getViewName());
    }
}

테스트 끝나면 OK, 실패하면?

4까지 완료후 브라우져에서 http://localhost:8080/testProject/hello.do 를 호출한다.
8080 다음의 이름은 eclipse에서 프로젝트 생성한 이름으로 WebContext가 잡히기 때문에 혹시 이부분 에러가 나거나 404 Not Found가 나온다면 생성한 프로젝트 명으로 바꾸면 된다.