Spring: How to access contents of webapp/resources in service layer

spring boot static resources
spring resources/static-locations
spring mvc:resources mapping java config
spring security static resources
spring boot webapp folder
spring boot thymeleaf static resources
spring boot static html example
addresourcehandlers

How do I access the contents of my webapp/resources folder from the service layer? I need to access a JSON file to be used for Elasticsearch mappings...

This is how my project structure looks like: https://www.dropbox.com/s/crdzae1ko0x9p89/Screenshot%202015-05-25%2010.24.12.png?dl=0

I tried this: http://www.mkyong.com/java/java-read-a-file-from-resources-folder/

String mapping = String.format("es_mappings/%s.json", type);
        ClassLoader classLoader = getClass().getClassLoader();
        String result = IOUtils.toString(classLoader.getResourceAsStream(mapping));

But I got a null pointer exception for the third line in the code snippet above.

Also tried this:

File file = ResourceUtils.getFile("classpath:es_mappings/bom_exports.json")
String txt= FileUtils.readFileToString(file);

But I got this error: java.io.FileNotFoundException: class path resource [es_mappings/bom_exports.json] cannot be resolved to absolute file path because it does not reside in the file system.

I have this in my -servlet.xml file:

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

Thanks.

Using relative paths depends on the classloader, so you need to either work out where your classloader is looking or else just use an absolute path - when using getResourceAsStream you need to start with a leading / so try this:

String mapping = String.format("/es_mappings/%s.json", type);
    ClassLoader classLoader = getClass().getClassLoader();
    String result = IOUtils.toString(classLoader.getResourceAsStream(mapping));

Also I'm not sure the webapp/resources folder will be added to the classpath by default in maven. Usually resources like files you need to access at runtime would be in the src/main/resources directory. (but I could be wrong, the easy way to tell is check the packaged war file, if the files are in /WEB-INF/classes then they are on the classpath)

Serve Static Resources with Spring, How to map and handle static resources with Spring MVC - use the simple Here, we're serving static contents from the /files and /static-files an html page would get us the myCss.css resource inside the webapp/resources directory: and of course your /rest/* is mapped to your Controller layer – Spring  Spring 4.1. provides – with the new ResourcesResolvers – different types of resource resolvers that can be used to optimize browser performance when loading static resources. These resolvers can be chained and cached in the browser to optimize request handling.

I using this code. It's simple and works.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;

// ...

@Value("/resources/json/your_file.json")
private Resource jsonResource;

// ...

InputStream jsonStream = jsonResource.getInputStream();

Now you can use stream to read json.

Tutorial, REST has quickly become the de-facto standard for building web services on the web because they're easy to build This will be wrapped with a Spring MVC layer to access remotely. Creates a new Employee record, and then sends the content back to us: RESTful representation of a collection of employee resources. 2. Using Resource. The Resource interface helps in abstracting access to low-level resources. In fact, it supports handling of all kinds of file resources in a uniform manner. Let's start by looking at various methods to obtain a Resource instance.

ResourceUtils.getFile("classpath:es_mappings/bom_exports.json")

This method get resources file from the webapp/WEB-INF/classes when you pass classpath:*. If you want get the json file from webapp/resources/es_mappings/your_file.json, the service class can implement the interface ServletContextAware and get servletContext. Because the webapp directory is determined by the web container such as tomcat or jetty, it only get the relative path from servletContext.getResource(). That method can get resources under webapp. Code example maybe like:

class your_service implements ServletContextAware {

     private ServletContext servletContext;

     public void setServletContext(ServletContext servletContext) {
           this.servletContext = servletContext;
     }

     public void getJsonResource() {
        ...//other code
        String josnFilepath = servletContext.getResource(
                     "/resources/es_mappings/your_file.json");
     }
}

Also you can get the webapp directory by finding "WEB-INF/classes" substring in classpath.

String path =  this.getClass().getResource("").getPath();
String fullPath = URLDecoder.decode(path, "utf-8");
String pathArr[] = fullPath.split("/WEB-INF/classes/");
if (2 == pathArr.length) { //pathArr[0] is webapp directory path
    String jsonFilepath = pathArr[0] + "/resources/es_mappings/your_file.json";
}

Getting Started, Like most Spring Getting Started guides, you can start from scratch and The following listing (from src/main/resources/templates/greeting.html ) shows the to look for other components, configurations, and services in the com/example package, This web application is 100% pure Java and you did not have to deal with  DAO stands for data access object. Usually, the DAO class is responsible for two concepts. Encapsulating the details of the persistence layer and provide a CRUD interface for a single entity. You can find a detailed description in this tutorial.

Reading application.properties in Spring Boot, To demonstrate how to read application properties in Spring Boot application I have created a very simple Spring Boot Web App. You can application.​properties file in src/main/resources folder of your Spring Boot project to inject the Environment object into your Rest Controller or Service class, like so:. The following example shows how to write a simple web-based application using Spring MVC Framework, which can access static pages along with dynamic pages with the help of <mvc:resources> tag. To start with, let us have a working Eclipse IDE in place and take the following steps to develope a Dynamic Form based Web Application using Spring Web Framework −

Spring MVC Hello World Example, In this example, we will build a hello world web application using the Spring MVC Table Of Contents What is MVC Framework? I do not consider service and DAO layers classes the part of MVC framework. Usually hey i am start to use spring mvc 5.0.9 and use java based configuration , when try to access my jsp page You built and scaled out a Java Web app using Spring Framework, JSP, Spring Data, Hibernate, JDBC, App Service Linux and Azure Database for MySQL. Clean up resources In the preceding sections, you created Azure resources in a resource group.

Spring MVC Tutorial: Web Application Guide With Examples, Multi-part Spring MVC tutorial about how to build a web application utilizing the request forms in order to get approval for any company expenses/purchases. a basic Spring MVC project, create a Spring Controller, Service Layer spring component can be injected by using @Resource which will by default look for a  Two Java examples of reading a file from resources folder in either simple Java application or any spring mvc / spring boot application. Below image describes the folder structure used in this example. Notice the file sample.txt in resources folder. We can read a file from the application’s resources package by using ClassLoader reference of

Comments
  • I added a leading / and moved my folder to src/main/resources and it works now. Thanks!
  • After spending good 4 hours, the above solution worked just fine. So @Value with no prefix (classpath/file) in the value reads from the root of war file. Also just to confirm what the original post asked for; anything under webapp directory of a maven project by default goes to the root of the war.