13

我希望我的回复包括以下内容:

"keyMaps":{
  "href":"http://localhost/api/keyMaps{/keyMapId}",
  "templated":true
 }

这很容易实现:

add(new Link("http://localhost/api/keyMaps{/keyMapId}", "keyMaps"));

但是,当然,我宁愿使用 ControllerLinkBuilder,如下所示:

add(linkTo(methodOn(KeyMapController.class).getKeyMap("{keyMapId}")).withRel("keyMaps"));

问题是,当变量“{keyMapId}”到达 UriTemplate 构造函数时,它已包含在编码 URL 中:

http://localhost/api/keyMaps/%7BkeyMapId%7D

因此 UriTemplate 的构造函数不会将其识别为包含变量。

如何说服 ControllerLinkBuilder 我想使用模板变量?

4

7 回答 7

8

在我看来,Spring-HATEOAS 的当前状态不允许通过ControllerLinkBuilder(我非常希望被证明是错误的),所以我自己使用以下类来模板化查询参数来实现这一点:

public class TemplatedLinkBuilder {

    private static final TemplatedLinkBuilderFactory FACTORY = new TemplatedLinkBuilderFactory();
    public static final String ENCODED_LEFT_BRACE = "%7B";
    public static final String ENCODED_RIGHT_BRACE = "%7D";

    private UriComponentsBuilder uriComponentsBuilder;

    TemplatedLinkBuilder(UriComponentsBuilder builder) {
        uriComponentsBuilder = builder;
    }

    public static TemplatedLinkBuilder linkTo(Object invocationValue) {
        return FACTORY.linkTo(invocationValue);
    }

    public static <T> T methodOn(Class<T> controller, Object... parameters) {
        return DummyInvocationUtils.methodOn(controller, parameters);
    }

    public Link withRel(String rel) {
        return new Link(replaceTemplateMarkers(uriComponentsBuilder.build().toString()), rel);
    }

    public Link withSelfRel() {
        return withRel(Link.REL_SELF);
    }

    private String replaceTemplateMarkers(String encodedUri) {
        return encodedUri.replaceAll(ENCODED_LEFT_BRACE, "{").replaceAll(ENCODED_RIGHT_BRACE, "}");
    }

}

public class TemplatedLinkBuilderFactory {

    private final ControllerLinkBuilderFactory controllerLinkBuilderFactory;

    public TemplatedLinkBuilderFactory() {
        this.controllerLinkBuilderFactory = new ControllerLinkBuilderFactory();
    }

    public TemplatedLinkBuilder linkTo(Object invocationValue) {
        ControllerLinkBuilder controllerLinkBuilder = controllerLinkBuilderFactory.linkTo(invocationValue);
        UriComponentsBuilder uriComponentsBuilder = controllerLinkBuilder.toUriComponentsBuilder();

        Assert.isInstanceOf(DummyInvocationUtils.LastInvocationAware.class, invocationValue);
        DummyInvocationUtils.LastInvocationAware invocations = (DummyInvocationUtils.LastInvocationAware) invocationValue;
        DummyInvocationUtils.MethodInvocation invocation = invocations.getLastInvocation();
        Object[] arguments = invocation.getArguments();
        MethodParameters parameters = new MethodParameters(invocation.getMethod());

        for (MethodParameter requestParameter : parameters.getParametersWith(RequestParam.class)) {
            Object value = arguments[requestParameter.getParameterIndex()];
            if (value == null) {
                uriComponentsBuilder.queryParam(requestParameter.getParameterName(), "{" + requestParameter.getParameterName() + "}");
            }
        }
        return new TemplatedLinkBuilder(uriComponentsBuilder);
    }
}

它嵌入了普通的 ControllerLinkBuilder ,然后使用类似的逻辑来解析为@RequestParam空的带注释的参数并将它们添加到查询参数中。此外,我们的客户端重新使用这些模板化的 URI 来执行对服务器的进一步请求。为了实现这一点并且不需要担心剥离未使用的模板化参数,我必须执行反向操作({params}与交换null),我正在使用自定义 SpringRequestParamMethodArgumentResolver进行如下操作

public class TemplatedRequestParamResolver extends RequestParamMethodArgumentResolver {

    public TemplatedRequestParamResolver() {
        super(false);
    }

    @Override
    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
        Object value = super.resolveName(name, parameter, webRequest);
        if (value instanceof Object[]) {
            Object[] valueAsCollection = (Object[])value;
            List<Object> resultList = new LinkedList<Object>();
            for (Object collectionEntry : valueAsCollection) {
                if (nullifyTemplatedValue(collectionEntry) != null) {
                    resultList.add(collectionEntry);
                }
            }
            if (resultList.isEmpty()) {
                value = null;
            } else {
                value = resultList.toArray();
            }
        } else{
            value = nullifyTemplatedValue(value);
        }
        return value;
    }

    private Object nullifyTemplatedValue(Object value) {
        if (value != null && value.toString().startsWith("{") && value.toString().endsWith("}")) {
            value = null;
        }
        return value;
    }

}

这也需要替换RequestParamMethodArgumentResolver我所做的现有:

@Configuration
public class ConfigureTemplatedRequestParamResolver {

    private @Autowired RequestMappingHandlerAdapter adapter;

    @PostConstruct
    public void replaceArgumentMethodHandlers() {
        List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<HandlerMethodArgumentResolver>(adapter.getArgumentResolvers());
        for (int cursor = 0; cursor < argumentResolvers.size(); ++cursor) {
            HandlerMethodArgumentResolver handlerMethodArgumentResolver = argumentResolvers.get(cursor);
            if (handlerMethodArgumentResolver instanceof RequestParamMethodArgumentResolver) {
                argumentResolvers.remove(cursor);
                argumentResolvers.add(cursor, new TemplatedRequestParamResolver());
                break;
            }
        }
        adapter.setArgumentResolvers(argumentResolvers);
    }

}

不幸的是,虽然{}模板化URI 中的有效字符,但它们在 URI 中无效,这对您的客户端代码来说可能是个问题,具体取决于它的严格程度。我更喜欢 Spring-HATEOAS 内置的更简洁的解决方案!

于 2014-07-30T16:13:41.340 回答
6

使用最新版本,spring-hateoas您可以执行以下操作:

UriComponents uriComponents = UriComponentsBuilder.fromUri(linkBuilder.toUri()).build();
UriTemplate template = new UriTemplate(uriComponents.toUriString())
   .with("keyMapId", TemplateVariable.SEGMENT);

会给你:http://localhost:8080/bla{/keyMapId}",

于 2016-07-04T11:54:23.287 回答
5

我们遇到了同样的问题。一般的解决方法是我们有自己的 LinkBuilder 类和一堆静态助手。模板化的看起来像这样:

public static Link linkToSubcategoriesTemplated(String categoryId){

    return new Link(
        new UriTemplate(
            linkTo(methodOn(CategoryController.class).subcategories(null, null, categoryId))
                .toUriComponentsBuilder().build().toUriString(),
            // register it as variable
            getBaseTemplateVariables()
        ),
        REL_SUBCATEGORIES
    );
}

private static TemplateVariables getBaseTemplateVariables() {
    return new TemplateVariables(
        new TemplateVariable("page", TemplateVariable.VariableType.REQUEST_PARAM),
        new TemplateVariable("sort", TemplateVariable.VariableType.REQUEST_PARAM),
        new TemplateVariable("size", TemplateVariable.VariableType.REQUEST_PARAM)
    );
}

这是为了公开 PagedResource 的控制器响应的参数。

然后在控制器中,我们根据需要将其称为附加一个 withRel。

于 2014-08-04T20:47:00.050 回答
5

从此提交开始:

https://github.com/spring-projects/spring-hateoas/commit/2daf8aabfb78b6767bf27ac3e473832c872302c7

您现在可以传递null路径变量的预期位置。它对我有用,没有解决方法。

resource.add(linkTo(methodOn(UsersController.class).someMethod(null)).withRel("someMethod"));

结果:

    "someMethod": {
        "href": "http://localhost:8080/api/v1/users/{userId}",
        "templated": true
    },

还要检查相关问题:https ://github.com/spring-projects/spring-hateoas/issues/545

于 2018-01-26T08:20:12.970 回答
4

根据这个问题评论,这将在即将发布的 spring-hateoas 中得到解决。

目前,在 Maven Central 中有一个ControllerLinkBuilder可直接替换的替代品。de.escalon.hypermedia:spring-hateoas-ext

我现在可以这样做:

import static de.escalon.hypermedia.spring.AffordanceBuilder.*

...

add(linkTo(methodOn(KeyMapController.class).getKeyMap(null)).withRel("keyMaps"));

我作为参数值传入null以指示我要使用模板变量。变量的名称会自动从控制器中提取。

于 2016-11-11T22:47:37.557 回答
2

我需要在 Spring Data Rest 应用程序的根目录中包含一个带有模板变量的链接,以通过 traverson 访问 oauth2 令牌。这工作正常,也许有用:

@Component
class RepositoryLinksResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {

    @Override
    RepositoryLinksResource process(RepositoryLinksResource resource) {

        UriTemplate uriTemplate =  new UriTemplate(
                ControllerLinkBuilder.
                        linkTo(
                                TokenEndpoint,
                                TokenEndpoint.getDeclaredMethod("postAccessToken", java.security.Principal, Map )).
                        toUriComponentsBuilder().
                        build().
                        toString(),
                new TemplateVariables([
                        new TemplateVariable("username", TemplateVariable.VariableType.REQUEST_PARAM),
                        new TemplateVariable("password", TemplateVariable.VariableType.REQUEST_PARAM),
                        new TemplateVariable("clientId", TemplateVariable.VariableType.REQUEST_PARAM),
                        new TemplateVariable("clientSecret", TemplateVariable.VariableType.REQUEST_PARAM)
                ])
        )

        resource.add(
                new Link( uriTemplate,
                        "token"
                )
        )

        return resource
    }
}
于 2016-04-16T14:05:54.523 回答
0

根据之前的评论,我已经实现了一个通用的辅助方法(针对 spring-hateoas-0.20.0)作为“临时”解决方法。该实现确实只考虑了 RequestParameters 并且远未得到优化或经过良好测试。不过,对于其他一些在同一个兔子洞中旅行的可怜的灵魂来说,它可能会派上用场:

public static Link getTemplatedLink(final Method m, final String rel) {
    DefaultParameterNameDiscoverer disco = new DefaultParameterNameDiscoverer();

    ControllerLinkBuilder builder = ControllerLinkBuilder.linkTo(m.getDeclaringClass(), m);
    UriTemplate uriTemplate = new UriTemplate(UriComponentsBuilder.fromUri(builder.toUri()).build().toUriString());
    Annotation[][] parameterAnnotations = m.getParameterAnnotations();

    int param = 0;
    for (Annotation[] parameterAnnotation : parameterAnnotations) {
        for (Annotation annotation : parameterAnnotation) {
            if (annotation.annotationType().equals(RequestParam.class)) {
                RequestParam rpa = (RequestParam) annotation;
                String parameterName = rpa.name();
                if (StringUtils.isEmpty(parameterName)) parameterName = disco.getParameterNames(m)[param];
                uriTemplate = uriTemplate.with(parameterName, TemplateVariable.VariableType.REQUEST_PARAM);
            }
        }
        param++;
    }
    return new Link(uriTemplate, rel);
}
于 2016-10-11T16:32:16.170 回答