java - 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();
}
}
解决方案
包括application.properties
以下内容:
server.servlet.context-path=/api
但是,默认情况下,这将使其成为应用程序中所有端点的根
此外,一旦包含@RequestMapping
注释,您是为整个控制器还是为每个方法的标头设置它?
推荐阅读
- for-loop - 初学者的基本问题。bucle 中的定义存在问题。枫
- javascript - 浏览器选项卡查询“接收端不存在”,适用于 chrome
- python-3.x - Python 请求未收到响应 cookie
- java - 如何修复以下错误“请将环境变量 OPENCV_ANDROID_SDK 指定到 OpenCV Android SDK 目录。” 在安卓工作室?
- django - 在 Django 中扩展抽象模型
- php - 使用 php PDO 在 while($row->$statement->fetch()) 中不起作用
- ruby-on-rails - 电子邮件格式验证的 RSpec 失败
- c# - http请求不包含.net core 2.1中createresponse的定义
- django - MultipleObjectsReturned- get() 返回了多个 mPurchase - 它返回了 2
- java - 注释类型元素的语法是什么?