You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Spring:如何使用@RequestBody接收POST请求的JSON对象

实现接收@RequestBody的POST接口方案

没问题,我来帮你一步步搞定这个POST接口。咱们先理清楚核心逻辑:需要先定义一个请求数据类来映射POST过来的JSON参数,然后在Controller方法里用@RequestBody绑定参数,最后处理游戏业务并返回规范响应。

步骤1:创建请求参数的DTO类

首先得有个Java类来对应POST请求的JSON结构,假设你的接口是用来处理用户猜字母的操作(可以根据你的实际需求调整字段),比如:

public class GameGuessRequest {
    private String gameId;
    private char guess;

    // 记得添加getter和setter,或者用Lombok的@Data注解一键生成
    public String getGameId() {
        return gameId;
    }

    public void setGameId(String gameId) {
        this.gameId = gameId;
    }

    public char getGuess() {
        return guess;
    }

    public void setGuess(char guess) {
        this.guess = guess;
    }
}

步骤2:编写POST接口方法

接下来在你的Controller里添加POST方法,用@RequestBody接收上面的DTO,同时结合Session里的游戏数据处理业务逻辑,最后返回更新后的游戏状态:

@RequestMapping(value = "/new", method = RequestMethod.POST)
public GameUpdateResponse processGuess(HttpSession session, @RequestBody GameGuessRequest request) {
    // 从Session获取当前游戏列表
    List<Game> games = getCurrentGames(session);
    
    // 根据gameId找到对应的游戏实例
    Game targetGame = games.stream()
            .filter(game -> game.getId().equals(request.getGameId()))
            .findFirst()
            .orElseThrow(() -> new RuntimeException("找不到ID为" + request.getGameId() + "的游戏"));
    
    // 处理用户的猜测逻辑(这里需要你根据Game类的现有实现补充具体逻辑)
    boolean isGuessCorrect = targetGame.checkGuess(request.getGuess());
    String updatedWordState = targetGame.getUpdatedWord(); // 比如返回"_a__e__"这样的状态
    int remainingChances = targetGame.getRemainingAttempts();

    // 返回自定义的响应结果
    return new GameUpdateResponse(targetGame.getId(), updatedWordState, isGuessCorrect, remainingChances);
}

步骤3:定义响应结果的DTO类

为了让返回的JSON结构更规范,创建一个响应类:

public class GameUpdateResponse {
    private String gameId;
    private String word;
    private boolean correctGuess;
    private int remainingAttempts;

    // 构造函数
    public GameUpdateResponse(String gameId, String word, boolean correctGuess, int remainingAttempts) {
        this.gameId = gameId;
        this.word = word;
        this.correctGuess = correctGuess;
        this.remainingAttempts = remainingAttempts;
    }

    // 省略getter和setter,推荐用Lombok简化代码
}

示例请求与响应

  • POST请求的JSON体:
{
  "gameId": "kvmuyw",
  "guess": "o"
}
  • 返回的JSON响应:
{
  "gameId": "kvmuyw",
  "word": "__o____",
  "correctGuess": true,
  "remainingAttempts": 5
}

额外提示

  • 确保你的项目已经包含Jackson依赖(Spring Boot默认自带),这样Spring才能自动完成JSON和Java对象的互相转换。
  • 可以添加全局异常处理,比如用@ExceptionHandler捕获找不到游戏的异常,返回404状态码和友好提示。
  • 如果你的POST接口是做其他操作(比如重置游戏),只需要修改请求DTO和业务逻辑部分,@RequestBody的核心用法是一致的。

内容的提问来源于stack exchange,提问作者ohbrobig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:12:03