java - 请求方法 'GET' 不受支持,但它实际上存在于 Controller 中

标签 java spring spring-mvc

当我遇到这个奇怪的错误时,我正在开发一个简单的 CRUD 应用程序。奇怪的是,因为在我的 Controller 类中,方便的 @RequestMapping 注释方法与请求 GET 方法映射一起存在。请求的 URI 为 [context]/purchase/change/2。错误如下:

org.springframework.web.servlet.PageNotFound - Request method 'GET' not supported

这是我的 Controller :

@Controller
@RequestMapping("/purchase")
public class PurchasesController {

    //...

    @RequestMapping(value = "/add/{userId}", method = RequestMethod.GET)
    public String addPurchase(Model model, @PathVariable int userId) {
        //that method works with mapping ex. "context/purchase/add/1"
        return "purchase_update_add";
    }

    @RequestMapping(value = "/add/{userId}", method = RequestMethod.POST)
    public String addPurchase(
            @ModelAttribute("purchase") PurchaseDTO purchaseDto,
            @PathVariable int userId) {

        //that works too

        return "redirect:/user/" + userId;
    }

    @RequestMapping(value = "/change/${purchaseId}", method = RequestMethod.GET)
    public String changePurchaseDate(Model model, @PathVariable int purchaseId) {

        model.addAttribute("operation", "change");

        PurchaseDTO purchase = new PurchaseDTO();
        Purchase purchaseEntity = purchasesDAO.getPurchase(purchaseId);
        purchase.setDate(purchaseEntity.getDate());
        purchase.setId(purchaseId);

        model.addAttribute("purchase", purchase);

        return "purchase_update_add";
    }

    @RequestMapping(value = "/change/{userId}", method = RequestMethod.POST)
    public String changePurchaseDate(
            @ModelAttribute("purchase") PurchaseDTO purchaseDto,
            @PathVariable int userId) {
        Purchase purchase = purchasesDAO.getPurchase(purchaseDto.getId());
        purchase.setDate(purchaseDto.getDate());
        purchasesDAO.updatePurchase(purchase);
        return "redirect:/user/" + userId;
    }

最佳答案

您已经使用 ${...} 语法创建了一个路径变量:

@RequestMapping(value = "/change/${purchaseId}", method = RequestMethod.GET)
                                 ^ $ is redundant

请使用正确的 {...} 语法:

@RequestMapping(value = "/change/{purchaseId}", method = RequestMethod.GET)

关于java - 请求方法 'GET' 不受支持,但它实际上存在于 Controller 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35274501/

相关文章:

java - 如何从java中的base64编码字体字符串创建字体文件

启用安全性的 Spring Boot 1.4 测试?

java - Spring CSS 图像加载

java - 使用 spring 和 tomcat 静态编织 eclipselink jpa

java - 在 Spring 中使用 @Inject 进行字段注入(inject)

java - Hibernate @Size 验证自定义类型

java - 通过Java在RTF文件中搜索单词

java - 无法在 Google App Engine 上发送电子邮件

java - spring JPA查询与spel表达式随机

spring - 使用条件查询/hibernate 查询选择最大 id 行时出现问题?