【问题标题】:How to pass correct JSON to contoller in Spring MVC?如何在 Spring MVC 中将正确的 JSON 传递给控制器​​?
【发布时间】:2014-05-26 01:52:01
【问题描述】:

我无法弄清楚为什么在将 POST 请求传递给 http://localhost:8080/company 时会收到 HTTP 415

我在 POST 请求中的 JSON

{
    "id" : 7,
    "name" : "IBM"
}

这是我在控制器中的方法

@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;

有什么解决办法吗?

更新:

回复信息:The server refused this request because the request entity is in a format not supported by the requested resource for the requested method

【问题讨论】:

  • 我更新了我的问题。
  • 你确定你没有得到 406 吗? 405 与错误消息不匹配。还是 415?
  • 抱歉,当然是HTTP Status 415

标签: java json spring spring-mvc


【解决方案1】:

你会注意到你的方法被注释了

@RequestMapping(method = RequestMethod.POST,
                consumes = MediaType.APPLICATION_JSON_VALUE)

consumes 是对@RequestMapping 的限制,表示此方法将仅处理具有Content-Typeapplication/json 的请求。您的请求似乎没有该标头。您需要添加它。

【讨论】:

    猜你喜欢
    • 2013-03-19
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多