Spring-MVC 3.1:如何使用尾部斜杠映射URL?

时间:2012-07-19 12:28:17

标签: spring spring-mvc

我正在将旧的servlet应用程序转换为Spring 3.1。在此过程中,一些URL现在已过时。我们的网络存在一些问题,不会很快得到解决。我的老板不想相信他们的重定向将始终可操作。所以,她让我把自己的重定向放到webapp中。

一切都很好,除非如果URL有一个尾部斜杠,Spring 3.1将找不到处理它的Controller类函数。

找到,映射和处理

http://blah.blah.blah/acme/makedonation

http://blah.blah.blah/acme/makedonation /不

以下是我用来处理旧版网址的控制器类

import org.springframework.stereotype.Controller;
import org.springframework.validation.*;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;


import org.apache.log4j.Logger;

@Controller
public class LegacyServletController {

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

    // Redirect these legacy screns "home", the login screen via the logout process
    @RequestMapping({"makeadonation","contact","complain"})
    public String home() {
        logger.debug("started...");
        return "redirect:logout";

    }// end home()  

}// end class LegacyServletController

我用Google搜索并发现这个Stack Overflow post提供了一些建议,但我是Spring的新手,并且对它的实施不够了解。这个听起来特别适合我的需求:

  

spring 3.1 RequestMappingHandlerMapping允许你设置一个   “useTrailingSlashMatch”属性。默认情况下,这是真的。我认为   将其切换为false将解决您的问题,

有人会给我一个如何做到这一点的基本例子,引用一个有这样一个例子的网址(我没跟谷歌好运)或者给我一个更好的想法吗?

非常感谢 史蒂夫

2 个答案:

答案 0 :(得分:6)

您应该在context.xml中配置bean,并设置property。  或者您可以参考link或春季文档部分16.4

示例配置

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="useTrailingSlashMatch" value="true">
    </property>
</bean>

答案 1 :(得分:2)

如果您使用的是Spring的Java @Configuration,您也可以像这样声明@Bean

@Bean
public RequestMappingHandlerMapping useTrailingSlash() {
    return new RequestMappingHandlerMapping() {{ setUseTrailingSlashMatch(true); }};
}
相关问题