Spring引导-为什么我不能在RestController中生成字符串?
在SpringBoot中,我正在配置服务器,除了我的RestController之外,一切都正常工作。我不知道为什么: (所以还不允许包含图片,这里有一个链接) 这就是小控制器类。注意,我的Intellij IDEA中的方法名称 为灰色-未使用Spring引导-为什么我不能在RestController中生成字符串?,spring,spring-boot,rest,Spring,Spring Boot,Rest,在SpringBoot中,我正在配置服务器,除了我的RestController之外,一切都正常工作。我不知道为什么: (所以还不允许包含图片,这里有一个链接) 这就是小控制器类。注意,我的Intellij IDEA中的方法名称 为灰色-未使用 package com.example.intermediate.controller; import org.springframework.web.bind.annotation.*; @RestController public class
package com.example.intermediate.controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class GrakaController {
@GetMapping(value = "/graka", produces = "text/plain")
@ResponseBody
public String getSimpleString() {
return "IT WORKED!";
}
}
在《邮递员》中,我尝试使用http://localhost:8080/graka
:我得到的返回码是200,但响应正文是空的,无论我在Postman中选择哪种响应正文格式。但我想我应该把“成功了”这句话拿回来
我为此挣扎了几个小时。谁有什么想法?谢谢你的每一个提示 对于Spring4,如果您的控制器使用@RestController注释,则不需要@ResponseBody注释 使用响应性
@GetMapping("/graka")
public ResponseEntity<String> getSimpleString() {
LOG.info("REST request get string value");
return new ResponseEntity<>("{\"status\" : \"IT WORKED!\"}", HttpStatus.OK);
}
@GetMapping(“/graka”)
公共响应getSimpleString(){
LOG.info(“REST请求获取字符串值”);
返回新的ResponseEntity(“{\“status\”:\“IT WORKED!\“}”,HttpStatus.OK);
}
试试这个
@GetMapping("/graka")
public String getSimpleString(){
return "IT WORKED!";
}
也许你没有重新编译你的代码?我尝试在上创建spring boot应用程序,仅使用web依赖项,并将您的方法复制粘贴到控制器中,然后在控制台curl-X GET“”中执行,我得到了正确的响应。尝试在Browser中打开URL。您可以将代码库推到某个位置,例如GitHub一段时间看看吗?它在spring boot 2.3.0上运行良好,那么您使用的Spring boot版本是什么呢?它适用于Spring boot 2.3.4。控制器位于与主应用程序不同的包中。Spring可能不会使用它来创建bean(但因为您得到的响应是200,这让我很困惑)。你能分享你的主应用程序类吗?响应只是使代码复杂化了。在这种情况下,这是不必要的。ResponseBody不应该破坏控制器。没错,RestController是可选的。是的,还有其他选项可以满足我们的需要,它们可以产生更干净的代码。使用ResponseEntity对我来说似乎是最先进的,您不需要
ResponseEntity
。只有当你需要控制响应代码、内容,并且想做更复杂的事情时,才需要这样做。我试过了,它不起作用。只是一个空洞的回答