====== Mapping URL to Local File System ======
===== For File System =====
It is possible for us to map a URL to the sever local file system. Here is how we do it:
- Write a WebConfiguration class with @Configuration annotation that implements WebMvcConfigurer.
- @Override that method ''public void addResourceHandlers(ResourceHandlerRegistry registry) {...}''
- 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 URL "http://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.
===== For Relative Path Inside the War/Jar File =====
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.
- Create a directory under "src/main/resources". ''demo'' for example.
- 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...