gpt4 book ai didi

spring - SimpleUrlHandlerMapping的Java配置( Spring 启动)

转载 作者:行者123 更新时间:2023-12-04 05:38:31 25 4
gpt4 key购买 nike

我有一个现有的Spring Web应用程序,该应用程序使用两个扩展AbstractController的 Controller 。我想将Spring Boot集成到应用程序中,以便我们可以将其作为独立的应用程序运行。

我遇到了一个问题,因为Spring没有将调用转发给我的 Controller 。如何将 Controller 映射到“/app/*”之类的URL模式?

SampleController.java

@Controller("myController")
public class SampleController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.getWriter().print("Hello world!");
return null;
}
}

应用程序
@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}

@Bean
public SimpleUrlHandlerMapping sampleServletMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();

Properties urlProperties = new Properties();
urlProperties.put("/index", "myController");

mapping.setMappings(urlProperties);

return mapping;
}
}

当我启动应用程序时,我收到以下消息:
INFO  [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping] Mapped URL path [/index] onto handler 'myController'

但是,当我向/index发送请求时,收到以下消息:
DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] Looking up handler method for path /index
DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] Did not find handler method for [/index]
DEBUG [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping] Matching patterns for request [/index] are [/**]
DEBUG [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping] URI Template variables for request [/index] are {}
DEBUG [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping] Mapping [/index] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.ResourceHttpRequestHandler@11195d3e] and 1 interceptor

最佳答案

SimpleUrlHandlerMappings是有序的,并且作为described in the javadoc的默认值是Integer.MAX_VALUE,这意味着它们的优先级最低。这会导致ResourceHttpRequestHandler(默认情况下映射到/**并具有Integer.MAX_VALUE - 1的顺序)优先于 Controller 的映射。

更新sampleServletMapping()方法以将映射顺序设置为小于Integer.MAX_VALUE - 1的值。例如:

@Bean
public SimpleUrlHandlerMapping sampleServletMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MAX_VALUE - 2);

Properties urlProperties = new Properties();
urlProperties.put("/index", "myController");

mapping.setMappings(urlProperties);


return mapping;
}

关于spring - SimpleUrlHandlerMapping的Java配置( Spring 启动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25037113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com