如何在springboot web中获取@DeleteMapping以停止返回405不允许的方法

问题描述 投票:0回答:1

我正在学习 springboot,目前遇到一个问题,每当我发送删除请求时,我都会在邮递员和命令提示符中收到 405 method not allowed 错误。

这是我的

AuthorCtrl
文件

AuthorCtrl

package com.samuel.progresqldatabase.controllers;

import com.samuel.progresqldatabase.domain.dto.AuthorDto;
import com.samuel.progresqldatabase.domain.entities.AuthorEntity;
import com.samuel.progresqldatabase.mappers.Mapper;
import com.samuel.progresqldatabase.services.AuthorService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
public class AuthorCtrl {

    private AuthorService authorService;
    private Mapper<AuthorEntity, AuthorDto> authorMapper;


    public AuthorCtrl(AuthorService authorService, Mapper<AuthorEntity, AuthorDto> authorMapper) {
        this.authorMapper = authorMapper;
        this.authorService = authorService;
    }

    @PostMapping(path = "/authors")
    public ResponseEntity<AuthorDto> createAuthor(@RequestBody AuthorDto authorDto) {
        AuthorEntity authorEntity = authorMapper.mapFrom(authorDto);
        AuthorEntity savedAuthorEntity = authorService.save(authorEntity);
        return new ResponseEntity<>(authorMapper.mapTo(savedAuthorEntity), HttpStatus.CREATED);
    }

    @GetMapping(path="/authors")
    public ResponseEntity<List<AuthorDto>> getAuthors() {
        List<AuthorEntity> authorEntitites = authorService.getAuthors();
        return new ResponseEntity<>(authorEntitites.stream().map(authorMapper::mapTo).collect(Collectors.toList()), HttpStatus.OK);
    }

    @GetMapping(path="/authors/{id}")
    public  ResponseEntity<AuthorDto> getAuthor(@PathVariable("id") Long id) {
        Optional<AuthorEntity> foundAuthor = authorService.getAuthor(id);
        System.out.println(foundAuthor);
        return foundAuthor.map(authorEntity -> {
            AuthorDto authorDto = authorMapper.mapTo(authorEntity);
            return new ResponseEntity<>(authorDto, HttpStatus.OK);
        }).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @PutMapping(path = "/authors/{id}")
    public ResponseEntity<AuthorDto> updateAuthor(@PathVariable("id") Long id, @RequestBody AuthorDto authorDto) {
        if (!authorService.isExists(id)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        authorDto.setId(id);
        AuthorEntity authorEntity = authorMapper.mapFrom(authorDto);
        AuthorDto updatedAuthorDto = authorMapper.mapTo(authorService.save(authorEntity));
        return new ResponseEntity<>(updatedAuthorDto, HttpStatus.OK);
    }

    @PatchMapping(path = "/authors/{id}")
    public ResponseEntity<AuthorDto> patchAuthor(@PathVariable("id") Long id, @RequestBody AuthorDto authorDto) {
        if (!authorService.isExists(id)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        authorDto.setId(id);
        AuthorEntity authorEntity = authorMapper.mapFrom(authorDto);
        AuthorDto updatedAuthorDto = authorMapper.mapTo(authorService.patch(authorEntity));
        return new ResponseEntity<>(updatedAuthorDto, HttpStatus.OK);
    }


    @DeleteMapping(path = "authors/a/{id}")
    public ResponseEntity<?> deleteAuthor(@PathVariable("id") Long id) {
        authorService.delete(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}

AuthorRepo

package com.samuel.progresqldatabase.repositories;

import com.samuel.progresqldatabase.domain.entities.AuthorEntity;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository

public interface AuthorRepo extends CrudRepository<AuthorEntity, Long> {


}

AuthorServiceImpl

package com.samuel.progresqldatabase.services.impl;

import com.samuel.progresqldatabase.domain.entities.AuthorEntity;
import com.samuel.progresqldatabase.repositories.AuthorRepo;
import com.samuel.progresqldatabase.services.AuthorService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Service
public class AuthorServiceImpl implements AuthorService {
    private AuthorRepo authorRepo;

    public  AuthorServiceImpl(AuthorRepo authorRepo) {
        this.authorRepo = authorRepo;
    }

    @Override
    public AuthorEntity save(AuthorEntity authorEntity) {
        return authorRepo.save(authorEntity);
    }

    @Override
    public List<AuthorEntity> getAuthors() {
        return StreamSupport.stream(authorRepo.findAll().spliterator(), false).collect(Collectors.toList());
    }

    @Override
    public Optional<AuthorEntity> getAuthor(Long id) {
        return authorRepo.findById(id);
    }

    @Override
    public boolean isExists(Long id) {
        return authorRepo.existsById(id);
    }

    @Override
    public AuthorEntity patch(AuthorEntity authorEntity) {
        Long id  = authorEntity.getId();
        return authorRepo.findById(id).map(
                existingAuthor -> {
                    Optional.ofNullable(authorEntity.getName()).ifPresent(existingAuthor::setName);
                    Optional.ofNullable(authorEntity.getAge()).ifPresent(existingAuthor::setAge);
                    return authorRepo.save(existingAuthor);
                }
        ).orElseThrow(() -> new RuntimeException("Author does not exist"));
    }

    @Override
    public void delete(Long id) {
         authorRepo.deleteById(id);
    }
}

我尝试编辑 application.properties 文件,但没有成功

spring.mvc.hiddenmethod.filter.enabled=true

java spring-boot spring-mvc spring-data-jpa
1个回答
0
投票

我认为您可能会以 DELETE /authors/{id} 的形式调用端点,并且由于 Spring Boot 无法将其映射到具有该路径的任何端点(只能映射到 GET、PUT 或 PATCH),因此它会失败,因为该方法是不允许使用该路径。

您唯一的 DELETE 端点是“authors/a/{id}”(/a/ 是拼写错误吗?我建议使用路径 /authors/{id} 以获得更好的连贯性并遵循良好实践),如果您使用该方法调用它路径,它应该正确响应。

如果有帮助请告诉我:)

© www.soinside.com 2019 - 2024. All rights reserved.