Spring boot - 控制器捕获所有URL [英] Spring boot - Controller catching all URLs

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

问题描述

我正在构建一个Spring启动Web应用程序并使用注释进行控制器/ URL映射。

I am building a Spring boot web app and am using annotations for controller/url mapping.

我有几个用 @RequestMapping注释的控制器设置的url值(空字符串和特定URL)工作正常,例如

I have several controllers annotated with @RequestMapping with the url value set (both empty strings and specific URLs) which are working fine e.g.

@Controller
@RequestMapping("/accounts")
class SignInController {

    @Autowired PartyService partyService

    @RequestMapping(value="", method = RequestMethod.GET )
    public String signinPage( Model model) {

导航到/ accounts渲染登录页面正确。

Navigating to /accounts renders the sign-in page correctly.

但是,如果我添加一个没有 RequestMapping 值的控制器,例如

However, if I add a controller with no RequestMapping values e.g.

@Controller
class CustomController {

    @RequestMapping
    public String transform( Model model ) {

然后我输入的任何与任何其他特定控制器不匹配的URL都是gett由这个控制器处理(所以页面我希望404只是渲染这个页面)。这是预期的行为吗?我没想到这一点,并且由于RequestMapping值默认为空并且是一个antMatcher,我不会认为它会处理所有其他URL。

Then any URL I enter that doesn't match any other specific controller is getting handled by this controller (so pages I would expect to 404 all just renderthis page). Is this expected behaviour? I was not expecting this, and as the RequestMapping value defaults to empty and is an antMatcher I wouldn't have thought it would handle all other URLs.

我有的原因这个控制器没有 RequestMapping 定义是因为我想要一个 SimpleUrlMappingHandler 定义了一些明确的URL转到那个控制器,如果我不包括 @Controller & @RequestMapping 对该控制器的注释然后我收到一个关于无法找到处理程序方法的错误(可能问题是我误解了它的实现细节) 。

The reason I have this controller with out RequestMapping defined is because I want to also have a SimpleUrlMappingHandler defined with some explicit URLs going to that controller, and if I don't include the @Controller & @RequestMapping annotations to that controller then I get an error about not being able to find the handler method (maybe the problem is that I have mis-understood the implementation details of that).

我的自定义控制器应该处理所有网址吗?如果是这样,有什么我可以做的,所以它没有,只被调用显式的 SimpleUrlMappingHandler 我已定义?

Should my custom controller be handling all URLs? If so, is there something I can do so it doesnt and only gets called for the explicit SimpleUrlMappingHandler I have defined?

推荐答案

如评论中所述 - 我刚从类中删除了 @Controller 注释,然后将控制器明确定义为我的配置类中的 @Bean 并明确地将其分配给 SimpleUrlMappingHandler 配置中的映射

As mentioned in the comments - I just removed the @Controller annotation from the class, and then explicitly defined the controller as a @Bean in my config class and explicitly assigned that to the mapping in the SimpleUrlMappingHandler configuration

这篇关于Spring boot - 控制器捕获所有URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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