代码之家  ›  专栏  ›  技术社区  ›  Joris Schellekens

无法使用spring服务静态资源,请改为接收索引

  •  0
  • Joris Schellekens  · 技术社区  · 8 年前

    我有一个简单的spring web应用程序。

    @Controller
    public class GreetingController {
    
        @Autowired
        GreetingRepository repository;
    
        @GetMapping("/greeting")
        public String greetingForm(Model model) {
            model.addAttribute("greeting", new Greeting());
            return "greeting";
        }
    
        @PostMapping("/greeting")
        public String greetingSubmit(@ModelAttribute Greeting greeting) {
            repository.save(greeting);
            return "result";
        }
    
    }
    

    HTML是:

    <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org">
    <head> 
        <title>Greeting Sample</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" th:href="@{/css/style.css}"/>
    </head>
    <body>
        <h1>Form</h1>
        <form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
            <p>Id: <input type="text" th:field="*{id}" /></p>
            <p>Message: <input type="text" th:field="*{content}" /></p>
            <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
        </form>
    </body>
    </html>
    

    这是HTML中引用的CSS文件:

    p {
        color: #ff5588;
    }
    

    但是,不应用css。

    实际上,当我查询localhost:8080/css/style.css时,它返回索引页的html内容。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Arif Ulusoy    8 年前

    可能是安全配置问题。您的项目中是否有安全实现(springsecurity或custom)?如果是,您的用户是否可以访问 /css/* URL或此URL具有公共访问权限?如果用户无权访问URL或在处理请求时出现异常,则可能会发生重定向。

        2
  •  0
  •   Joris Schellekens    8 年前

    安全配置结果阻止了对资源的所有请求。相反,它将这些请求重定向到索引页(已配置)。

    解决方案很简单,授权所有对网站资源的请求( /images/** 和 /css/** 和 /js/** )

    配置好之后,web应用程序就可以按预期工作了。