jan*_*nes 4 rest json spring-mvc backbone.js
我是Spring MVC的新手,我正在尝试使用Spring MVC + Hibernate从头开始构建一个Web应用程序来提供类似JSON Rest API的东西,在客户端通过Backbone消耗这个API.为此,我开始学习本教程(http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/).
So I have a model Message which will have the following REST API Interface:
GET /api/messages ( working ok )
GET /api/messages/:id ( working ok )
DELETE /api/messages/:id ( working ok )
PUT /api/messages/:id ( working ok )
POST /api/messages ( error: (DefaultHandlerExceptionResolver.java:194) - Request method 'POST' not supported)
Run Code Online (Sandbox Code Playgroud)
我预计在通过表单执行请求时,PUT或DELETE请求会发生此问题,但不会发生POST请求.我甚至没有通过表格来处理请求.在客户端,请求通过Backbone完成,如下所示:
new App.Models.Message({ attributeA : 'a', attributeB : 'b' }).save();
Run Code Online (Sandbox Code Playgroud)
我已经尝试在web.xml中添加httpMethodFilter,如其他Stackoverflow问题所示:
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<servlet-name>mvc-dispatcher</servlet-name>
</filter-mapping>
Run Code Online (Sandbox Code Playgroud)
有没有人有同样的问题?
我离开这里我的MessagesController:
@Controller
@RequestMapping("/api/messages")
public class MessagesController {
@Autowired
private MessageService messageService;
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody List<Message> getMessagesInJSON(@RequestParam( value = "type", required = false ) String type) {
List<Message> messages = messageService.findAll();
return messages;
}
@RequestMapping( value = "/{id}", method = RequestMethod.GET )
public @ResponseBody Message getMessageInJson(@PathVariable Integer id ) {
Message message = messageService.findById(id);
return message;
}
@RequestMapping( value = "/{id}", method = RequestMethod.DELETE )
@ResponseStatus( value = HttpStatus.NO_CONTENT )
public void deleteMessage(@PathVariable Integer id ) throws NotFoundException {
messageService.delete(id);
}
@RequestMapping( value = "/{id}", method = RequestMethod.PUT )
@ResponseStatus( value = HttpStatus.NO_CONTENT )
public void editMessage( @PathVariable Integer id, @RequestBody Message message ) throws NotFoundException {
message.setId(id);
messageService.update(message);
}
@RequestMapping( value = "/", method = RequestMethod.POST )
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody Message createMessage( @RequestBody Message message ) {
return messageService.create(message);
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢!
您已经映射/api/messages
到getMessagesInJSON
仅允许GET请求的方法.您的POST请求将映射到其他路径.
我建议在请求映射中省略value属性createMessage
.
@RequestMapping(method = RequestMethod.POST )
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
44326 次 |
最近记录: |