【问题标题】:Spring MVC 3: same @RequestMapping in different controllers, with centralised XML URL mapping (hybrid xml/annotations approach)Spring MVC 3:不同控制器中的相同@RequestMapping,具有集中式 XML URL 映射(混合 xml/注释方法)
【发布时间】:2012-06-29 03:33:00
【问题描述】:

我喜欢将所有映射保存在同一个地方,所以我使用 XML 配置:

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

    <property name="mappings">
        <value>
            /video/**=videoControllerr
            /blog/**=blogController
        </value>
    </property>
    <property name="alwaysUseFullPath">
        <value>true</value>
    </property>
</bean>

如果我在不同的控制器中创建具有相同名称的第二个请求映射,

@Controller
public class BlogController {
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String info(@RequestParam("t") String type) {
        // Stuff
    }
}

@Controller
public class VideoController {
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String info() {
        // Stuff
    }
}

我得到一个例外:

Caused by: java.lang.IllegalStateException: Cannot map handler 'videoController' to URL path [/info]: There is already handler of type [class com.cyc.cycbiz.controller.BlogController] mapped.

有没有办法在不同的控制器中使用相同的请求映射?

我希望有 2 个网址:

/video/info.html

/blog/info.html

使用 Spring MVC 3.1.1

编辑: 我不是唯一一个: https://spring.io/blog/2008/03/24/using-a-hybrid-annotations-xml-approach-for-request-mapping-in-spring-mvc

应用程序的其余部分运行良好。

【问题讨论】:

  • 我不这么认为,因为这两个请求映射都是由两个不同的映射处理程序/适配器处理的。你能告诉我你决定保留SimpleUrlHandlerMapping的原因吗?
  • 只是个人喜好问题。我喜欢把它集中起来,而不是在每个控制器中定义。我认为它也提供了更大的灵活性。

标签: spring spring-mvc request-mapping


【解决方案1】:

只需将请求映射也放在控制器级别:

@Controller
@RequestMapping("/video")
public class VideoController {
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String info() {
        // Stuff
    }
}

@Controller
@RequestMapping("/blog")
public class BlogController {
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String info(@RequestParam("t") String type) {
        // Stuff
    }
}

【讨论】:

  • +1,这个,你不能像 XML 和基于注释的映射那样玩混合和匹配。它们由不同的映射器处理,而不是“加在一起”
  • @Biju:那是我试图避免的。
  • @Affe:你可能是对的,但这对我来说很有意义。见编辑。
【解决方案2】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 2016-07-04
  • 2015-11-28
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
相关资源
最近更新 更多