【问题标题】:How can I serve static content and spring data rest at / using content negotiation?如何在/使用内容协商时提供静态内容和弹簧数据?
【发布时间】:2016-08-16 04:01:41
【问题描述】:

我想同时托管静态内容,并且 Spring 数据基于 /

curl http://localhost:8080                                                                                                                                       slave-vi
<!DOCTYPE html><html><head><title>RPF</title><meta name="viewport" content="width=device-width,initial-scale=1"><base href="/"><link href="styles.css" rel="stylesheet"></head><body aurelia-app="main"><div class="splash"><div class="message">RPF</div><i class="fa fa-spinner fa-spin"></i></div><script type="text/javascript" src="aurelia-bootstrap.3c6271fc099630981613.bundle.js"></script><script type="text/javascript" src="aurelia.042f8d07b45053bfe6a6.bundle.js"></script><script type="text/javascript" src="app.86af2df503886ba0a486.bundle.js"></script></body></html>

唯一的区别应该基于内容协商

curl -H "Accept: application/json" http://localhost:8080                                                                                                    slave-vi
{
  "_links" : {
    "users" : {
      "href" : "http://localhost:8080/users{?page,size,sort}",
      "templated" : true
    },
    "profile" : {
      "href" : "http://localhost:8080/profile"
    }
  }
}

因此,如果浏览器 Accept 标头(它们是非特定的)或未发送接受标头,我会收到 index.html 但如果发送 application/json 或其他特定内容标头,我会收到该类型或 415,具体取决于支持程度。

目前我通过在命令行中添加这个来设置静态位置-Dspring.resources.staticLocations=...

【问题讨论】:

    标签: java spring spring-mvc spring-boot spring-data-rest


    【解决方案1】:

    您可以让控制器监听/ 上的所有请求并根据某些条件转发它们:

    @RequestMapping("/")
    public String handleIndexPage(@RequestHeader(value="Accept") String acceptValue) {
        if (MediaType.APPLICATION_JSON_VALUE.equals(acceptValue)) {
            return "forward:/spring-data-rest-url";
        } else {
            return "forward:/other-url";
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 2018-12-25
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    相关资源
    最近更新 更多