728x90

1. SpringMVC에서 Controller 가 View를 찾는  방법

@RequestMapping어노테이션에 적힌 url로 요청하면

해당 어노테이션이 부여된 메소드가 호출되면서 return에 적힌 jsp페이지를 자동으로 사용자에게 응답하게 됩니다. 

SpringMVC에서는 최초로 사용자로부터 요청을 전달받게되면 DispatcherServlet이 수신합니다.

 

DispatcherServlet ( web.xml )

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

Spring MVC 프로젝트 생성 후 web.xml(배포서술자)를 읽어보면 우선 /로 시작한다면 즉, 모든요청이 appServlet( DispathcherServlet )으로 매핑 됩니다.

 

또한 init-param(초기화 파라미터)의 값으로 /WEB-INF/spring/appServlet/ servlet-context.xml

가지고 생성 되는 것을 볼 수 있습니다.

 

/WEB-INF/spring/appServlet/servlet-context.xml

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.bk.myapp" />

DispatcherServlet이 생성되면서 초기화 파라미터로 가지는 xml파일을 열어보게 되면 다음과 같습니다. 

InternalResourceViewResolver를 빈으로 가지게 되는데 사용자에게 보여줄 view를 찾기 위한 prefix, suffix를 제공합니다. 예로들면 controller에서는 home을 return하게 되는데 prefix인 /WEB-INF/views/  home 

그리고 suffix인 .jsp를 합쳐 /WEB-INF/views/하위에 존재하는 home.jsp를 찾아 사용자에게 보여주게 됩니다.

ViewResolver는 사용자에게 결과를 렌더링하여 보여주는 역할을 합니다. 

   

DispatcherServlet은 사용자의 요청을 최초로 전달 받은 후 Controller로 전달합니다.

<context:component-scan base-package="com.bk.myapp" />

<context:component-sca base-package="패키지경로"/>

component-scan은 @Component 어노테이션 뿐만아니라 

Streotype(@Controller, @Service, @Repository)등을 자동으로 스캔하여 Bean으로 등록해 줍니다.

 

이 덕분에 HomeController 상단의 @Controller 어노테이션을 보고 Bean으로 등록한 후

Controller에게 요청을 전달할 수 있습니다.

model addAttribute("key", "value");메소드를 이용해 view에 값을 전달할 수 있습니다.

그리고 return에 적혀있는 view를 사용자에게 응답하게됩니다.


DI ( 의존성 주입 )

DI IOC Container가 개발자 대신 xml파일에 정의된 대로Bean객체를 생성하고 의존성을 대신 주입하는 것을 의미한다. spring의 IOC Container가 대신 해준다.

  • 첫번째 방법은 A객체가 B와 C객체를 New 생성자를 통해서 직접 생성하는 방법 
  • 두번째 방법은 외부에서 생성 된 객체를 setter()나 생성자를 통해 사용하는 방법

메인클래스를 보시면 방법1 처럼 직접 객체를 생성하지 않고

GenericXmlApplicationContext를 사용하여 객체(bean)을 외부에서 얻어와서 호출(사용)을 합니다.

외부는 configLocation에 담겨 있는 위치 이며, 객체(bean)을 생성한 applicationContext.xml을 보면

DI(의존성 주입)을 적용한 두번째 예제는 직접 객체를 생성하지 않고, 외부(applicationContext.xml)에서 객체를 생성 후 사용할 객체에 주입을 시켜주어 사용 합니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
 
<!-- "diEx.Cats"클래스를 cats라는 id를 지정해서 객체(bean)을 생성 -->
<!-- "이 객체(bean)의 이름(id)은 cats입니다. 
        cats는 diEx패키지에 있는 Cats 클래스를 말합니다." 라고 선언 --> 
<bean id="cats" class="diEx.Cats" />
 
 
<!-- "diEx.MyCats"클래스를 myCats라는 id를 지정해서 객체(bean)을 생성 -->
<bean id="myCats" class="diEx.MyCats">
    <!-- diEx.MyCats라는 클래스에 있는 필드들의 값을 설정해줌 -->
    <property name="cats"><!-- 첫번째 property(필드) -->
        <ref bean="cats"/><!-- 이 property는 위에서 생성한 bean(객체)인 cats를 참조한다. -->
    </property>
    <property name="firstCatName" value="순덕" /><!-- MyCats의 필드의 이름과 값을 설정 -->
    <property name="secondCatName" value="나비" />
    <property name="firstCatAge" value="1" />
    <property name="secondCatAge" value="2" />
</bean>
</beans>

IOC Container(Spring Container)

  • 가장 중요한 인터페이스는 ApplicatonContext이다
  • 애플리케이션 컴포넌트의 중앙 저장소이다.
  •  설정 소스로 부터  정의를 읽어들이고, 빈을 구성하고 제공한다.
  • 빈들의 의존 관계를 설정해준다.(객체의 생성을 책임지고, 의존성을 관리한다)

- 설정 방법

1. XML 파일 기술

2. @(어노테이션) 사용

728x90

+ Recent posts