2014-04-11 35 views
2

我想不通爲什麼我GET HTTP 415時通POST請求http://localhost:8080/company如何在Spring MVC中將正確的JSON傳遞給控制器​​?

我在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; 

任何想法如何修理它?

UPD:

響應消息:The server refused this request because the request entity is in a format not supported by the requested resource for the requested method

+0

我更新了我的問題。 – Arkasha

+0

你確定你沒有收到406嗎? 405與錯誤消息不匹配。還是415? –

+0

對不起,'HTTP狀態415'當然。 – Arkasha

回答

6

你會發現你的方法標註有

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

consumes對於@RequestMapping說,這種方法只會處理請求的限制有Content-Typeapplication/json。您的請求似乎沒有該標題。你需要添加它。

相關問題