[英]How to define a default handler in Spring Boot 2
How can I define a default handler, or controller action, that will be invoked when no other handler is found for a given URL?如何定义默认处理程序或控制器操作,当找不到给定 URL 的其他处理程序时将调用该处理程序?
I tried by using a catch-all pattern /**
(syntax is Kotlin):我尝试使用一个包罗万象的模式
/**
(语法是 Kotlin):
@Controller
class DefaultController {
@RequestMapping("/**")
fun default(...) {
...
}
}
But this gets matched with higher precedence that Spring's own handlers, for example the static file path configured in spring.mvc.static-path-pattern
is no longer available.但这与Spring 自己的处理程序的更高优先级相匹配,例如
spring.mvc.static-path-pattern
配置的静态文件路径不再可用。 I need my default handler to have the lowest precedence.我需要我的默认处理程序具有最低优先级。
You would have to add your implementation of HandlerMapping
and add it to list of handlers.您必须添加
HandlerMapping
的实现并将其添加到处理程序列表中。 You need to specify the order of handlers taking care of request as well:您还需要指定处理请求的处理程序的顺序:
@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
SimpleUrlHandlerMapping simpleUrlHandlerMapping
= new SimpleUrlHandlerMapping();
Map<String, Object> urlMap = new HashMap<>();
urlMap.put("/**", defaultController());
simpleUrlHandlerMapping.setUrlMap(urlMap);
simpleUrlHandlerMapping.setOrder(1);
return simpleUrlHandlerMapping;
}
Here the defaultController()
method returns a @Controller
, that you have defined for the given mapping, so DefaultController
.这里
defaultController()
方法返回一个@Controller
,它是您为给定映射定义的,所以DefaultController
。 The setOrder
method defines a priority (order) of handlers, starting from 0. Of course some default HandlerMapping
must be defined as a @Bean
as well. setOrder
方法定义了处理程序的优先级(顺序),从 0 开始。当然一些默认的HandlerMapping
必须定义为@Bean
。 More about such configuration you can find here .您可以在此处找到有关此类配置的更多信息。
Edit with some thoughts from @Tobia:使用@Tobia 的一些想法进行编辑:
You need to remove the @RequestMapping
annotation so that the controller is not picked up by RequestMappingHandlerMapping
and implement the AbstractController
interface to override the definition of controller in handleRequestInternal()
.您需要删除
@RequestMapping
注释,以便RequestMappingHandlerMapping
不会选择控制器并实现AbstractController
接口以覆盖handleRequestInternal()
的控制器定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.