Json 为什么@RequestBody获取的对象具有null属性
我有一个springboot REST控制器,带有补丁的请求方法,并按指示放置。出于某种原因,@RequestBody“company”的字段/属性以空值的形式出现。我错过了什么 我在前端使用angular8,它正在执行补丁调用 我尝试了其他一些帖子的建议,但没有成功。如果这是一个重复的问题,请告诉我答案Json 为什么@RequestBody获取的对象具有null属性,json,angular,rest,spring-boot,Json,Angular,Rest,Spring Boot,我有一个springboot REST控制器,带有补丁的请求方法,并按指示放置。出于某种原因,@RequestBody“company”的字段/属性以空值的形式出现。我错过了什么 我在前端使用angular8,它正在执行补丁调用 我尝试了其他一些帖子的建议,但没有成功。如果这是一个重复的问题,请告诉我答案 Spring Tool Suite 4 版本:4.1.0.0发布 构建Id:201812201347 版权所有(c)2007-2018 Pivotal,Inc。 版权所有。拜访 我正在使用
Spring Tool Suite 4
版本:4.1.0.0发布
构建Id:201812201347
版权所有(c)2007-2018 Pivotal,Inc。
版权所有。拜访
我正在使用pgAdmin 4.12进行博士后考试
这是我在Angular打的电话:
this.companyService.patch$(this.currentId, this.appMenu.currentObject).subscribe(selectedCompany => {this.appMenu.currentObject = selectedCompany});
这是如上所述的角度服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { Company } from '../models/company.model';
@Injectable({
providedIn: 'root'
})
export class CompanyService {
private url: string;
constructor(private http: HttpClient) {
this.url = "http://localhost:8080/niche/company";
}
getOne$ = (companyId: number): Observable<Company> => this.http.get<Company>(`${this.url}/${companyId}`);
get$ = (): Observable<Company[]> => this.http.get<Company[]>(this.url);
post$ = (company: Company): Observable<Company> => this.http.post<Company>(this.url, { company });
patch$ = (companyId: number, company: Company): Observable<Company> => this.http.patch<Company>(`${this.url}/${companyId}`, { company });
delete$ = (companyId: number): Observable<Company> => this.http.delete<Company>(`${this.url}/${companyId}`);
}
这是实际的JSON:
{"company":{"createdBy":"denis","createdDate":"2019-04-14T04:00:00.000+0000","updatedBy":"denis","updatedDate":"2019-05-14T04:00:00.000+0000","id":2,"email":"bullwinkle@mail.com","companyName":"Bull Winkle","webSite":"bullwilkle.com","phone":"999999999","notes":"test","products":[]}}
springboot后端控制器:
/**
*
*/
package com.ebusiness.niche.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import com.ebusiness.niche.entity.Company;
import com.ebusiness.niche.service.CompanyService;
//import com.sun.istack.internal.logging.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author denisputnam
*
*/
@RestController
@RequestMapping( value = "/niche" )
public class CompanyController {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private CompanyService companyService;
@ResponseBody
@RequestMapping(value = {"/company"}, method = { RequestMethod.GET })
@CrossOrigin(origins = "http://localhost:4200")
public ResponseEntity<List<Company>> getCompanys() {
log.info("getCompanys(): Called...");
List<Company> companyList = null;
companyList = this.companyService.findAll();
if( companyList == null || companyList.isEmpty() ) {
log.info("getCompanys(): returned a null or empty list.");
ResponseEntity<List<Company>> rVal = new ResponseEntity<List<Company>>(companyList, HttpStatus.NO_CONTENT);
return rVal;
}
return new ResponseEntity<List<Company>>(companyList, HttpStatus.OK);
}
@ResponseBody
@RequestMapping(value = {"/company/{id}"}, method = { RequestMethod.GET })
@CrossOrigin(origins = "http://localhost:4200")
public ResponseEntity<Company> getCompany(@PathVariable("id") Long id) {
log.info("getCompany(): Called...");
log.info("id=" + id);
// List<Company> companyList = null;
Optional<Company> optcompany = null;
Company company = null;
optcompany = this.companyService.findById(id);
if( optcompany == null ) {
log.info("getCompany(): returned a null.");
ResponseEntity<Company> rVal = new ResponseEntity<Company>(company, HttpStatus.NO_CONTENT);
return rVal;
} else {
company = optcompany.get();
}
return new ResponseEntity<Company>(company, HttpStatus.OK);
}
@ResponseBody
// @RequestMapping(value = {"/company/{id}"}, headers = {
// "content-type=application/json" }, consumes = MediaType.APPLICATION_JSON_VALUE, method = { RequestMethod.PATCH, RequestMethod.PUT, RequestMethod.POST })
@RequestMapping(value = {"/company/{id}"}, method = { RequestMethod.PATCH, RequestMethod.PUT })
@CrossOrigin(origins = {"http://localhost:4200"})
public ResponseEntity<Company> updateCompany(@PathVariable("id") Long id, @RequestBody Company company) {
log.info("updateCompany(): Called...");
log.info("id=" + id);
Optional<Company> currentCompany = this.companyService.findById(id);
Company dbCompany = null;
if( currentCompany == null ) {
log.error("Unable to update. The company with id {} not found.", id);
ResponseEntity<Company> rVal = new ResponseEntity<Company>(company, HttpStatus.NO_CONTENT);
return rVal;
}
dbCompany = currentCompany.get();
dbCompany.setCompanyName(company.getCompanyName());
dbCompany.setEmail(company.getEmail());
dbCompany.setNotes(company.getNotes());
dbCompany.setPhone(company.getPhone());
dbCompany.setWebSite(company.getWebSite());
this.companyService.update(dbCompany);
return new ResponseEntity<Company>(dbCompany, HttpStatus.OK);
}
}
我对其进行了编辑,以添加控制台日志中的跟踪输出。我还简化了公司实体,使其不包含任何日期或与其他实体的任何其他关系,因此现在只传递字符串
以下是跟踪输出:
2019-09-18 15:52:19.591 TRACE 47732 --- [nio-8080-exec-1] o.h.r.j.i.ResourceRegistryStandardImpl : Releasing JDBC resources
2019-09-18 15:52:19.591 TRACE 47732 --- [nio-8080-exec-1] cResourceLocalTransactionCoordinatorImpl : ResourceLocalTransactionCoordinatorImpl#afterCompletionCallback(true)
2019-09-18 15:52:19.591 TRACE 47732 --- [nio-8080-exec-1] .t.i.SynchronizationRegistryStandardImpl : SynchronizationRegistryStandardImpl.notifySynchronizationsAfterTransactionCompletion(3)
2019-09-18 15:52:19.591 TRACE 47732 --- [nio-8080-exec-1] org.hibernate.internal.SessionImpl : SessionImpl#afterTransactionCompletion(successful=true, delayed=false)
2019-09-18 15:52:19.594 DEBUG 47732 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/json, application/*+json]
2019-09-18 15:52:19.594 TRACE 47732 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [[com.ebusiness.niche.entity.Company@ddb52f3, com.ebusiness.niche.entity.Company@73d5674e]]
2019-09-18 15:52:19.619 TRACE 47732 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : No view rendering, null ModelAndView returned.
2019-09-18 15:52:19.619 TRACE 47732 --- [nio-8080-exec-1] org.hibernate.internal.SessionImpl : Closing session [f1652eeb-71a2-4776-8d94-9573336d60f3]
2019-09-18 15:52:19.619 TRACE 47732 --- [nio-8080-exec-1] o.h.e.jdbc.internal.JdbcCoordinatorImpl : Closing JDBC container [org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl@6effa4c8]
2019-09-18 15:52:19.619 TRACE 47732 --- [nio-8080-exec-1] o.h.r.j.i.ResourceRegistryStandardImpl : Releasing JDBC resources
2019-09-18 15:52:19.619 TRACE 47732 --- [nio-8080-exec-1] o.h.r.j.i.LogicalConnectionManagedImpl : Closing logical connection
2019-09-18 15:52:19.620 TRACE 47732 --- [nio-8080-exec-1] o.h.r.j.i.ResourceRegistryStandardImpl : Releasing JDBC resources
2019-09-18 15:52:19.620 TRACE 47732 --- [nio-8080-exec-1] o.h.r.j.i.LogicalConnectionManagedImpl : Logical connection closed
2019-09-18 15:52:19.620 DEBUG 47732 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK, headers={masked}
2019-09-18 15:52:31.192 TRACE 47732 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<com.ebusiness.niche.entity.Company> com.ebusiness.niche.controller.CompanyController.updateCompany(java.lang.Long,com.ebusiness.niche.entity.Company)
2019-09-18 15:52:31.264 TRACE 47732 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<com.ebusiness.niche.entity.Company> com.ebusiness.niche.controller.CompanyController.updateCompany(java.lang.Long,com.ebusiness.niche.entity.Company)
2019-09-18 15:52:31.266 TRACE 47732 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : PUT "/niche/company/2", parameters={}, headers={masked} in DispatcherServlet 'dispatcherServlet'
2019-09-18 15:52:31.267 TRACE 47732 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<com.ebusiness.niche.entity.Company> com.ebusiness.niche.controller.CompanyController.updateCompany(java.lang.Long,com.ebusiness.niche.entity.Company)
2019-09-18 15:52:31.268 TRACE 47732 --- [nio-8080-exec-3] .i.SessionFactoryImpl$SessionBuilderImpl : Opening Hibernate Session. tenant=null, owner=null
2019-09-18 15:52:31.268 TRACE 47732 --- [nio-8080-exec-3] org.hibernate.internal.SessionImpl : Opened Session [740dabea-2970-4491-8ff7-d373afc649f6] at timestamp: 1568836351268
2019-09-18 15:52:31.268 TRACE 47732 --- [nio-8080-exec-3] o.s.web.cors.DefaultCorsProcessor : Skip: response already contains "Access-Control-Allow-Origin"
2019-09-18 15:52:31.312 TRACE 47732 --- [nio-8080-exec-3] m.m.a.RequestResponseBodyMethodProcessor : Read "application/json;charset=UTF-8" to [com.ebusiness.niche.entity.Company@46388186]
2019-09-18 15:52:31.320 TRACE 47732 --- [nio-8080-exec-3] .w.s.m.m.a.ServletInvocableHandlerMethod : Arguments: [2, com.ebusiness.niche.entity.Company@46388186]
2019-09-18 15:52:19.591 TRACE 47732---[nio-8080-exec-1]o.h.r.j.i.ResourceRegistryStandardImpl:释放JDBC资源
2019-09-18 15:52:19.591跟踪47732---[nio-8080-exec-1]cResourceLocalTransactionCoordinatorImpl:ResourceLocalTransactionCoordinatorImpl#afterCompletionCallback(true)
2019-09-18 15:52:19.591跟踪47732---[nio-8080-exec-1].t.i.SynchronizationRegistryStandardImpl:SynchronizationRegistryStandardImpl.notifySynchronizationsAfterTransactionCompletion(3)
2019-09-18 15:52:19.591 TRACE 47732---[nio-8080-exec-1]org.hibernate.internal.SessionImpl:SessionImpl#后交易完成(成功=真,延迟=假)
2019-09-18 15:52:19.594调试47732---[nio-8080-exec-1]o.s.w.s.m.m.a.HttpEntityMethodProcessor:使用“application/json”,给定[application/json,text/plain,*/*]并支持[application/json,application/*+json,application/json,application/*+json]
2019-09-18 15:52:19.594 TRACE 47732---[nio-8080-exec-1]o.s.w.s.m.m.a.HttpEntityMethodProcessor:编写[[com.ebusiness.niche.entity]。Company@ddb52f3,com.ebusiness.niche.entity。Company@73d5674e]]
2019-09-18 15:52:19.619跟踪47732---[nio-8080-exec-1]o.s.web.servlet.DispatcherServlet:没有视图呈现,返回空模型和视图。
2019-09-18 15:52:19.619跟踪47732---[nio-8080-exec-1]org.hibernate.internal.SessionImpl:结束会话[F1652EB-71a2-4776-8d94-9573336d60f3]
2019-09-18 15:52:19.619跟踪47732---[nio-8080-exec-1]o.h.e.jdbc.internal.jdbcoordinatorImpl:关闭jdbc容器[org.hibernate.engine.jdbc.internal。JdbcCoordinatorImpl@6effa4c8]
2019-09-18 15:52:19.619跟踪47732---[nio-8080-exec-1]o.h.r.j.i.ResourceRegistryStandardImpl:释放JDBC资源
2019-09-18 15:52:19.619跟踪47732---[nio-8080-exec-1]o.h.r.j.i.LogicalConnectionManagedImpl:关闭逻辑连接
2019-09-18 15:52:19.620跟踪47732---[nio-8080-exec-1]o.h.r.j.i.ResourceRegistryStandardImpl:释放JDBC资源
2019-09-18 15:52:19.620跟踪47732---[nio-8080-exec-1]o.h.r.j.i.逻辑连接管理DIMPL:逻辑连接关闭
2019-09-18 15:52:19.620调试47732---[nio-8080-exec-1]o.s.web.servlet.DispatcherServlet:完成了200个OK,头={masked}
2019-09-18 15:52:31.192跟踪47732---[nio-8080-exec-2]s.w.s.m.m.a.RequestMappingHandlerMapping:映射到公共org.springframework.http.ResponseEntity.com.ebusiness.niche.controller.CompanyController.updateCompany(java.lang.Long,com.ebusiness.niche.entity.Company)
2019-09-18 15:52:31.264跟踪47732---[nio-8080-exec-3]s.w.s.m.m.a.RequestMappingHandlerMapping:映射到public org.springframework.http.ResponseEntity.com.ebusiness.niche.controller.CompanyController.updateCompany(java.lang.Long,com.ebusiness.niche.entity.Company)
2019-09-18 15:52:31.266跟踪47732---[nio-8080-exec-3]o.s.web.servlet.DispatcherServlet:PUT“/niche/company/2”,参数={},标题={masked}在DispatcherServlet'DispatcherServlet's中
2019-09-18 15:52:31.267 TRACE 47732---[nio-8080-exec-3]s.w.s.m.m.a.RequestMappingHandlerMapping:映射到public org.springframework.http.ResponseEntity.com.ebusiness.niche.controller.CompanyController.updateCompany(java.lang.Long,com.ebusiness.niche.entity.Company)
2019-09-18 15:52:31.268跟踪47732---[nio-8080-exec-3].i.SessionFactoryImpl$SessionBuilderImpl:打开Hibernate会话。租户=null,所有者=null
2019-09-18 15:52:31.268 TRACE 47732---[nio-8080-exec-3]org.hibernate.internal.SessionImpl:打开的会话[740dabea-2970-4491-8ff7-d373afc649f6],时间戳:156836351268
2019-09-18 15:52:31.268跟踪47732---[nio-8080-exec-3]o.s.web.cors.DefaultCorsProcessor:跳过:响应已包含“访问控制允许源”
2019-09-18 15:52:31.312跟踪47732---[nio-8080-exec-3]m.m.a.RequestResponseBodyMethodProcessor:将“应用程序/json;字符集=UTF-8”读到[com.ebusiness.niche.entity]。Company@46388186]
2019-09-18 15:52:31.320跟踪47732---[nio-8080-exec-3].w.s.m.m.a.ServlettInvocableHandlerMethod:参数:[2,com.ebusiness.niche.entity。Company@46388186]
好的,这个问题是因为从前端应用程序
将JSON主体作为嵌套了公司的JSON对象发送<代码>{company}
patch$ = (companyId: number, company: Company): Observable<Company>
=> this.http.patch<Company>(`${this.url}/${companyId}`, { company });
我的spring引导后端代码
@PutMapping("updateFile")
public ResponseEntity<String> updateAttachment(@RequestBody Attachment attachment) {
storageService.updateAttachment(attachment);
return ResponseEntity.ok("file updated successfully");
}
下面的代码有效。当传递对象时,只传递整个对象,不带括号。它将被视为数据。
const message = await axiosInstance.put<string>(
`localhost:8080/files/updateFile`,
attachment,
);
const message=等待axiosInstance.put(
`localhost:8080/files/updateFile`,
附件
);
在此行之前公司服务更新(dbCompany)代码>您得到的是bdCompany null吗?您可以调试并让我们知道这是否具有null属性,这意味着当公司服务更新dbCompany时,dbCompany正在那里执行某些操作
patch$ = (companyId: number, company: Company): Observable<Company>
=> this.http.patch<Company>(`${this.url}/${companyId}`, { company });
patch$ = (companyId: number, company: Company): Observable<Company>
=> this.http.patch<Company>(`${this.url}/${companyId}`, company);
@PutMapping("updateFile")
public ResponseEntity<String> updateAttachment(@RequestBody Attachment attachment) {
storageService.updateAttachment(attachment);
return ResponseEntity.ok("file updated successfully");
}
const message = await axiosInstance.put<string>(
`localhost:8080/files/updateFile`,
{attachment:attachment},
);
const message = await axiosInstance.put<string>(
`localhost:8080/files/updateFile`,
attachment,
);