Angular4调用Spring Boot REST接口报错:数组类无默认构造函数
解决Spring Boot接收Angular POST数组时的构造函数错误
你遇到的这个错误其实不是StudentDetails类缺少无参构造——你已经正确定义了无参构造,问题出在Spring MVC没法直接处理数组类型的请求体参数。错误信息里的[Lcom.luv2code.springboot.cruddemo.entity.StudentDetails;是Java中数组的类名标识,Spring尝试实例化这个数组类型,但数组本身没有无参构造(也不能通过这种方式实例化),所以抛出了这个异常。
解决方案步骤:
1. 修改Spring控制器方法参数,改用List并添加@RequestBody注解
Spring的消息转换器(比如Jackson)可以很好地将JSON数组转换为List<StudentDetails>,但你需要明确告诉Spring要从请求体中读取数据,所以要加上@RequestBody注解,同时把参数类型从数组换成List:
@RestController @RequestMapping("api") @CrossOrigin(origins = "http://localhost:4200") // 解决跨域问题,根据你的Angular端口调整 public class StudentDetailsController { private StudentRepository studentRepositor; @Autowired public StudentDetailsController(StudentRepository theStudentDetailDAO) { this.studentRepositor = theStudentDetailDAO; } @RequestMapping(value="/saveStudent", method = RequestMethod.POST, produces = "application/json") public void saveStudent(@RequestBody List<StudentDetails> objStudentDetails) { List<StudentDetails> lstStudentDetais = studentRepositor.findAll(); studentRepositor.save(objStudentDetails.get(0)); } }
这里的@CrossOrigin是为了处理Angular和Spring Boot端口不同导致的跨域问题,如果你的项目已经全局配置了CORS,可以忽略这个注解。
2. 优化Angular端的请求代码
你的Angular代码已经接近正确,但不需要手动调用JSON.stringify——Angular的Http.post方法会自动帮你把对象序列化为JSON字符串,所以可以简化代码:
import { Injectable } from '@angular/core'; import { Http, Headers, Response, RequestOptions } from '@angular/http'; @Injectable() export class ServerService { constructor(private http: Http) { } headers = new Headers({"Content-Type": "application/json"}); storeServers(students: any[]) { const WEBSERVICE_ADDRESS_STUDENT: string = "http://localhost:8080/api/saveStudent"; // 直接传入students数组,不用手动JSON.stringify return this.http.post(WEBSERVICE_ADDRESS_STUDENT, students,{ headers: this.headers }) .subscribe( (response) => console.log(response), (error) => console.error("error: ", error) ); } }
为什么这样能解决问题?
- Spring MVC默认不会自动将请求体的JSON数据绑定到数组类型参数,而
List是集合类型,Jackson可以轻松将JSON数组转换为List<StudentDetails>。 @RequestBody注解明确告诉Spring:“从HTTP请求体中读取数据,并将其反序列化为方法参数的类型”,这是处理POST请求体数据的标准方式。
内容的提问来源于stack exchange,提问作者user2746466
相关产品推荐
相关产品推荐

