我正在使用Spring启动RESTful服务,Eclipse中的Java 8。每当我尝试从Postman(或任何其他地方)发送HTTP请求时,我都会收到404 Not found代码。除了其他的东西(代码的变化),我尝试安装Tomcat但似乎没有问题(它似乎很好,它适用于其他项目)。在过去的两个小时里,我在想象中尝试了一切。
open()
休息控制器: 包hr.fer.rznu.controller;
package hr.fer.rznu.init;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Lab1Application implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(Lab1Application.class, args);
}
@Override
public void run(String... args) throws Exception {
}
}
这是在build.gradle:
import java.util.List;
import hr.fer.rznu.model.User;
import hr.fer.rznu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RestController
public class RestAPIController {
@Autowired
UserService userService;
@RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
Long id = userService.addUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(id).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> getListOfUsers() {
List<User> users = userService.getAllUsers();
if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
}
如果需要,我可以提供更多代码或信息。我有用户模型,&#34; UserService&#34;像getUserById等方法。有人有任何建议吗?
答案 0 :(得分:1)
一些事情
似乎@SpringBootApplication在不同的包中而不是RestController
尝试以下,
@SpringBootApplication(scanBasePackages={"hr.fer.rznu"})
映射中的删除结束斜杠/
@RequestMapping(value = "/user", method = RequestMethod.POST)
和
@RequestMapping(value = "/user", method = RequestMethod.GET)