Springmvc Dispatcher Servlet 원리 및 용법 분석

Dispatcher Servlet 은 전단 컨트롤 러 디자인 모델 의 실현 으로 Spring Web MVC 의 집중 방문 점 을 제공 하고 직책 을 담당 하 는 할당 이 며 Spring IoC 용기 와 빈 틈 없 이 통합 되 어 Spring 의 모든 장점 을 얻 을 수 있 습 니 다.Dispatcher Servlet 은 주로 직책 스케줄 링 업무 로 사용 되 는데 그 자체 가 통제 절차 에 사용 되 고 주요 직책 은 다음 과 같다.
  • 파일 업로드 분석,요청 형식 이 multipart 이면 MultipartResolver 를 통 해 파일 업로드 분석 을 진행 합 니 다
  • Handler Mapping 을 통 해 프로세서 에 요청 을 표시 합 니 다(프로세서 하나,Handler Interceptor 차단기 여러 개 포함)
  • HandlerAdapter 를 통 해 다양한 종류의 프로세서(HandlerExecutionChain 의 프로세서)를 지원 합 니 다
  • ViewResolver 를 통 해 논리 보기 이름 을 구체 적 인 보기 로 해석 하여 실현 합 니 다
  • 현지 화 해석;
  • 구체 적 인 보기 등 을 렌 더 링 합 니 다.
  • 실행 중 이상 이 발생 하면 Handler ExceptionResolver 에 게 맡 깁 니 다.
  • DispathcherServlet 설정 상세 설명
    
    		<servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <!-- servlet-mapping -->
      <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    load-on-startup:용 기 를 시작 할 때 이 Servlet 을 초기 화 하 는 것 을 의미 합 니 다
  • url-pattern:Spring Web MVC 에 어떤 요청 을 맡 겼 는 지 표시 합 니 다."/"는 기본 servlet 맵 을 정의 하 는 데 사 용 됩 니 다.html 를 확장자 로 하 는 모든 요청 을 차단 할 수 있 습 니 다
  • contextConfigLocation:SpringMVC 프로필 의 경 로 를 표시 합 니 다

  • 스프링 구성
    서비스 패 키 지 를 추가 하고 HelloService 클래스 를 제공 합 니 다.다음 과 같 습 니 다.
    
    @Service 
    public class HelloService { 
    	public String hello(String name) { 
    		return "hello " + name; 
    		} 
    }
    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"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/context 
        https://www.springframework.org/schema/context/spring-context.xsd">
      <context:component-scan base-package="org.javaboy" use-default-filters="true">
        <context:exclude-filter type="annotation"
           expression="org.springframework.stereotype.Controller"/>
      </context:component-scan>
    </beans>
    이 프로필 은 기본적으로 자동 으로 불 러 오지 않 습 니 다.모든 것 은 웹.xml 에서 설정 해 야 합 니 다.
    
    <context-param> 
    	<param-name>contextConfigLocation</param-name> 
    	<param-value>classpath:applicationContext.xml</param-value> 
    </context-param> 
    <listener> 
    	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
    우선 context-param 을 통 해 Spring 프로필 의 위 치 를 지정 합 니 다.이 프로필 에 도 기본 규칙 이 있 습 니 다.프로필 이름 은 기본적으로 applicationContext.xml 이 라 고 합 니 다.또한 이 프로필 을 WEB-INF 디 렉 터 리 에 두 면 설정 파일 의 위 치 를 지정 하지 않 고 모니터 만 지정 하면 됩 니 다.이 설정 은 Spring 통합 웹 환경의 일반적인 설정 입 니 다.일반적으로 웹 층 을 제외 한 Bean(예 를 들 어 DAO,Service 등)을 불 러 와 다른 모든 웹 프레임 워 크 와 통합 할 수 있 도록 합 니 다.
    contextConfigLocation:Bean 을 불 러 올 프로필 을 표시 합 니 다.
    contextClass:Bean 을 불 러 오 는 응용 프로그램 Context 구현 클래스 를 표시 합 니 다.기본 웹 응용 프로그램 Context 입 니 다.
    MyController 에 Hello Service 주입:
    
    @org.springframework.stereotype.Controller("/hello")
      public class MyController implements Controller {
        @Autowired
        HelloService helloService;
    
        /**
         *             
         * * @param req             
         * * @param resp              
         * * @return        ModelAndView,Model            ,
         * View        * @throws Exception
         */
        public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
          System.out.println(helloService.hello("javaboy"));
          ModelAndView mv = new ModelAndView("hello");
          mv.addObject("name", "javaboy");
          return mv;
        }
      }
    SpringMVC 용기 에서 MyController 를 스 캔 할 수 있 도록 MyController 에@Controller 주 해 를 추가 하 였 으 며,현재 사용 하고 있 는 Handler Mapping 은 BeanNameUrl Handler Mapping(요청 주소 가 프로세서 Bean 의 이름 임 을 의미 함)이기 때문에 수 동 으로 MyController 의 이름 을 지정 해 야 합 니 다.
    마지막 으로 SpringMVC 의 프로필 을 수정 하고 Bean 을 스 캔 형식 으로 설정 합 니 다.
    
    <context:component-scan base-package="org.javaboy.helloworld" use-default-filters="false">  
    		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    
    <!--         ,    ,           Bean    ,       bean            -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" id="handlerMapping">  
    	<property name="beanName" value="/hello"/>
    </bean>
    
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" id="handlerAdapter"/>
    <!--     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">  
    	<property name="prefix" value="/jsp/"/>  
    	<property name="suffix" value=".jsp"/>
    </bean>
    설정 이 완료 되면 프로젝트 를 다시 시작 합 니 다.Spring 용기 도 생 성 됩 니 다./hello 인터페이스 에 접근 하면 Hello Service 의 hello 방법 이 자동 으로 호출 됩 니 다.
    용기 두 개

    Spring 과 SpringMVC 가 동시에 나타 나 면 프로젝트 에 두 개의 용기 가 존재 합 니 다.하 나 는 Spring 용기 이 고 다른 하 나 는 SpringMVC 용기 입 니 다.Spring 용 기 는 ContextLoaderListener 를 통 해 로드 되 고 SpringMVC 용 기 는 Dispatcher Servlet 을 통 해 로드 됩 니 다.이 두 용 기 는 다 릅 니 다.
    그림 에서 볼 수 있다.
  • ContextLoader Listener 가 초기 화 한 컨 텍스트 로 불 러 온 Bean 은 전체 응용 프로그램 에 공 유 된 것 입 니 다.어떤 표현 층 기술 을 사용 하 든 보통 DAO 층,Service 층 Bean 과 같 습 니 다
  • Dispatcher Servlet 초기 화 된 컨 텍스트 에 불 러 온 Bean 은 Spring Web MVC 에 만 효과 적 인 Bean 입 니 다.예 를 들 어 Controller,HandlerMapping,HandlerAdapter 등 이 초기 화 된 컨 텍스트 는 웹 관련 구성 요소 만 불 러 와 야 합 니 다
  • 그 럴 리 가 없어.서버 에 요청 한 후 Dispatcher Servlet 를 찾 아 처리 하기 때문에 SpringMVC 용기 에서 만 찾 을 수 있 습 니 다.이 는 Controller 가 SpringMVC 용기 에서 스 캔 해 야 한 다 는 뜻 입 니 다.
    2.왜 SpringMVC 용기 에서 모든 Bean 을 스 캔 하지 않 습 니까?
    이것 은 가능 합 니 다.SpringMVC 용기 에서 모든 Bean 을 스 캔 할 수 있 습 니 다.함께 쓰 지 않 는 데 는 두 가지 이유 가 있다.
  • 프로필 관 리 를 편리 하 게 하기 위해
  • Spring+SpringMVC+Hibernate 조합 에서 도 이러한 표기 법 은 사실상 지원 되 지 않 는 다
  • 이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기