使用Spring mvc中的标头请求映射

时间:2013-12-18 10:28:45

标签: spring-mvc

目前我正在使用标头使用Spring mvc请求映射。

以下是我的两种方法:

方法1:

@RequestMapping(value = "/accounts", method = RequestMethod.GET,
headers="Accept=application/vnd.se.company1.product1+json; version=2.0")

@ResponseBody
public ResponseEntity<String> loginVerionOne(final HttpServletRequest request){}

方法2:

@RequestMapping(value = "/accounts", method = RequestMethod.GET,
headers="Accept=application/vnd.se.company1.product1+json; version=3.0")

@ResponseBody
public ResponseEntity<String> loginVersionTwo(final HttpServletRequest request) {}

这里的问题是当客户端以下面的格式在其请求中发送accept头时: Accept=application/vnd.se.company1.product1+json; version=3.0

然后,即使版本为3.0,spring也只映射到第一种方法 我在其中一篇文章中读到,春天在使用标题的请求映射中忽略; (分号)后的请求映射。

我们正在使用自定义接受标头,我们需要单独保留内容类型和版本。

如果我使用以下格式的Accept标头,则映射有效: Accept=application/vnd.se.company1.product1.v2.0+json

但我不想使用上述格式 欢迎任何有关此问题的帮助。

以下是我使用的代码:

RequestMappingController
========================
@RequestMapping(value = "/helloworld",method=RequestMethod.GET)
        @SubdomainMapping(subdomains="application/vnd.se.company1.product1+json;version=2.0")
    public ModelAndView helloWordNew(HttpServletRequest req){
         String message = "Hello World Version 2.0";
         return new ModelAndView("helloworld", "message",message);
    }
    @RequestMapping(value = "/helloworld",method=RequestMethod.GET)
    @SubdomainMapping(subdomains="application/vnd.se.company1.product1+json;version=3.0")
    public ModelAndView helloWord(HttpServletRequest req){
          String message = "Hello World Version 3.0";
          return new ModelAndView("helloworld", "message",message);
    }

RequestCondition:
================

public class SubdomainRequestCondition implements
        RequestCondition<SubdomainRequestCondition> {

    private final Set<String> subdomains;


    public SubdomainRequestCondition(String subdomains) {
        this(Arrays.asList(subdomains));
    }

    public SubdomainRequestCondition(Collection<String> subdomains) {
        this.subdomains = Collections.unmodifiableSet(new HashSet<String>(
                subdomains));
    }

    @Override
    public SubdomainRequestCondition combine(SubdomainRequestCondition other) {
        Set<String> allRoles = new LinkedHashSet<String>(this.subdomains);
        allRoles.addAll(other.subdomains);
        return new SubdomainRequestCondition(allRoles);
    }

    @Override
    public SubdomainRequestCondition getMatchingCondition(
            HttpServletRequest request) {
            String header = request.getHeader("Accept");
            for (String s : subdomains) {
                if (s.equals(header)) {
                    return this;
                }
            }
        return null;
    }

   @Override
    public int compareTo(SubdomainRequestCondition other,
            HttpServletRequest request) {
        return org.apache.commons.collections.CollectionUtils.removeAll(other.subdomains, this.subdomains).size();
    }
}

HandlerMapping
==============

public class CustomRequestMappingHandlerMapping extends
        RequestMappingHandlerMapping {
   @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        SubdomainMapping typeAnnotation = AnnotationUtils.findAnnotation(
                handlerType, SubdomainMapping.class);
        return createCondition(typeAnnotation);
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        SubdomainMapping methodAnnotation = AnnotationUtils.findAnnotation(
                method, SubdomainMapping.class);
        return createCondition(methodAnnotation);
    }

    private RequestCondition<?> createCondition(SubdomainMapping accessMapping) {
        return (accessMapping != null) ? new SubdomainRequestCondition(accessMapping.subdomains()) : null;
    }
}



   applicationContext.xml
    ======================
    <context:component-scan base-package="com.net.controllers"/>

        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">

            <property name="prefix">
                <value>/WEB-INF/views/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>

        <bean name="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <property name="webBindingInitializer">
            <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
               <property name="validator">
                    <bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
                </property>
            </bean>
        </property>
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter"></bean>
                <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
                <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
                <bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean>
                <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
            </list>
        </property>
        </bean>
<bean id="re" class="com.net.controllers.WebConfig"/>
</beans>

WebConfig.java
==============

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Autowired

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        CustomRequestMappingHandlerMapping handlerMapping = new CustomRequestMappingHandlerMapping();
        handlerMapping.setOrder(0);
        handlerMapping.setInterceptors(getInterceptors());
        return handlerMapping;
    }

     @Bean
        @Override
        public FormattingConversionService mvcConversionService() {

            // Use the DefaultFormattingConversionService but do not register defaults
            DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(false);
            return conversionService;
        }
}

2 个答案:

答案 0 :(得分:1)

内容协商有一些特殊属性:consumesproduces。在你的情况下,它将是

@RequestMapping(value = "/accounts", method = RequestMethod.GET,
produces="application/vnd.se.company1.product1+json; version=2.0")

但这并不能解决你的问题。 Spring在查找匹配时仅考虑媒体类型和子类型。这是一种硬编码行为。

我可以提供两种解决方案:

解决方案1 ​​

仅映射到媒体类型并具有单独的私有方法。像

这样的东西
@RequestMapping(value = "/accounts", method = RequestMethod.GET,
produces="application/vnd.se.company1.product1+json")
@ResponseBody
public ResponseEntity<String> login(final HttpServletRequest request){
   if(getVersion(request).equals(VERSION_2)) {
     loginVersion2(request);

解决方案2

实施您自己的映射条件。这并不难,但官方文档中没有任何参考。您必须谷歌org.springframework.web.servlet.mvc.condition.RequestCondition

答案 1 :(得分:0)

用逗号分隔两个标题:

headers = {"Accept=application/vnd.se.company1.product1+json", "version=3.0"})