首页 > 解决方案 > Rest Controller returns 404 on base path

问题描述

I am trying to make a REST API with Spring Boot. When I do "http://localhost:8080/foo/*", I get what I want but when I use "http://localhost:8080/api/foo/*", I get 404 error. I have other controllers that are almost the same and they work just fine. I have tried using @RequestMapping but nothing changed. application.properties:

.
.
spring.data.rest.base-path=/api

Controller:

@RestController
public class FooController {
    @Autowired
    private FooRepository fooRepository;
    
    @GetMapping("/foo")
    public List<Foo> retreiveAllFoos(){
        return fooRepository.findAll();
    }
    
    @GetMapping("/foo/{id}")
    public Foo retrieveFoo(@PathVariable int id) {
        Optional<Foo> foo = fooRepository.findById(id);
        return foo.get();
    }
    
    @DeleteMapping("/foo/{id}")
    public void deleteFoo(@PathVariable int id) {
        fooRepository.deleteById(id);
    }
    
    @PostMapping("/foo")
    public ResponseEntity<Object> createFoo(@RequestBody Foo foo){
        Foo savedFoo = fooRepository.save(foo);
        
        
        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
                .buildAndExpand(savedFoo.getId()).toUri();
        return ResponseEntity.created(location).build();
    }
    
    @PutMapping("/foo/{id}")
    public ResponseEntity<Object> updateFoo(@RequestBody Foo foo, @PathVariable int id){
        Optional<Foo> fooOptional = fooRepository.findById(id);
        
        if(!fooOptional.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        foo.setId(id);
        
        fooRepository.save(foo);
        
        return ResponseEntity.noContent().build();
    }
}

标签: javaspring-bootspring-mvcspring-restcontroller

解决方案


包括application.properties以下内容:

server.servlet.context-path=/api

但是,默认情况下,这将使其成为应用程序中所有端点的根

此外,一旦包含@RequestMapping注释,您是为整个控制器还是为每个方法的标头设置它?


推荐阅读