Template variables with ControllerLinkBuilder

后端 未结 7 1991
生来不讨喜
生来不讨喜 2021-02-13 17:54

I want my response to include this:

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

That\'s easy

7条回答
  •  既然无缘
    2021-02-13 18:18

    Based on the previous comments I have implemented a generic helper method (against spring-hateoas-0.20.0) as a "temporary" workaround. The implementation does consider only RequestParameters and is far from being optimized or well tested. It might come handy to some other poor soul traveling down the same rabbit hole though:

    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);
    }
    

提交回复
热议问题