【问题标题】:Display a String in a view returned by a Spring Boot Thymeleaf controller在 Spring Boot Thymeleaf 控制器返回的视图中显示字符串
【发布时间】:2019-01-25 08:27:01
【问题描述】:

我在视图中苦苦挣扎,我需要在视图上显示我的 API 函数的返回:

Spring 控制器代码

@Controller
public class mainController {

  @RequestMapping(value = {"/"}, method = RequestMethod.GET)
  public String index() throws IOException, GeneralSecurityException {
    DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
    String res = drive.checkFile("cwg");

    return res;

drive.checkFile是一个返回String的API函数。

我需要在我的视图index.html 上显示它。 非常感谢你。

【问题讨论】:

  • 使用@RestController?或将@ResponseBody 添加到您的控制器方法中?
  • @Keijack 是其中之一。拥有@RestController 已经将@ResponseBody 添加到您的方法中。 * Types that carry this annotation are treated as controllers where * {@link RequestMapping @RequestMapping} methods assume * {@link ResponseBody @ResponseBody} semantics by default.
  • 你会在没有ajax请求的情况下使用这个方法吗?如果是这样,那么您将获得带有该方法返回的字符串的空白页面。
  • 是的,我得到了空白页,到目前为止我有 0 次 ajax 经验。你能给我一些线索吗?
  • @Pijotrek 是的,你是对的,所以我使用or

标签: java spring-boot thymeleaf


【解决方案1】:

更新您的方法如下:

@RestController
public class mainController {

  @RequestMapping(value = "/", method = RequestMethod.GET)
  public String index() throws IOException, GeneralSecurityException {
    DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
    String res = drive.checkFile("cwg");

    return res;
}

我做的修改是: 将 @Controller 替换为 @RestController 和 更新@RequestMapping

【讨论】:

  • 您好,谢谢您的回答,我已经这样做了,但它只是在白页上显示字符串。我的目标是建立一个小界面,我可以在其中创建/显示/删除文件。所以我需要在我的html页面上显示它
  • 希望您将通过 html 中的 AJAX 调用调用此 REST 服务,在您的 AJAX 调用中,您将获得此方法的输出作为响应字符串。使用此字符串(响应值)并显示在您的 html 页面中。
  • 太棒了!一票将不胜感激:P 干杯!
【解决方案2】:
@GetMapping("/")
public String index(Model model) throws IOException, GeneralSecurityException {
        DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
        model.addAttribute("drive", drive)
    return "/routeToTemplate";
    }

在百里香中

<div th:text="${drive}"></div>

【讨论】:

  • 感谢您的回答,但在 index.html 中他无法解析 ${drive} 无法弄清楚原因。
  • 有什么建议吗?我的回报可能是错误的?如果我需要在模板/index.html 上显示它
  • 您能否在项目中指向您的代码和 index.html 或至少是目录布局,否则很难说出什么不适合您。
猜你喜欢
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多