Java Spring中的重载控制器方法 [英] Overload Controller Method in Java Spring

查看:192
本文介绍了Java Spring中的重载控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器需要使用不同的URL参数表现不同。这样的事情:

I have a controller that needs to behave differently with different URL parameters. Something like this:

@RequestMapping(method = RequestMethod.GET)
public A getA(@RequestParam int id, @RequestParam String query) {
    ...
}


@RequestMapping(method = RequestMethod.GET)
public A getA(@RequestParam int id) {
    ...
}

但这似乎不合适为了工作,我得到以下异常:

But this doesn't seem to work, I get the following exception:

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '[controller name]' bean method 

有没有办法让应用程序选择依赖方法在URL params?

Is there a way that the application chooses the method depending on the URL params?

推荐答案

在映射中指出哪些参数应该存在

Indicate in the mapping which params should be present

@RequestMapping(method = RequestMethod.GET, params = {"id", "query"})
public A getA(@RequestParam int id, @RequestParam String query) {
    ...
}


@RequestMapping(method = RequestMethod.GET, params = {"id"})
public A getA(@RequestParam int id) {
    ...
}

这篇关于Java Spring中的重载控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆