티스토리 뷰

처음 하는 스프링(Spring), pom.xml과 web.xml에 이어서.

처음 하는 WebApplicationContext

이제 본격적인 Spring 설정 과정을 살펴보도록 하자.
이번 포스팅에선 설정을 더 간결하게, context:component-scan의 내용을 참고하였다.

1. Root WebApplicationContext

root1
root-context.xml 파일을 열면 아직까진 아무 내용도 없는 상태이다.

root2
Spring 설정은 Namespace를 통해서 더욱 쉽게 할 수 있는데,
Root WebApplicationContext 설정에선 context Namespace를 사용할 예정이므로 체크해주도록 하자.

root3
다시 소스 코드 부분으로 가면 context가 추가된 것을 볼 수 있다.

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
    
    <context:component-scan base-package="com.first">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>
cs

root-context.xml 파일에서는 Controller를 제외한 나머지 자원들을 제어할 수 있도록 component-scan의 범위를 지정해주었다.

2. Servlet WebApplicationContext(DispatcherServlet)

begin1
다음으로 begin-servlet.xml 파일을 살펴보도록 하겠다.
마찬가지로 처음 만들어진 상태를 가져와봤는데, 약간 다른 부분이 보일 것이다.
root-context.xml과 달리 기본 Namespace가 beans가 아닌 mvc로 되어있는데,
Spring 설정에서 가장 많이 다루는 부분이 beans Namespace여서 이 부분을 beans로 바꿔주도록 하자.

begin2
위와 같이 beans와 mvc의 선언을 서로 바꿔서, beans가 기본 Namespace가 되도록 해 주었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
    
    
    <mvc:annotation-driven />
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <context:component-scan base-package="com.first" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>
cs

이번 포스팅에서 구현하고자 하는 begin-servlet.xml의 완성된 모습이다.
간단히 설명을 하자면, DispatcherServlet에서 Request를 받아서 Controller에 전달하는 과정에 있어서 HandlerMapping과 HandlerAdapter라는 두 단계를 거치게 된다.
(저 둘에 대해선 추후 자세히 포스팅해볼 예정이다.)
지금은 RequestMappingHandlerMapping과 RequestMappingHandlerAdapter를 사용하기 위해서 간단히 한 줄로 표현하기 위해 <mvc:annotation-driven />을 사용한다 정도로 넘어가려고 한다.
resourses 태그는 Web의 정적 자원의 경로 매핑과 관련된 부분인데, 지금은 사용하지 않기 때문에 지워주도록 하자.
ViewResolver 설정 부분에서는 jsp 파일을 모아놓는 폴더의 이름을 바꿔준 부분만 반영해주었다.
마지막으로 root-context.xml에서 제외했던 Controller만 제어할 수 있도록 component-scan의 범위를 지정해주었다.

3. View(jsp)
Spring 개발에 필요한 최소한의 설정을 마무리해주었다.
이제 이를 바탕으로 설정한 것이 잘 적용되었는지 Controller를 만들어서 간단히 테스트해보도록 하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <strong>처음 시작하는 index.jsp</strong><br/>
    <div>
        <form action="/sample.bgn" method="post">
            <button onclick="submit">처음 만든 버튼</button>
        </form>
    </div>
</body>
</html>
cs

먼저, index.jsp 페이지에서 다른 페이지로 이동할 수 있는 버튼을 하나 만들도록 하자.
앞서 DispatcherServlet이 특정 URL 패턴을 가로채서 처리하도록 web.xml에서 설정을 했었는데, 그러한 패턴이 잘 적용되도록 /sample.bgn과 같이 지정해주자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>
    Begin Project!  
</h1>
<P>  "처음 만든 버튼"을 누르셨습니다! </P>
</body>
</html>
cs

다음은 /WEB-INF/view 경로에 sample.jsp 파일을 하나 만든 다음, 페이지가 넘어왔음을 알 수 있게 아무 내용이나 써서 저장하도록 하자.

4. Controller
보여줄 화면이 준비가 되었다.
이제 화면을 넘겨줄 Controller를 작성해보도록 하자.

controller1
controller 패키지에 SampleController.java 파일을 만들었다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.first.begin.sample.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class SampleController {
 
    @RequestMapping("/sample.bgn")
    public String sampleView() {
        return "sample";
    }
 
}
cs

간단히 설명을 하자면, 6번 라인에 @Controller와 같이 애노테이션 선언을 해주면 해당 클래스는 begin-servlet.xml이 Controller라고 인식을 한다.
이제 SampleController.java 파일은 우리 프로젝트의 Controller가 된 것이다.
다음으로 9번 라인의 @RequestMapping("/sample.bgn") 애노테이션 선언을 해석하자면, /sample.bgn에 해당하는 URL로 요청이 올 경우 애노테이션이 적용된 메소드에서 처리를 하겠다는 의미이다.
아래의 메소드는 요청을 받으면 "sample"이라는 단순한 문자열을 리턴하도록 처리되어 있는데, 여기서 리턴된 문자열이 바로 DispatcherServlet에서 지정해 준 ViewResolver가 매핑할 jsp의 파일명이다.

즉, 위의 Controller를 한마디로 다시 설명하자면, "/sample.bgn URL을 요청받으면 sample.jsp를 보여준다"는 의미이다.

5. 확인하기
이제 마지막으로 페이지가 잘 넘어가는지 확인해보도록 하자.

view1
서버를 실행하고 접속해보면 추가한 버튼이 보인다.

view2
버튼을 눌러보면 '/sample.bgn' URL의 sample.jsp 페이지로 넘어간 것을 확인할 수 있다.

이번 포스팅까지 해서 최소한의 Spring 개발 환경을 구축하고, 아주 간단한 테스트를 진행해보았다.
다음은 DB에 대한 내용을 정리해보려고 한다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함