본문 바로가기

IT/Spring

Spring MVC 예제

1. 구조

Spring에서 데이터는 많은 과정을 거친다. Client 요청하면 Dispatcher 가운데에서 조율을 하면서

데이터들은 Controller, Dao, Service, Model, DB, View 통해 이동한다.

 

 

2. Spring MVC

Spring MVC 대해 알아야 사항은 모든 요청을 Dispatcher Servlet 받는 다는 . 그래서 적절하게 처리할 Controller URL 따라 선택하기 위해 Hanlder Mapping 이용하고,

선택된 Controller 요청을 처리하고 ModelAndView 돌려준다.

Dispatcher Servlet 돌아오는 View Name 바탕으로 View Resolver 호출해 View 얻고

여기에 Model 적용해 Response 만들어 Request 보냈던 Client 에게 돌려준다.

 

Controller View 역할도 비슷하고, Backbone 이나 Node Router Handler Mapping 것도 비스무리 하다. 이름만 다를 . 조금 다른 점은 View 묶어 View Resolver 관리 한다는 이다.

하지만 사실 Backbone 에서도 많은 View 배열이나 기타 등등을 통해 관리한다는 점을 보면, 프로그래머가 구현했어야 하는 Spring MVC 해준다는 정도의 차이만 존재한다.

기능상으로는 차이가 없다.

 

 

  

  

비슷한 일을 하는 보이는, DAO(Data Access Object) Service 차이

 

DAO : 단일 데이터에 [접근, 갱신]만을 처리한다.

Service : 여러 DAO 호출하여 여러 번의 데이터 [접근, 갱신] 하며 읽은 데이터에 대해 [비즈니스 로직 수행], [하나의 트랜잭션으로 묶음].

 

마디로 DAO이상의 일들을 service 처리하며, 비즈니스 로직 구조가 복잡하게 될수록 service 중요해진다는 같음.

간혹, Service DAO 동일해지는 경우, 비즈니스 로직이 단일 DB접근으로 끝날 때이다.

 

 


 

 

Sample mvc만드는 방법  

 

 

 

 

 

 

 

 

 

 

  

, 항상 보던 Controller 보자

 

package com.mashee.app;

 

/**

 * Handles requests for the application home page.

 */

@Controller

public class HomeController {

       

        private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

       

        /**

         * Simply selects the home view to render by returning its name.

         */

        @RequestMapping(value = "/", method = RequestMethod.GET)

        public String home(Locale locale, Model model) {

               logger.info("Welcome home! The client locale is {}.", locale);

              

               Date date = new Date();

               DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

              

               String formattedDate = dateFormat.format(date);

               

 

               model.addAttribute("serverTime", formattedDate );

              

               return "home";

        }

       

}


 

 

 

위와 똑같은 소스임.

package com.mashee.app;

 

/**

 * Handles requests for the application home page.

 */

@Controller

public class HomeController {

       

        private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

       

        /**

         * Simply selects the home view to render by returning its name.

         */

        @RequestMapping(value = "/", method = RequestMethod.GET)

        public String home(Locale locale) {

               logger.info("Welcome home! The client locale is {}.", locale);

              

               Date date = new Date();

               DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

              

               String formattedDate = dateFormat.format(date);

               

               ModelAndView model = new ModelAndView("home","serverTime",formattedDate);

              

               return model;

        }

       

}

 

 

 

 

@RequestMapping("/Test/{smthing}")

public ModelAndView showOwner(@PathVariable("smting") int smthing) {

    ModelAndView mav = new ModelAndView("Test/smthingDetails");

    mav.addObject(this.clinicService.findOwnerById(smthing));

    return mav;

}

 

 

 

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 

        <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->

        <context-param>

               <param-name>contextConfigLocation</param-name>

               <param-value>/WEB-INF/spring/root-context.xml</param-value>

        </context-param>

       

        <!-- Creates the Spring Container shared by all Servlets and Filters -->

        <listener>

               <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

        </listener>

 

        <!-- 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>

 

</web-app>

 

 

이제 좀 알겠네, <context-parm>을 통해서 선언된 contextConfigLocation Root spring Container를 선언한거지.

, <parm-value>의 위치에 있는 root-context.xml을 모든 filter servlet들이 공유 가능하게 하는거.

 

그리고, <listener>는 정의가 아니라 create이라고 되어 있는데 이게 무얼 의미하는지 잘 모르겠는데, 이 역시 spring container관련한 것.

 

 

다음은, <servlet-name> <servlet-class>를 이용해서, Servlet과 관련된 내용들인데, 서블릿이 사용할 이름과, 위치를 선언하고 <init-param>을 통해 설정에 관한 xml을 설정한다.

그리고, mapping을 통해서, url 패턴을 정해주고, 이 패턴이 들어오면 servlet으로 연결하게 시킨다.

 


 

 

이건 servlet-context.xml인데,

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/mvc"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xmlns:beans="http://www.springframework.org/schema/beans"

        xmlns:context="http://www.springframework.org/schema/context"

        xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd

               http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 

        <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

       

        <!-- Enables the Spring MVC @Controller programming model -->

        <annotation-driven />

 

        <!-- 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.mashee.app" />

       

       

       

</beans:beans>

 

 

<annotation-driven/>을 선언해줌으로써, Annotation을 통해서 java에서 @Controller, @Requestmapping과 같은 annotation을 사용한 programming을 가능하게 해준다.

 

<resources mapping> HTTP GET 요청을 /resource/**로 처리하기 위함이다.

이는 정적인 리소스들을 ${webappRoot}/resources 디렉터리에 효율적으로 전달한다.

, CSS image가 있는 statis폴더를 지정

 

<beans:bean>을 통해서, ViewResolver를 지정해주고,

Prefix suffix를 통해 view의 위치와, 파일타입을 지정한다.

 

마지막으로 context:component-scan base-package를 통해서 component base package를 지정해줌. => controller 어디있는지 말해주는거임.

 

 

'IT > Spring' 카테고리의 다른 글

Spring Annotation 설명 및 예제  (0) 2015.01.31
Spring에서 excel 사용하기 JXL & POI 개념 및 예제  (2) 2015.01.23
Spring JDBC framework 개념 및 예제  (0) 2015.01.22
Spring-IOC (DI) 개념 및 예제  (2) 2015.01.21
Spring 이론  (0) 2015.01.20