Home > Enterprise >  Nested @DeleteMapping annotation inside @RequestMapping-annotated controller fails to catch URI @Pat
Nested @DeleteMapping annotation inside @RequestMapping-annotated controller fails to catch URI @Pat

Time:08-11

I'm developing a simple REST API using Java Spring-Boot. I've got a CommentController service class, written as follows:

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/api/comment")
public class CommentController {
    @Autowired
    CommentService commentService;

    //... irrelevant code

    @DeleteMapping(value = "/delete/{id}")
        public void deleteComment(@PathVariable("id") long targetId) {
            commentService.removeComment(targetId);
        }

If I run a DELETE request with the following URI: http://localhost:8081/api/comment/delete/?id=12, I receive a 404 - Not Found error.

However, should I run the following query: http://localhost:8081/api/comment/delete/12, the request is successfully completed.

I think that it might be related with the nested @DeleteMapping annotation under the @RequestMapping, however the only answer that I found mentions editing a dispatcher-servlet.xml file, but the answer is old and my project doesn't have said file. Is there a way to configure this from the application.properties file?

CodePudding user response:

You are confusing path variable with query parameter. api/comment/delete/12 and /api/comment/delete/?id=12 are different mappings. If you want to use the latter, you should accept the id as a query parameter rather than path variable.

    @DeleteMapping(value = "/delete")
    public void deleteComment(@RequestParam(name = "id") long targetId) {
         commentService.removeComment(targetId);
    }
  • Related