반응형

<참조> https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/mvc.html

Spring WEB MVC 프레임워크 (5)

 

작업중... 

 

13. ETag 지원

 

<filter>
  <filter-name>etagFilter</filter-name>
    <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>etagFilter</filter-name>
  <servlet-name>petclinic</servlet-name>
</filter-mapping>

14. 코드 기반 서블릿 컨테이너 초기화

 

import org.springframework.web.WebApplicationInitializer;
public class MyWebApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        XmlWebApplicationContext appContext = new XmlWebApplicationContext();
        appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }
}

 

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MyWebConfig.class };
    }
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

 

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        XmlWebApplicationContext cxt = new XmlWebApplicationContext();
        cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
        return cxt;
    }
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

 

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
    // ...
    @Override
    protected Filter[] getServletFilters() {
        return new Filter[] { new HiddenHttpMethodFilter(), new CharacterEncodingFilter() };
    }
}

 

15 스프링 MVC 설정

 

15.1 MVC 자바 구성 또는 MVC XML 네임스페이스 활성화

 

@Configuration
@EnableWebMvc
public class WebConfig {
}

XML에서 동일한 결과를 얻으려면 mvc:annotation-driven 요소를 사용하자.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <mvc:annotation-driven />
</beans>
  1.  

15.2 제공된 구성 사용자 정의

 

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  protected void addFormatters(FormatterRegistry registry) {
    // Add formatters and/or converters
  }
  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    // Configure the list of HttpMessageConverters to use
  }
}

.

<mvc:annotation-driven conversion-service="conversionService">
    <mvc:message-converters>
        <bean class="org.example.MyHttpMessageConverter"/>
        <bean class="org.example.MyOtherHttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="formatters">
        <list>
            <bean class="org.example.MyFormatter"/>
            <bean class="org.example.MyOtherFormatter"/>
        </list>
    </property>
</bean>

15.3 인터셉터 구성

 

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LocaleInterceptor());
    registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
    registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*");
 }
}

XML에서는 다음 <mvc:interceptors>요소를 사용한다.

<mvc:interceptors>
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
    <mvc:interceptor>
        <mapping path="/**"/>
        <exclude-mapping path="/admin/**"/>
        <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor" />
    </mvc:interceptor>
    <mvc:interceptor>
        <mapping path="/secure/*"/>
        <bean class="org.example.SecurityInterceptor" />
    </mvc:interceptor>
</mvc:interceptors>

15.4 콘텐츠 협상 구성

 

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false).favorParameter(true);
  }
}
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="true" />
    <property name="mediaTypes" >
        <value>
            json=application/json
            xml=application/xml
        </value>
    </property>
</bean>

 

15.5 뷰 컨트롤러 구성

 

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("home");
  }
}

XML에서도 동일한 <mvc:view-controller> 요소를 사용한다.

<mvc:view-controller path="/" view-name="home"/>

15.6 리소스 제공 구성

 

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/public-resources/");
  }
}

XML에서도 마찬가지이다.

<mvc:resources mapping="/resources/**" location="/public-resources/"/>

 

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/public-resources/").setCachePeriod(31556926);
  }
}

그리고 XML에서:

<mvc:resources mapping="/resources/**" location="/public-resources/" cache-period="31556926"/>

 

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
      .addResourceLocations("/", "classpath:/META-INF/public-web-resources/");
  }
}

그리고 XML에서:

<mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/public-web-resources/"/>

 

application.version=1.0.0

util:properties그런 다음 속성 파일의 값을 태그 를 사용하여 빈으로 SpEL에 액세스할 수 있도록 합니다 .

<util:properties id="applicationProps" location="/WEB-INF/spring/application.properties"/>

resources이제 SpEL을 통해 애플리케이션 버전에 액세스할 수 있으므로 이를 태그 사용에 통합할 수 있습니다 .

<mvc:resources mapping="/resources-#{applicationProps['application.version']}/**" location="/public-resources/"/>

 

@Configuration
@EnableWebMvc
@PropertySource("/WEB-INF/spring/application.properties")
public class WebConfig extends WebMvcConfigurerAdapter {
  @Inject Environment env;
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources-" + env.getProperty("application.version") + "/**")
      .addResourceLocations("/public-resources/");
  }
}

마지막으로 적절한 URL로 리소스를 요청하기 위해 Spring JSP 태그를 활용할 수 있습니다.

<spring:eval expression="@applicationProps['application.version']" var="applicationVersion"/>
<spring:url value="/resources-{applicationVersion}" var="resourceUrl">
    <spring:param name="applicationVersion" value="${applicationVersion}"/>
</spring:url>
<script src="${resourceUrl}/dojo/dojo.js" type="text/javascript"> </script>

15.7 mvc:기본 서블릿 핸들러

 

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
  }
}

또는 XML:

<mvc:default-servlet-handler/>

 

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable("myCustomDefaultServlet");
  }
}

또는 XML:

<mvc:default-servlet-handler default-servlet-name="myCustomDefaultServlet"/>

15.8 더 많은 스프링 웹 MVC 리소스

  •  

15.9 MVC Java 구성을 사용한 고급 사용자 지정

 

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
  @Override
  public void addInterceptors(InterceptorRegistry registry){
    // ...
  }
  @Override
  @Bean
  public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
      // Create or let "super" create the adapter
      // Then customize one of its properties
  }
}

 

15.10 MVC 네임스페이스를 사용한 고급 사용자 지정

 

@Component
public class MyPostProcessor implements BeanPostProcessor {
  public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
    if (bean instanceof RequestMappingHandlerAdapter) {
      // Modify properties of the adapter
    }
  }
}

 

반응형

+ Recent posts