簡體   English   中英

如何在SpringBoot中使用SimpleUrlHandlerMapping

[英]How to Use SimpleUrlHandlerMapping with SpringBoot

我正在使用SpringBoot,並想為我的自定義映射配置SimpleUrlHandlerMapping bean。 為此,下面是我編寫的代碼。

@Configuration
public class WebConfiguration {

    @Bean
    public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
        System.out.println("creating  SimpleUrlHandlerMapping ....");
        SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
        simpleUrlHandlerMapping.setOrder(0);
        Properties urlProperties = new Properties();
        urlProperties.put("/index", "myController");

        simpleUrlHandlerMapping.setMappings(urlProperties);

        return simpleUrlHandlerMapping;
    }
}

我還有一個名稱為myController的Controller,其代碼如下所示。

@Controller("myController")
public class MyController extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
        System.out.println("My Controller!");
        return null;
    }

}

現在按照代碼,當點擊http:// localhost:7171 // index時,它將在控制台上打印My Controller消息。 但是它不碰這個代碼。 因為這是一個SpringBoot應用程序,並且在啟動時使用myController打印此bean注冊。

有人可以幫助解決此問題,並告訴我這段代碼有什么問題。

提前致謝。

配置類中的@Autowire Controller Bean並將其通過Properties傳遞

SimpleUrlHandlerMapping是最靈活的HandlerMapping實現。 它允許在bean實例和URL之間或bean名稱和URL之間進行直接和聲明性映射。

讓我們將請求“ / simpleUrlWelcome”和“ / * / simpleUrlWelcome”映射到“ welcome” bean: 這里

@Configuration
public class WebConfiguration {

@Autowired
private indexController index;

@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
    System.out.println("creating  SimpleUrlHandlerMapping ....");
    SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
    simpleUrlHandlerMapping.setOrder(0);
    Properties<String,Object> urlProperties = new Properties<>();
    urlProperties.put("/index", index);

    simpleUrlHandlerMapping.setMappings(urlProperties);

    return simpleUrlHandlerMapping;
     }
 }

調節器

@Controller("index")
public class indexController extends AbstractController {

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
    System.out.println("My Controller index!");
    return null;
     }

 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM