【问题标题】:How could I map "/test/test" to a method of a controller, which is mapped to "/test"?如何将“/test/test”映射到控制器的方法,该方法映射到“/test”?
【发布时间】:2012-11-04 20:01:09
【问题描述】:

我对 Spring 的 @RequestMapping 注释的行为感到困惑。在以下代码中,test() 映射到 "/test"test_test() 映射到 "/test/test/test"。这里发生了什么?如果我想将test()映射到"/test/test"应该怎么办?

package com.mvc.spring;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/test")
public class Test {
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    String test() {
        return "test";
    }

    @RequestMapping(value = "/test/test", method = RequestMethod.GET)
    String test_test() {
        return "test";
    }
}

【问题讨论】:

  • 试试....@RequestMapping({"/test","/test/test"})
  • 您可以做的其他方法是删除请求映射(在控制器注释之后)
  • @PratapMurukutla 那行不通。日志显示Mapped "{[/test || /test/test/test], ...
  • 我不知道你尝试了什么......在我看到你的问题之后,出于好奇,我对此进行了研究并尝试使用我的答案,令人惊讶的是我在评论中的第一个答案有效..

标签: spring model-view-controller controller annotations


【解决方案1】:

Spring 是故意这样做的;当方法和类型级别的请求映射模式值匹配时,它只使用其中之一。 @见org.springframework.util.AntPathMatcher#combine()

一种方法是在方法级别为 RequestMapping 值添加“/”后缀(如下所示),这样您就可以使用 "/test/test/" 作为 url(NOT /test/test,当然)。

@Controller
@RequestMapping(value = "/test")
public class Test {
    @RequestMapping(value = "/test/", method = RequestMethod.GET)
    String test() {
        return "test";
    }
}

不知道为什么没有记录。

所以,我认为匹配"/test/test" url 的唯一方法是使用URI 模板模式。

@Controller
@RequestMapping(value = "/test")
public class Test {
    @RequestMapping(value = "/{anythinghere}", method = RequestMethod.GET)
    String test() {
        return "test";
    }
}

【讨论】:

  • 感谢您的回答,但 "/{anythinghere}" 也匹配 "/test/" 后跟任何字符串,例如它匹配"/test/abc"
  • 所以没有办法映射到"/test/test"?是不是spring框架的bug?
猜你喜欢
  • 2011-08-05
  • 1970-01-01
  • 2012-10-25
  • 2021-11-20
  • 2018-07-09
  • 1970-01-01
  • 2015-09-25
  • 2018-01-24
相关资源
最近更新 更多