如何在Spring MVC中将正确的JSON传递给控制器? [英] How to pass correct JSON to contoller in Spring MVC?
本文介绍了如何在Spring MVC中将正确的JSON传递给控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法弄清楚为什么在将POST请求传递给 http:// localhost:8080 / company
I can't figure out why I'm get HTTP 415 when pass POST request to http://localhost:8080/company
我在POST请求中的JSON
My JSON in POST request
{
"id" : 7,
"name" : "IBM"
}
这是我在控制器中的方法
Here is my method in controller
@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
CompanyRepository companyRepository;
@RequestMapping(method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<Company> getAll() {
return companyRepository.getCompanies();
}
@RequestMapping(method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public String add(@RequestBody Company company) {
companyRepository.save(company);
return "redirect:/company";
}
}
我的实体
@Entity
@Table(name = "company")
public class Company implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column
private String name;
@JsonIgnore
@OneToMany(mappedBy = "company")
@LazyCollection(LazyCollectionOption.FALSE)
private Collection<Employee> employees;
任何想法如何解决?
UPD:
响应消息:服务器拒绝了此请求,因为请求实体的格式不受请求方法所请求的资源支持
推荐答案
您会注意到您的方法是用
You'll notice your method is annotated with
@RequestMapping(method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
消费
是 @RequestMapping
的限制说此方法仅处理 Content-Type
application / json
的请求。您的请求似乎没有该标头。你需要添加它。
The consumes
is a restriction for the @RequestMapping
saying that this method will only handle requests that have a Content-Type
of application/json
. Your request doesn't seem to have that header. You need to add it.
这篇关于如何在Spring MVC中将正确的JSON传递给控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文