Micronaut 响应状态

2023-03-02 17:46 更新

默认情况下,Micronaut 控制器操作会使用 200 HTTP 状态代码进行响应。

如果操作返回 HttpResponse,请使用 status 方法配置响应的状态代码。

 Java Groovy  Kotlin 
@Get(value = "/http-response", produces = MediaType.TEXT_PLAIN)
public HttpResponse httpResponse() {
    return HttpResponse.status(HttpStatus.CREATED).body("success");
}
@Get(value = "/http-response", produces = MediaType.TEXT_PLAIN)
HttpResponse httpResponse() {
    HttpResponse.status(HttpStatus.CREATED).body("success")
}
@Get(value = "/http-response", produces = [MediaType.TEXT_PLAIN])
fun httpResponse(): HttpResponse<String> {
    return HttpResponse.status<String>(HttpStatus.CREATED).body("success")
}

您还可以使用@Status 注释。

 Java Groovy  Kotlin 
@Status(HttpStatus.CREATED)
@Get(produces = MediaType.TEXT_PLAIN)
public String index() {
    return "success";
}
@Status(HttpStatus.CREATED)
@Get(produces = MediaType.TEXT_PLAIN)
String index() {
    "success"
}
@Status(HttpStatus.CREATED)
@Get(produces = [MediaType.TEXT_PLAIN])
fun index(): String {
    return "success"
}

甚至用 HttpStatus 回应

 Java Groovy  Kotlin 
@Get("/http-status")
public HttpStatus httpStatus() {
    return HttpStatus.CREATED;
}
@Get("/http-status")
HttpStatus httpStatus() {
    HttpStatus.CREATED
}
@Get("/http-status")
fun httpStatus(): HttpStatus {
    return HttpStatus.CREATED
}


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号