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

Spring Boot PUT请求传JSON对象报500错误求助

REST服务500内部错误排查与修复

问题背景

用Java Spring Boot搭建REST后端控制器,前端通过Angular的HttpClient调用接口时出现500内部错误。曾尝试在请求体添加"parameters=",问题未解决,确认问题出在Java代码层面。

相关日志信息

OPTIONS "/api/adress/sav", parameters={}
Mapped to saveAdress(Adress)
Completed 200 OK
PUT "/api/adress/sav", parameters={}
Mapped to com.gcssara.hexa.application.AdressEndPoint#saveAdress(Adress)
Failed to complete request: java.lang.NullPointerException
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
"ERROR" dispatch for PUT "/error", parameters={}
Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/json, application/*+json]
Writing [{timestamp=Tue Aug 30 14:41:23 CEST 2022, status=500, error=Internal Server Error, path=/api/adressm (truncated)...]
Exiting from "ERROR" dispatch, status 500

代码问题分析

Java控制器代码问题

原控制器方法未添加@RequestBody注解,Spring无法将请求体中的JSON数据绑定到Adresse参数,导致参数为null,调用adressService.saveAdress(adress)时触发空指针异常。

原代码:

@RestController
@RequestMapping("/api/adress")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class AdressEndPoint {

    @PutMapping(path ="/sav")
    public Adress saveAdress( Adresse adress) {
return adressService.saveAdress(adress);
    }

}

Angular请求代码问题

使用JSON.stringify(adress)将对象转为字符串,导致请求体格式为纯文本,请求头Content-Type被设为text/plain,而Spring默认期望application/json格式,引发415不支持的媒体类型错误(从请求头日志可见Status code:415)。

原代码:

createUpdate(adress:Adress, ) {
      return this._httpClient.put<Adress>(this.requestUrlBase +"/api/adress/sav",JSON.stringify(adress), {} );
    }

修复步骤

  1. 修正Java控制器代码:给方法参数添加@RequestBody注解,让Spring自动解析请求体JSON到Adresse对象:
@RestController
@RequestMapping("/api/adress")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class AdressEndPoint {

    @PutMapping(path ="/sav")
    public Adress saveAdress(@RequestBody Adresse adress) {
return adressService.saveAdress(adress);
    }

}
  1. 修正Angular请求代码:去掉JSON.stringify,直接传入adress对象,HttpClient会自动将对象序列化为JSON,并设置正确的Content-Type: application/json请求头:
createUpdate(adress:Adress) {
      return this._httpClient.put<Adress>(this.requestUrlBase +"/api/adress/sav", adress);
    }
  1. 检查实体类配置:确保Adresse实体类具备无参构造器、getter和setter方法,保证Jackson能正确完成JSON反序列化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:51:25