Showing posts with label Serve static resources from different locations using spring. Show all posts
Showing posts with label Serve static resources from different locations using spring. Show all posts

Spring Boot + Spring Security + Serve static resources from different locations

In Spring we can configure static resources such as  images, js, and, css files from specific locations under web application root, the classpath, and other locations. Even we can configure multiple locations to server different type of file.
An implementation of WebMvcConfigurer interface in WebMvcConfigurerAdapter abstract class with empty methods allowing sub-classes to override only the methods they're interested in. To achieve and serve static resources from different locations we need to extend WebMvcConfigurerAdapter class and need to @Override addResourceHandlers() method in our Application class.
Lets simple example to serve static resources like images and text files from different locations.
Here in this example we are loading images and text files from different locations like

  • images from C://images 
  • text files from C://txtfiles

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.app</groupId>
 <artifactId>staticresourceloader</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <name>staticresourceloader</name>
 <description>staticresourceloader project</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.2.5.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

  <dependencies>
  
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-ws</artifactId>
  </dependency>
  
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>
 
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>


application.properties

security.user.password=Efhj34tGVW

staticresourceloader.imageFileLocation.path:file:C:\\images\\

staticresourceloader.txtFileLocation.path:file:C:\\txtfiles\\


Application.java

package com.app.staticresourceloader;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter  {

 @Value("${staticresourceloader.imageFileLocation.path}")
    private String staticImageFilePath;
 
 @Value("${staticresourceloader.txtFileLocation.path}")
    private String staticTxtFilePath;
 
 public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    
 @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/api/image/**").addResourceLocations(staticImageFilePath);
        registry.addResourceHandler("/api/txt/**").addResourceLocations(staticTxtFilePath);
    }    
}


ServletInitializer.java

package com.app.staticresourceloader;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

 @Override
 protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  return application.sources(Application.class);
 } 
}


MyController.java

package com.app.staticresourceloader;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class MyController {

 @Value("${staticresourceloader.imageFileLocation.path}")
    private String staticImageFilePath;
 
 @Value("${staticresourceloader.txtFileLocation.path}")
    private String staticTxtFilePath;
 
 
 @RequestMapping(value="/api/getImageList", method=RequestMethod.GET, headers="Accept=application/json")
 public ResponseEntity<Collection<String>> getImageList(){
  
  Collection<String> fileList = fileList(staticImageFilePath, "image");
  
  return new ResponseEntity<Collection<String>>(fileList, HttpStatus.OK);
 } 
 
 


        @RequestMapping(value="/api/getTxtList", method=RequestMethod.GET, headers="Accept=application/json")
 public ResponseEntity<Collection<String>> getTxtFileList(){
  
  Collection<String> fileList = fileList(staticTxtFilePath, "txt");
  
  return new ResponseEntity<Collection<String>>(fileList, HttpStatus.OK);
 } 
 
 


        public Collection<String> fileList(String folderPath, String type) {
  
  File directory = new File(folderPath.replace("file:", ""));
  File[] fList = directory.listFiles();
  
  Collection<String> list = new ArrayList<String>();
  
  for (File file : fList) {
   
   list.add("http://localhost:8080/api/"+type+"/"+file.getName());
  }  
  return list;
 } 
}


Spring Boot + Spring Security + Serve static resources from different locations



OUTPUT:

Spring Boot + Spring Security + Serve static resources from different locations

Spring Boot + Spring Security + Serve static resources from different locations

Spring Boot + Spring Security + Serve static resources from different locations

Spring Boot + Spring Security + Serve static resources from different locations

Spring Boot + Spring Security + Serve static resources from different locations