spring-projects / spring-hateoas-examples

Collection of examples on how (and why) to build hypermedia-driven apps with Spring HATEOAS
Apache License 2.0
384 stars 186 forks source link

Demoonstrate that changing the servlet context path via Spring Boot works. #31

Open gregturn opened 4 years ago

gregturn commented 4 years ago

When applying server.servlet.context-path=/ctx, the links automatically adjust.

2020-04-13 10:43:59.877  INFO 79416 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path '/ctx'

Testing with curl...

$ curl localhost:8080/ctx/employees | jq
{
  "_embedded": {
    "employees": [
      {
        "id": 1,
        "firstName": "Frodo",
        "lastName": "Baggins",
        "role": "ring bearer",
        "fullName": "Frodo Baggins",
        "_links": {
          "self": {
            "href": "http://localhost:8080/ctx/employees/1"
          },
          "employees": {
            "href": "http://localhost:8080/ctx/employees"
          }
        }
      },
      {
        "id": 2,
        "firstName": "Bilbo",
        "lastName": "Baggins",
        "role": "burglar",
        "fullName": "Bilbo Baggins",
        "_links": {
          "self": {
            "href": "http://localhost:8080/ctx/employees/2"
          },
          "employees": {
            "href": "http://localhost:8080/ctx/employees"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/ctx/employees"
    }
  }
}
avivmu commented 4 years ago

If the issue is closed due to no feedback from issuer / others, should we close / merge this one?

gcwilliams commented 3 years ago

Hi,

I've notice that this does not work correctly if you are using DeferredResult<T> and generating the HATEOAS link on another thread. It looks like it uses ThreadLocals requestAttributesHolder and inheritableRequestAttributesHolder in

org.springframework.web.context.request.RequestContextHolder#getRequestAttributes

called from

org.springframework.web.servlet.support.ServletUriComponentsBuilder#getCurrentRequest

If those ThreadLocals are not set, it drops the context path in the link that's generated.

I found this issue from https://github.com/spring-projects/spring-hateoas/issues/1268 which has been closed now.