Home > Software engineering >  The spring boot project cannot access static files
The spring boot project cannot access static files

Time:12-25

I created a new springboot project, the directory structure of the project is as follows: enter image description here The yml configuration is as follows:

server:
  port: 8783
  servlet:
    context-path: /spring-demo

spring:
  scan : com.example
  application:
    name: spring-demo
  mvc:
    view:
      suffix: .html
      prefix: /
  web:
    resources:
      static-path-pattern: /**
      static-locations: classpath:/templates/,classpath:/static/
  thymeleaf:
    cache: false
    suffix: .html

IndexController is as follows

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    @RequestMapping("/index")
    public String index(){
        System.out.println("index");
        return "/index";
    }
}

index.html

<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="icon" href="/static/favicon.ico">
  <title>private-report</title>
</head>

<body><noscript><strong>We're sorry but private-report doesn't work properly without JavaScript enabled. Please enable
  it to continue.</strong></noscript>
<div id="app"></div>
<link href="/static/js/chunk-vendors.365b8cfb.js" rel="preload" as="script">

</body>

</html>

When I start the spring-demo service and enter http://localhost:8783/spring-demo/index in the browser, the page reports an error enter image description here

The index interface can be accessed, but the js file cannot be accessed and a 404 error is reported.

I tried many ways but couldn't access the js file, and the spring boot version is 2.5.5.

CodePudding user response:

I have found your error. You use the root context path spring-demo which is not applied to the relative path as needed

You must change it into

   <link href="/spring-demo/static/js/chunk-vendors.365b8cfb.js" rel="preload" as="script">
  • Related