spring-hateoas: ControllerLinkBuilder does not take Spring Data REST's base path into account

I have the repository REST base path set to /rest, and a @RepositoryRestController with some custom handlers:

@RepositoryRestController
public class RestController {
    @RequestMapping(value = "/foo", method = RequestMethod.GET)
    public ResponseEntity<Bar> foo() {
        return new ResponseEntity<>(new Bar(), HttpStatus.OK);
    }
    ...
}
public class Bar extends ResourceSupport {
    public Bar() {
        ...
        add(linkTo(methodOn(RestController.class).foo()).withSelfRel());
    }
}

The endpoint works fine at http://localhost:8080/rest/foo, however, the link is incorrect:

{
  ...
  _links: {
    self: {
      href: "http://localhost:8080/foo"
    }
  }
}

For some reason, the base path (/rest) was ignored.

I’m using Spring HATEOAS 0.19.0.RELEASE (comes with Spring Boot 1.3.1.RELEASE).

About this issue

  • Original URL
  • State: open
  • Created 11 years ago
  • Reactions: 11
  • Comments: 29 (8 by maintainers)

Commits related to this issue

Most upvoted comments

I have the same problem and implemented the following service that prepends the base path as a workaround:

@Service
public class BasePathAwareLinks {
	
  private final URI contextBaseURI;
  private final URI restBaseURI;
	
  @Autowired
  public BasePathAwareLinks(ServletContext servletContext, RepositoryRestConfiguration config) {
    contextBaseURI = URI.create(servletContext.getContextPath());
    restBaseURI = config.getBasePath();
  }

  public LinkBuilder underBasePath(ControllerLinkBuilder linkBuilder) {
    return BaseUriLinkBuilder.create(contextBaseURI)
      .slash(restBaseURI)
      .slash(contextBaseURI.relativize(URI.create(linkBuilder.toUri().getPath())));
  }
}

To use it, just pass the LinkBuilder returned from linkTo to underBasePath before actually building the link:

public class MyResourceProcessor<Person> implements ResourceProcessor<Person> {
	
  @Autowired
  private BasePathAwareLinks service;
	
  public Resource<Person> process(Resource<Person> resource) {
    resource.add(
      service.underBasePath(
        linkTo(methodOn(SpecialPersonController.class).doSomething())
      )
      .withRel("something")
    );
    return resource;
  }
}

Hope this helps.

I just came across this issue as well. Did you find a workaround?

I assume we will need a RestControllerLinkBuilder class in the data-rest package…

I anybody needs a solution for this, here is mine: a LinkBuilder implementation based on WebMvcLinkBuilder that handles the base-path and the BasePathAwareController Annotation.

A few details:

  • If the BasePathAwareController annotation contains more than one path, there will be an exception
  • the api is a carbon-copy of WebMvcLinkBuilder; just put the variable in front of any linkTo(...) you already have
  • no use of toUri(...) or toUriString(...) because these break links that contain parameter-placeholders
import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation;

/**
 * Wrapper for {@link org.springframework.hateoas.server.mvc.WebMvcLinkBuilder} that adds data-rests base-path
 */
public class BasePathAwareLinks {

    private String baseUri;

    public BasePathAwareLinks(RepositoryRestConfiguration repositoryRestConfiguration) {
        this.baseUri = repositoryRestConfiguration.getBasePath().toString();
    }

    public BasePathAwareLinkBuilder linkTo(Class<?> controller) {
        return new BasePathAwareLinkBuilder(controller, WebMvcLinkBuilder.linkTo(controller));
    }

    /**
     * Creates a new {@link BasePathAwareLinkBuilder} with a base of the mapping annotated to the given controller class. The
     * additional parameters are used to fill up potentially available path variables in the class scop request mapping.
     *
     * @param controller the class to discover the annotation on, must not be {@literal null}.
     * @param parameters additional parameters to bind to the URI template declared in the annotation, must not be
     *                   {@literal null}.
     * @return
     */
    public BasePathAwareLinkBuilder linkTo(Class<?> controller, Object... parameters) {
        return new BasePathAwareLinkBuilder(controller, WebMvcLinkBuilder.linkTo(controller, parameters));
    }

    /**
     * Creates a new {@link BasePathAwareLinkBuilder} with a base of the mapping annotated to the given controller class.
     * Parameter map is used to fill up potentially available path variables in the class scope request mapping.
     *
     * @param controller the class to discover the annotation on, must not be {@literal null}.
     * @param parameters additional parameters to bind to the URI template declared in the annotation, must not be
     *                   {@literal null}.
     * @return
     */
    public BasePathAwareLinkBuilder linkTo(Class<?> controller, Map<String, ?> parameters) {
        return new BasePathAwareLinkBuilder(controller, WebMvcLinkBuilder.linkTo(controller, parameters));
    }

    /*
     * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Method)
     */
    public BasePathAwareLinkBuilder linkTo(Method method) {
        return linkTo(method.getDeclaringClass(), method, new Object[method.getParameterTypes().length]);
    }

    /*
     * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Method, Object...)
     */
    public BasePathAwareLinkBuilder linkTo(Method method, Object... parameters) {
        return linkTo(method.getDeclaringClass(), method, parameters);
    }

    /*
     * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Class<?>, Method)
     */
    public BasePathAwareLinkBuilder linkTo(Class<?> controller, Method method) {
        return linkTo(controller, method, new Object[method.getParameterTypes().length]);
    }

    /*
     * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(Class<?>, Method, Object...)
     */
    public BasePathAwareLinkBuilder linkTo(Class<?> controller, Method method, Object... parameters) {
        return new BasePathAwareLinkBuilder(controller, WebMvcLinkBuilder.linkTo(controller, method, parameters));

    }

    /**
     * Creates a {@link BasePathAwareLinkBuilder} pointing to a controller method. Hand in a dummy method invocation result you
     * can create via {@link #methodOn(Class, Object...)} or {@link DummyInvocationUtils#methodOn(Class, Object...)}.
     *
     * <pre>
     * &#64;BasePathAwareController("/customers")
     * class CustomerController {
     *
     *   &#64;RequestMapping("/{id}/addresses")
     *   HttpEntity&lt;Addresses&gt; showAddresses(@PathVariable Long id) { … }
     * }
     *
     * Link link = basePathAwareLinks.linkTo(methodOn(CustomerController.class).showAddresses(2L)).withRel("addresses");
     * </pre>
     * <p>
     * The resulting {@link Link} instance will point to {@code <base-path>/customers/2/addresses} and have a rel of
     * {@code addresses}. For more details on the method invocation constraints, see
     * {@link DummyInvocationUtils#methodOn(Class, Object...)}.
     *
     * @param invocationValue
     * @return
     */
    public BasePathAwareLinkBuilder linkTo(Object invocationValue) {
        Assert.isInstanceOf(LastInvocationAware.class, invocationValue);

        LastInvocationAware invocations = DummyInvocationUtils
            .getLastInvocationAware(invocationValue);

        return new BasePathAwareLinkBuilder(invocations.getLastInvocation().getTargetType(), WebMvcLinkBuilder.linkTo(invocationValue));
    }

    /**
     * Extract a {@link Link} from the {@link BasePathAwareLinkBuilder} and look up the related {@link Affordance}. Should only
     * be one.
     *
     * <pre>
     * Link findOneLink = basePathAwareLinks.linkTo(methodOn(EmployeeController.class).findOne(id)).withSelfRel()
     * 		.andAffordance(afford(methodOn(EmployeeController.class).updateEmployee(null, id)));
     * </pre>
     * <p>
     * This takes a link and adds an {@link Affordance} based on another Spring MVC handler method.
     *
     * @param invocationValue
     * @return
     */
    public Affordance afford(Object invocationValue) {
        BasePathAwareLinkBuilder linkBuilder = linkTo(invocationValue);

        Assert.isTrue(linkBuilder.getAffordances().size() == 1, "A base can only have one affordance, itself");

        return linkBuilder.getAffordances().get(0);
    }

    /**
     * Wrapper for {@link DummyInvocationUtils#methodOn(Class, Object...)} to be available in case you work with static
     * imports of {@link BasePathAwareLinks}.
     *
     * @param controller must not be {@literal null}.
     * @param parameters parameters to extend template variables in the type level mapping.
     * @return
     */
    public static <T> T methodOn(Class<T> controller, Object... parameters) {
        return DummyInvocationUtils.methodOn(controller, parameters);
    }

    protected UriComponents uriWithBasePath(Class<?> controller, WebMvcLinkBuilder linkBuilder) {
        var uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(linkBuilder.toString());

        var basePath = getBasePathedPrefix(controller);
        var linkPath = uriComponentsBuilder.build().getPath();

        return uriComponentsBuilder.replacePath(basePath + linkPath).build();
    }

    protected String getBasePathedPrefix(Class<?> handlerType) {

        Assert.notNull(handlerType, "Handler type must not be null");

        BasePathAwareController mergedAnnotation = findMergedAnnotation(handlerType, BasePathAwareController.class);
        String[] customPrefixes = mergedAnnotation == null ? new String[0] : mergedAnnotation.value();

        String[] basePathPrefixes = customPrefixes.length == 0 //
            ? new String[]{baseUri} //
            : Arrays.stream(customPrefixes).map(baseUri::concat).toArray(String[]::new);

        Assert.isTrue(basePathPrefixes.length == 1, "Cant build links to controller with more than one path");

        return basePathPrefixes[0];
    }

    public class BasePathAwareLinkBuilder extends TemplateVariableAwareLinkBuilderSupport<BasePathAwareLinkBuilder> {

        BasePathAwareLinkBuilder(Class<?> controller, WebMvcLinkBuilder webMvcLinkBuilder) {
            super(uriWithBasePath(controller, webMvcLinkBuilder), TemplateVariables.NONE, Collections.emptyList());
        }

        BasePathAwareLinkBuilder(UriComponents uriComponents, TemplateVariables variables, List<Affordance> affordances) {
            super(uriComponents, variables, affordances);
        }

        /*
         * (non-Javadoc)
         * @see org.springframework.hateoas.UriComponentsLinkBuilder#getThis()
         */
        @Override
        protected BasePathAwareLinkBuilder getThis() {
            return this;
        }

        /*
         * (non-Javadoc)
         * @see org.springframework.hateoas.server.core.TemplateVariableAwareLinkBuilderSupport#createNewInstance(org.springframework.web.util.UriComponents, java.util.List, org.springframework.hateoas.TemplateVariables)
         */
        @Override
        protected BasePathAwareLinkBuilder createNewInstance(UriComponents components, List<Affordance> affordances,
                                                             TemplateVariables variables) {
            return new BasePathAwareLinkBuilder(components, variables, affordances);
        }
    }
}

Hey, I was fighting with this issue myself and found out that you can add base path of SDR to @RequestMapping annotation explicitly and here is what happens: you get proper link using static ControllerLinkBuilder AND your method gets registered properly as you want it - the prefix with base path will be ignored somehow.

Although I’m not sure how it is happening, this is what I’m using and it works fine for me.

@drenda happy to help! 😺

For me the first part was not important, but in general we probably should consider it as well. I guess you could extract it from linkBuilder.toUri(), maybe something like the following (didn’t test) could work:

  public LinkBuilder underBasePath(ControllerLinkBuilder linkBuilder) {
    URI uri = linkBuilder.toUri();
    URI origin = new URI(uri.getScheme(), uri.getAuthority(), null, null, null);
    URI suffix = new URI(null, null, uri.getPath(), uri.getQuery(), uri.getFragment());
    return BaseUriLinkBuilder.create(origin)
      .slash(contextBaseURI)
      .slash(restBaseURI)
      .slash(suffix);
  }

We basically take the link from the ControllerLinkBuilder and just prepend the context base URI and the rest base URI to its path, while leaving everything else intact. So maybe now it also works for templated links.

Have exactly the same problem.