【发布时间】:2016-10-16 11:43:51
【问题描述】:
这是我的控制器:
@RequestMapping(value = "", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> create(
@RequestBody Category category) {
if (categoryService.create(category)) {
return new ResponseEntity<String>(HttpStatus.OK);
} else {
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
}
}
这是我的配置:
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<context:component-scan base-package="ru.tenet.cafe" />
这是类别类:
private Integer id;
private String title;
private String engTitle;
private String description;
private List<MenuItem> menuItems;
public Category()
{
}
public Category(Integer id, String title, String engTitle,
String description, List<MenuItem> menuItems) {
super();
this.id = id;
this.title = title;
this.engTitle = engTitle;
this.description = description;
this.menuItems = menuItems;
}
// getters and setters
如果我尝试使用 Content-type:application/json 和以下正文发送 post 请求:
{"id":8,"title":"Пицца","engTitle":"Pizza","description":null,"menuItems":[{"id":4,"title":"Пепперони ","engTitle":"Pepperoni","price":300.0,"description":"Сами лючщи пица слющи。 Тольки щто привезли дарагой.","consistOf":"E666, стальная стружка, вода (без ГМО)","volumeValue":500.0,"volumeTitle":"г"},{"id":5,"title":"Маргарита","engTitle":"Margarita","price":400.0,"description ":"Сами сочни пица слющи。 Мамай клянус.","consistOf":"Перец, сыр, колбаска, ногти","volumeValue":500.0,"volumeTitle":"г"},{"id":6,"title":"Кавказ","engTitle":"Kavkaz ji est","price":300.0,"description":"Вах пица. Сам ем дарагой.","consistOf":"Ароматизатор \"Гусь\" идентичный натуральному","volumeValue":500.0,"volumeTitle":"г"}]}
我会得到:
HTTP 状态 415。服务器拒绝此请求,因为请求 实体的格式不受请求的资源支持 请求的方法。
怎么了?
统一更新:
添加这个
@RequestMapping(value = "", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE,produces = "application/json") 给了我同样的结果
【问题讨论】:
-
在@RequestMapping 中添加
produces = "application/json"。请求时还要在请求中添加标头 -
在
@RequestMapping注解中添加consumes = MediaType.APPLICATION_JSON_VALUE -
没有帮助。同样的事情。
-
@ViswanathLekshmanan,什么样的标题?内容类型?
-
是的。在请求中添加 Content-Type