默认情况下,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
}
|
更多建议: