简体   繁体   中英

How to Use SimpleUrlHandlerMapping with SpringBoot

I am using SpringBoot and want to configure SimpleUrlHandlerMapping bean for my custom mapping. For that follow are the piece of code that I wrote.

@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;
    }
}

I also have one Controller with name myController and its code looks like this.

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

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

}

Now as per code when http://localhost:7171//index is hit then it should print the My Controller message on console. But it not touch this code. Because this is an SpringBoot application and on start it print this bean registration with myController.

Could someone help to resolve this issue and tell me whats wrong in this code.

Thanks in advance.

@Autowire Controller Bean in Configuration class and pass it through Properties

SimpleUrlHandlerMapping is the most flexible HandlerMapping implementation. It allows for direct and declarative mapping between either bean instances and URLs or between bean names and URLs.

Let's map requests “/simpleUrlWelcome” and “/*/simpleUrlWelcome” to the “welcome” bean: here

@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

@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;
     }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM