【问题标题】:Spring-MVC 3.1: How to map URLs with a trailing slash?Spring-MVC 3.1:如何映射带有斜杠的 URL?
【发布时间】:2012-07-18 15:24:39
【问题描述】:

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

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

http://blah.blah.blah/acme/makedonation 被找到、映射和处理

http://blah.blah.blah/acme/makedonation/没有

这是我用来处理旧 URL 的控制器类

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

我搜索了一下,发现这个 Stack Overflow post 提供了一些建议,但我是 Spring 新手,对它的理解还不够,无法实施其中的一些建议。这一个听起来特别适合我的需求:

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

谁能给我一个基本的例子,给我一个有这样例子的网址(我在谷歌上没有运气)或者给我一个更好的主意?

在此先感谢 史蒂夫

【问题讨论】:

  • 我见过这样的解决方案@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)

标签: spring spring-mvc


【解决方案1】:

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

@Bean
public RequestMappingHandlerMapping useTrailingSlash() {
    return new RequestMappingHandlerMapping() {{ setUseTrailingSlashMatch(true); }};
}

【讨论】:

【解决方案2】:

您应该在 context.xml 中配置您的 bean,并设置属性。 或者你可以参考link或者spring doc部分16.4

示例配置

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

【讨论】:

  • 你是指我的 *-servlet.xml 还是我的 web.xml?
猜你喜欢
  • 1970-01-01
  • 2011-05-21
  • 2012-08-16
  • 2016-11-29
  • 2014-04-16
  • 2010-10-16
  • 1970-01-01
  • 2015-03-13
  • 2015-03-06
相关资源
最近更新 更多