Spring MVC HTTP Status 405 - Metoda żądania „POST” nie jest obsługiwana - Backbone Request
Jestem nowym użytkownikiem Spring MVC i próbuję zbudować aplikację sieciową od podstaw przy użyciu Spring MVC + Hibernate, aby obsłużyć coś takiego jak JSON Rest API, mając ten interfejs API wykorzystany przez Backbone po stronie klienta. Aby to zrobić, zacząłem śledzić ten samouczek (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)
Spodziewałem się, że ten problem wystąpi w przypadku żądań PUT lub DELETE podczas wykonywania żądania za pomocą formularza, ale nie w przypadku żądania POST. Nie wykonuję nawet prośby za pomocą formularza. Po stronie klienta żądanie jest realizowane za pomocą Backbone w ten sposób:
new App.Models.Message({ attributeA : 'a', attributeB : 'b' }).save();
Próbowałem już dodać httpMethodFilter w web.xml, jak sugerowano w innych pytaniach 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>
Czy ktoś miał ten sam problem?
Zostawiam tutaj mój 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);
}
}
Wielkie dzięki!