java Spring MVC @RequestMapping 注解的不区分大小写映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12684183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:49:50  来源:igfitidea点击:

case insensitive mapping for Spring MVC @RequestMapping annotations

javaweb-applicationsspring-mvc

提问by Zahid Riaz

Possible Duplicate:
How can I have case insensitive URLS in Spring MVC with annotated mappings

可能的重复:
如何在带有注释映射的 Spring MVC 中使用不区分大小写的 URL

I have Controller having multiple @RequestMapping annotations in it.

我的 Controller 中有多个 @RequestMapping 注释。

@Controller
public class SignUpController {

 @RequestMapping("signup")
 public String showSignUp() throws Exception {
    return "somejsp";
 }

 @RequestMapping("fullSignup")
 public String showFullSignUp() throws Exception {
    return "anotherjsp";
 }

 @RequestMapping("signup/createAccount")
 public String createAccount() throws Exception {
    return "anyjsp";
 }
}

How can I map these @RequestMapping to case insensitive. i.e. if I use "/fullsignup" or "/fullSignup" I should get "anotherjsp". But this is not happening right now. Only "/fullSignup" is working fine.

如何将这些 @RequestMapping 映射为不区分大小写。即如果我使用“/fullsignup”或“/fullSignup”,我应该得到“anotherjsp”。但这不是现在发生的。只有“/fullSignup”工作正常。

I've tried extending RequestMappingHandlerMapping but no success. I've also tried AntPathMatcher like the guy mentioned there is another question on this forum but its also not working for @RequestMapping annotation.

我试过扩展 RequestMappingHandlerMapping 但没有成功。我也试过 AntPathMatcher 就像那个人提到的在这个论坛上有另一个问题,但它也不适用于 @RequestMapping 注释。

Debugging console enter image description here

调试控制台 在此处输入图片说明

Output console when server is up.

服务器启动时的输出控制台。

enter image description here

在此处输入图片说明

I've added two images which shows the problem. I've tried both the solutions mentioned below. The console says that it mapped lowercased URLS but when I request to access a method with lowercase url then it shows that the original map where the values are stored stilled contained MixCase URLS.

我添加了两个显示问题的图像。我已经尝试了下面提到的两种解决方案。控制台说它映射了小写的 URL,但是当我请求访问带有小写 url 的方法时,它显示存储值的原始映射仍然包含 MixCase URL。

采纳答案by Biju Kunjummen

One of the approaches in How can I have case insensitive URLS in Spring MVC with annotated mappingsworks perfectly. I just tried it with combinations of @RequestMapping at the level of controller and request methods and it has worked cleanly, I am just reproducing it here for Spring 3.1.2:

其中一个在接近我怎么能在Spring MVC不区分大小写的网址映射注释的作品完美。我只是在控制器和请求方法级别结合@RequestMapping 进行了尝试,并且运行良好,我只是在此处为 Spring 3.1.2 重现它:

The CaseInsensitivePathMatcher:

CaseInsensitivePathMatcher:

import java.util.Map;

import org.springframework.util.AntPathMatcher;

public class CaseInsensitivePathMatcher extends AntPathMatcher {
    @Override
    protected boolean doMatch(String pattern, String path, boolean fullMatch, Map<String, String> uriTemplateVariables) {
        return super.doMatch(pattern.toLowerCase(), path.toLowerCase(), fullMatch, uriTemplateVariables);
    }
}

Registering this path matcher with Spring MVC, remove the <mvc:annotation-driven/>annotation, and replace with the following, configure appropriately:

用Spring MVC注册这个路径匹配器,去掉<mvc:annotation-driven/>注解,用下面的替换,适当配置:

<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="conversionService" ref="conversionService"></property>
            <property name="validator">
                <bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
                    <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
                </bean>
            </property>
        </bean>
    </property>
    <property name="messageConverters">
        <list>
            <ref bean="byteArrayConverter"/>
            <ref bean="jaxbConverter"/>
            <ref bean="jsonConverter"/>
            <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>
        </list>
    </property>
</bean>
<bean name="byteArrayConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
<bean name="jaxbConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean>
<bean name="jsonConverter" class="org.springframework.http.converter.json.MappingHymanson2HttpMessageConverter"></bean>
<bean name="caseInsensitivePathMatcher" class="org.bk.lmt.web.spring.CaseInsensitivePathMatcher"/>
<bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="pathMatcher" ref="caseInsensitivePathMatcher"></property>
</bean>

Or even more easily and cleanly using @Configuration:

或者使用@Configuration 更轻松、更干净:

@Configuration
@ComponentScan(basePackages="org.bk.webtestuuid")
public class WebConfiguration extends WebMvcConfigurationSupport{

    @Bean
    public PathMatcher pathMatcher(){
        return new CaseInsensitivePathMatcher();
    }
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = new RequestMappingHandlerMapping();
        handlerMapping.setOrder(0);
        handlerMapping.setInterceptors(getInterceptors());
        handlerMapping.setPathMatcher(pathMatcher());
        return handlerMapping;
    }
}

回答by Jerome Dalbert

The following simple solution should make @RequestMapping insensitive, whether it annotates a Controller or a method. Biju's solution should work too.

以下简单的解决方案应该使@RequestMapping 不敏感,无论是注释控制器还是方法。Biju 的解决方案也应该有效。

Create this custom HandlerMapping :

创建这个自定义 HandlerMapping :

public CaseInsensitiveAnnotationHandlerMapping extends DefaultAnnotationHandlerMapping {

    @Override
    protected Object lookupHandler(String urlPath, HttpServletRequest request)
                    throws Exception {

        return super.lookupHandler(urlPath.toLowerCase(), request);
    }

    @Override
    protected void registerHandler(String urlPath, Object handler)
                    throws BeansException, IllegalStateException {

        super.registerHandler(urlPath.toLowerCase(), handler);
    }

}

And add this in your [servlet-name]-servlet.xml :

并将其添加到您的 [servlet-name]-servlet.xml 中:

<bean class="yourpackage.CaseInsensitiveAnnotationHandlerMapping" />

Note: if you don't want two HandlerMapping in your app, you may want to remove <mvc:annotation-driven />(it instantiates a DefaultAnnotationHandlerMapping).

注意:如果你不想在你的应用程序中使用两个 HandlerMapping,你可能想要删除<mvc:annotation-driven />(它实例化一个DefaultAnnotationHandlerMapping)。