0

I have created a dedicated url mapper using SimpleUrlHandlerMapping in Spring Boot 2.

Below you can see a simplified code that only use one controller and maps only 2 urls: /url1 and /url2 to PageController.

My problem is that now Spring sends not only /url1 request but all static(js, css, ...) requests to PageController.

Why this happens and how can I avoid it?

@Configuration
public class SimpleUrlHandlerMappingConfig {

    @Autowired
    private PageRepository pageRepository;

    @Bean
    public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
        SimpleUrlHandlerMapping simpleUrlHandlerMapping
                = new SimpleUrlHandlerMapping();

        Map<String, Object> urlMap = fillMappingsFromDb();
        simpleUrlHandlerMapping.setUrlMap(urlMap);
        return simpleUrlHandlerMapping;
    }

    private Map<String, Object> fillMappingsFromDb() {
        List<String> sefUrls = pageRepository.findMappings();
        Map<String, Object> urlMap = new HashMap<>();
        for (String sefUrl : sefUrls) {
            urlMap.put(sefUrl, page());
        }
        return urlMap;
    }

    @Bean
    public PageController page() {
        return new PageController();
    }
}
Vmxes
  • 2,329
  • 2
  • 19
  • 34

1 Answers1

0

You can specify resources to be excluded from the default dispatcher servlet.

Assuming your static content is in a directory named resources:

Using xml

<mvc:resources mapping="/resources/**" location="/resources/" />

Using java config in a class that extends WebMvcConfigurerAdapter

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
secondbreakfast
  • 4,194
  • 5
  • 47
  • 101
  • Unfortunately this solution with resourceHandler doesn't work for me. All static requests are still processed by the PageController. I don't know why. I already had a problem with this [link](https://stackoverflow.com/questions/47414098/cache-and-zip-static-resources-with-spring-boot-2) – Vmxes Dec 21 '17 at 17:19