简体   繁体   English

Rest Controller 在基本路径上返回 404

[英]Rest Controller returns 404 on base path

I am trying to make a REST API with Spring Boot.我正在尝试使用 Spring 启动 REST API。 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.当我执行“http://localhost:8080/foo/*”时,我得到了我想要的,但是当我使用“http://localhost:8080/api/foo/*”时,我得到 404 错误。 I have other controllers that are almost the same and they work just fine.我有其他几乎相同的控制器,它们工作得很好。 I have tried using @RequestMapping but nothing changed.我尝试过使用@RequestMapping,但没有任何改变。 application.properties:应用程序属性:

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

Controller: 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();
    }
}

The correct property is spring.data.rest.basePath so you want the following in application.properties :正确的属性是spring.data.rest.basePath因此您需要在application.properties中包含以下内容:

spring.data.rest.basePath=/api

See https://docs.spring.io/spring-data/rest/docs/current/reference/html/#getting-started.changing-base-urihttps://docs.spring.io/spring-data/rest/docs/current/reference/html/#getting-started.changeing-base-uri

In application.properties include the following:application.properties中包括以下内容:

server.servlet.context-path=/api

However, this will make it by default the root for all endpoints in your application但是,默认情况下,这将使其成为应用程序中所有端点的根

Also, once you included the @RequestMapping annotation are you setting this for the whole controller or the header of each method?此外,一旦包含@RequestMapping注释,您是为每个方法的整个 controller 还是 header 设置这个?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM