Micronaut控制器如何确定其基本URL

时间:2019-08-14 13:31:03

标签: java web-services micronaut

例如,如果我具有以下控制器:

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.*;

@Controller("/test")
public class TestController {
    @Get()
    @Produces(MediaType.TEXT_PLAIN)
    public String index() {
        // How should this be implemented?
        return "???";
    }
}

然后在服务器上运行它,然后我希望index方法返回http://my-server:8080

4 个答案:

答案 0 :(得分:1)

从Micronaut V1.2.0开始,您可以使用HttpHostResolver interface,例如:

import io.micronaut.http.*;
import io.micronaut.http.annotation.*;
import io.micronaut.http.server.util.HttpHostResolver;
import io.micronaut.web.router.RouteBuilder;

@Controller("/test")
public class TestController {
    private final HttpHostResolver httpHostResolver;
    private final RouteBuilder.UriNamingStrategy uriNamingStrategy;

    public TestController(
            HttpHostResolver httpHostResolver,
            RouteBuilder.UriNamingStrategy uriNamingStrategy
    ) {
        this.httpHostResolver = httpHostResolver;
        this.uriNamingStrategy = uriNamingStrategy;
    }

    @Get()
    @Produces(MediaType.TEXT_PLAIN)
    public String index(HttpRequest httpRequest) {
        return httpHostResolver.resolve(httpRequest) +
                uriNamingStrategy.resolveUri(TestController.class);
    }
}

答案 1 :(得分:0)

这似乎可行:

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.*;
import io.micronaut.runtime.server.EmbeddedServer;
import io.micronaut.web.router.RouteBuilder;

import java.net.*;

@Controller("/test")
public class TestController {
    protected final String baseUrl;

    public TestController(EmbeddedServer embeddedServer, RouteBuilder.UriNamingStrategy uns)
            throws MalformedURLException {
        final String host = embeddedServer.getHost();
        final int port = embeddedServer.getPort();
        final String file = uns.resolveUri(TestController.class);
        baseUrl = new URL("http", host, port, file).toString();
    }

    @Get()
    @Produces(MediaType.TEXT_PLAIN)
    public String index() {
        return baseUrl;
    }
}

我不确定它是惯用语言还是在所有情况下都有效。如果有人发布更好的答案,我会接受的。

答案 2 :(得分:0)

如果您希望控制器在/处响应,请使用@Controller("/")而不是@Controller("/test")

答案 3 :(得分:0)

package com.tech.api;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.PathVariable;
import java.util.List;
import javax.inject.Inject;

@Controller("/")
public class ModelDefinitionsApi {

    @Get(uri="/modelName", produces = MediaType.APPLICATION_JSON)
    public String getModel(@PathVariable String modelName) {
        return "modelName";
    }
}

http://my-server:8080 => 主控制器网址

http://my-server:8080/modelName => 用于 getModel 方法