Spring Boot not serving static content

2019-01-03 01:08发布

I'm banging my head against the wall for a couple of hours now. My project is almost finished, but I can't get it to serve static content.

I've placed a folder named static under src/main/resources. Inside it I have a folder named images. When I package the app and run it, it can't find the images I have put on that folder.

I've tried to put the static files in public, resources and META-INF/resources but nothing works.

If I jar -tvf app.jar I can see that the files are inside the jar on the right folder: /static/images/head.png for example, but calling: http://localhost:8080/images/head.png, all I get is a 404

Any ideas why spring-boot is not finding this? (I'm using 1.1.4 BTW)

18条回答
2楼-- · 2019-01-03 01:43

The configuration could be made as follows:

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcAutoConfigurationAdapter {

// specific project configuration

}

Important here is that your WebMvcConfig may override addResourceHandlers method and therefore you need to explicitly invoke super.addResourceHandlers(registry) (it is true that if you are satisfied with the default resource locations you don't need to override any method).

Another thing that needs to be commented here is that those default resource locations (/static, /public, /resources and /META-INF/resources) will be registered only if there isn't already a resource handler mapped to /**.

From this moment on, if you have an image on src/main/resources/static/images named image.jpg for instance, you can access it using the following URL: http://localhost:8080/images/image.jpg (being the server started on port 8080 and application deployed to root context).

查看更多
三岁会撩人
3楼-- · 2019-01-03 01:43

I was having this exact problem, then realized that I had defined in my application.properties:

spring.resources.static-locations=file:/var/www/static

Which was overriding everything else I had tried. In my case, I wanted to keep both, so I just kept the property and added:

spring.resources.static-locations=file:/var/www/static,classpath:static

Which served files from src/main/resources/static as localhost:{port}/file.html.

None of the above worked for me because nobody mentioned this little property that could have easily been copied from online to serve a different purpose ;)

Hope it helps! Figured it would fit well in this long post of answers for people with this problem.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-03 01:44

This solution works for me:

First, put a resources folder under webapp/WEB-INF, as follow structure

-- src
  -- main
    -- webapp
      -- WEB-INF
        -- resources
          -- css
          -- image
          -- js
          -- ...

Second, in spring config file

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter{

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resource/**").addResourceLocations("WEB-INF/resources/");
    }
}

Then, you can access your resource content, such as http://localhost:8080/resource/image/yourimage.jpg

查看更多
时光不老,我们不散
5楼-- · 2019-01-03 01:44

Well sometimes is worth to check did you override the global mappings by some rest controller. Simple example mistake (kotlin):

@RestController("/foo")
class TrainingController {

    @PostMapping
    fun bazz(@RequestBody newBody: CommandDto): CommandDto = return commandDto

}

In the above case you will get when you request for static resources:

{
    title: "Method Not Allowed",
    status: 405,
    detail: "Request method 'GET' not supported",
    path: "/index.html"
}

The reason for it could be that you wanted to map @PostMapping to /foo but forget about @RequestMapping annotation on the @RestController level. In this case all request are mapped to POST and you won't receive static content in this case.

查看更多
We Are One
6楼-- · 2019-01-03 01:45

Look for Controllers mapped to "/" or with no path mapped.

I had a problem like this, getting 405 errors, and banged my head hard for days. The problem turned out to be a @RestController annotated controller that I had forgot to annotate with a @RequestMapping annotation. I guess this mapped path defaulted to "/" and blocked the static content resource mapping.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-03 01:46

I am in same situation where my spring-boot angular app(integration) is not serving static folder contents to show UI on localhost:8080. Frontend is developed in angular4 so used ng build that generated files in output path dir src/main/resources/static but do not show any contents. I made a controller specifically to serve index.html but seems like something is off for spring-boot to understand angular routing stuff and localhost:8080 just displays the returned string from my controller method "index.html" on webpage. Below is index.html (I changed default selector tag in body to as login component is the one I created and my main angular component for UI but still doesn't work whether app-root or this one):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hello Test App</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-login></app-login>
<script type="text/javascript" src="runtime.js"></script><script type="text/javascript" src="polyfills.js"></script><script type="text/javascript" src="styles.js"></script><script type="text/javascript" src="vendor.js"></script><script type="text/javascript" src="main.js"></script></body>
</html>

Controller code:

@RequestMapping("/")
public String userInterface() {
    return "index.html";
}

Not sure if it matters but this is gradle based project developed in IntellijIdea and spring boot version is -org.springframework.boot:spring-boot-starter-web:2.0.2.RELEASE .

@Vizcaino - As you said there is a simple trick- does Intellijidea provides a similar option to create source directory/folder as well? I did create from right click menu -> New -> directory. But not sure if its the same thing, wondering if it would be cause of my issue?

查看更多
登录 后发表回答