springboot:mapping_url_to_local_file_system

Mapping URL to Local File System

It is possible for us to map a URL to the sever local file system. Here is how we do it:

  1. Write a WebConfiguration class with @Configuration annotation that implements WebMvcConfigurer.
  2. @Override that method public void addResourceHandlers(ResourceHandlerRegistry registry) {…}
  3. The method looks like:
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/demo/**").addResourceLocations("file:///d:/demo/");
        }

Note that it would map any files, and sub-directories to the URLhttp://PATH_TO_YOUR_SERVER:PORT/demo/…” to the directory d:\demo in your windows system. we can do file:/opt/YOUR_DIRECTORY for your Unix/Linux system.

Assume we put a file called 1.jpg under the path src/main/resources/static, we can access it with URL http://PATH_TO_YOUR_SERVER:PORT/1.jpg. This directory is the best for putting css, javascript. However, if we want to mapping a directory under src/main/resources, there is no way to access it unless we do a static path mapping ourselves.

  1. Create a directory under “src/main/resources”. demo for example.
  2. Do something like the previous section, but do:
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/demo/**").addResourceLocations("classpath:/demo/");
        }

classpath:/ is the root directory of src/main/resources/. Note that it will work for all sub-directories…

  • springboot/mapping_url_to_local_file_system.txt
  • Last modified: 2020/06/01 15:32
  • by chongtin