第一种方法:
@RequestMapping(value = "/api/version/products", method = RequestMethod.GET)
public ModelAndView getAllProducts() throws IOException {
List<Product> products = productService.findAllProducts();
ModelAndView model = new ModelAndView("main");
model.addObject("products", products);
return model;
}
第二种方法:
@RequestMapping(value = "/api/version/products/{id}", method = RequestMethod.DELETE)
public String deleteProduct(@PathVariable String id) throws IOException {
Product productToDelete = productService.findById(id);
if (productToDelete != null) {
productService.deleteProduct(id);
}
return "redirect:/api/version/products";
}
DELETE请求后我收到了这条消息:
HTTP状态405 - 不支持请求方法“DELETE”
第三种方法正常工作:
@RequestMapping(value = "/api/version/products", method = RequestMethod.POST)
public String addProduct(@RequestParam String name, @RequestParam String price) throws IOException {
Product product = new Product();
product.setName(name);
product.setPrice(new BigDecimal(price));
productService.saveProduct(product);
return "redirect:/api/version/products";
}
答案 0 :(得分:2)
1)尝试使用与DELETE处理程序相同的URL路径添加GET请求处理程序(重定向到某些其他页面或其他内容)
@RequestMapping(value = "/api/version/products/{id}", method = RequestMethod.GET)
public String getProduct(@PathVariable String id) throws IOException {
return "redirect:/";
}
我曾经遇到过这样的问题,这解决了它
2)尝试:&#34; api / version / products / {id}&#34;而不是&#34; / api / version / products / {id}&#34;
答案 1 :(得分:0)
您可以使用AJAX调用void删除方法,然后在成功后重定向到所需的页面。
您将需要JQuery依赖项和简单的js文件引用来调用它……
类似的东西:
$('.deleteProductButton').on('click', function () {
var productId = $(this).attr('data-product-id');
$.ajax({
type : "DELETE",
url : "/api/version/products/"+ productId,
success: function (result) {
console.log(result);
window.location = '/api/version/products'; // redirect
},
error: function (e) {
console.log(e);
}
});
});
@RequestMapping(value = "/api/version/products/{id}", method = RequestMethod.DELETE)
public void deleteProduct(@PathVariable String id) throws IOException {
Product productToDelete = productService.findById(id);
if (productToDelete != null) {
productService.deleteProduct(id);
}
}