【问题标题】:How to send some specific info in Header and some info in Body in a single JSON response, for a GET request in Spring boot?对于 Spring Boot 中的 GET 请求,如何在单个 JSON 响应中发送 Header 中的一些特定信息和 Body 中的一些信息?
【发布时间】:2026-01-10 01:30:01
【问题描述】:

在我的 Spring boot 项目中,我创建了 AuthController 类,我在其中编写了用于发出登录 POST 请求的代码,作为响应,我显示了 jwt 令牌 由这个成功的登录请求生成。

这是我的 AuthController 类的代码-

@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(
                    loginRequest.getUsernameOrEmail(),
                    loginRequest.getPassword()
            )
    );

    SecurityContextHolder.getContext().setAuthentication(authentication);

    String jwt = tokenProvider.generateToken(authentication);
    return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
}

这是我在登录请求成功时得到的响应-

{
  "accessToken": "abcd",
  "tokenType": "Bearer"
}

----现在问题是---

我需要做一些不同的事情。我希望这个 accessToken 发送响应 HEADER 而不是 response Body响应正文,我想在 JSON 响应中发送 UserIdemail。我不知道该怎么做。因此,如果有人帮助我使用示例代码或对我给出的代码进行一些更改,那就太好了。

【问题讨论】:

    标签: java json spring-boot


    【解决方案1】:

    尝试使用HttpServletResponse 添加响应头。

    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest,
                                              HttpServletResponse response) {
    
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsernameOrEmail(),
                        loginRequest.getPassword()
                )
        );
    
        SecurityContextHolder.getContext().setAuthentication(authentication);
    
        String jwt = tokenProvider.generateToken(authentication);
    
        // set headers here
        response.addHeader("accessToken", jwt);      
        response.addHeader("tokenType", "Bearer");
    
        JwtAuthenticationResponse response = new JwtAuthenticationResponse();
        response.setUserId(/*userId here*/);
        response.setEmail(/*email here*/);
    
        return ResponseEntity.ok(response);
    }
    

    并在您的 JwtAuthenticationResponse 添加 userIdemail 字段,或者只使用另一个类。

    public class JwtAuthenticationResponse {
    
        private Long userId;
        private String email;
    
        //getters setters
    }
    

    【讨论】:

      最近更新 更多