Spring Boot的GET和POST返回未找到(CrudRepository)

huangapple go评论80阅读模式
英文:

Spring Boot GET and POST returning Not Found (CrudReposirory)

问题

基本上就是标题所说的。控制台中没有显示错误,所以我不知道问题出在哪里。我正在使用 CrudRepository。任务是为游戏商店创建一个 REST API。我试图访问 localhost:8080/game 的 URL,但是一直出现 404 错误。

编辑:将 @PostMapping() 和 @GetMapping() 更改为 @PostMapping 和 @GetMapping

GameStoreApplication.java:

package com.game_store.si2;

@SpringBootApplication
@ComponentScan("com.game_store.si2.repository")
public class GameStoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(GameStoreApplication.class, args);
    }

}

GameController.java:

package com.game_store.si2.controller;

@RestController
@RequestMapping("/game")
public class GameController {

    @Autowired
    private GameRepository repository;

    @PostMapping
    public ResponseEntity<Game> newGame(@RequestBody Game novoGame) {
        if(novoGame.getTitulo() != null) {
            repository.save(novoGame);
            return new ResponseEntity<>(HttpStatus.CREATED);
        }
        else {
            return new ResponseEntity<Game>(novoGame, HttpStatus.UNPROCESSABLE_ENTITY);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Game> findGame(@PathVariable int id){
        Optional<Game> gameObtido = repository.findById(id);
        if(!gameObtido.isPresent()) {
            return new ResponseEntity<Game>(HttpStatus.OK);
        }
        return new ResponseEntity<Game>(HttpStatus.NOT_FOUND);
    }

    @GetMapping
    public Iterable<Game> listGames(){
        return repository.findAll();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Game> deleteGame(@PathVariable int id){
        Game gameObtido = repository.findById(id).orElse(null);
        if(gameObtido != null) {
            repository.delete(gameObtido);
            return new ResponseEntity<Game>(gameObtido, HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<Game>(HttpStatus.NOT_FOUND);
    }

    @PutMapping("/update/{id}")
    public ResponseEntity<Game> updateGame(@PathVariable int id, @RequestBody Game game){
        Game existeGame = repository.findById(id).orElse(null);
        if(existeGame != null) {
            existeGame.setImgUrl(game.getImgUrl());
            existeGame.setPreco(game.getPreco());
            existeGame.setTitulo(game.getTitulo());
            repository.save(existeGame);
            return new ResponseEntity<Game>(existeGame, HttpStatus.OK);
        }
        return new ResponseEntity<Game>(HttpStatus.NOT_FOUND);
    }

}

Game.java:

package com.game_store.si2.model;

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Game {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private int id;

    private String titulo;
    private String ImgUrl;
    private double preco;
    private int numVendas;

}

GameRepository.java:

package com.game_store.si2.repository;

@RepositoryRestResource(collectionResourceRel = "game", path = "game")
public interface GameRepository extends CrudRepository<Game, Integer> {

}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.game_store</groupId>
    <artifactId>game_store</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>game_store</name>
    <description>Projeto de game store de SI2</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

GET 和 POST 返回:

{
    "timestamp": "2020-09-10T03:41:47.478+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "",
    "path": "/game"
}
英文:

Basically what the title says. No errors show in the console so I have no idea what's wrong. I am using CrudRepository. The task is to make a REST API for a game store. I am trying to access localhost:8080/game URL but 404 keeps happening.

Edit: changed @PostMapping() and @GetMapping() to @PostMapping and @GetMapping

GameStoreApplication.java:

package com.game_store.si2;
@SpringBootApplication
@ComponentScan(&quot;com.game_store.si2.repository&quot;)
public class GameStoreApplication {
public static void main(String[] args) {
SpringApplication.run(GameStoreApplication.class, args);
}
}

GameController.java:

package com.game_store.si2.controller;
@RestController @RequestMapping(&quot;/game&quot;)
public class GameController {
@Autowired
private GameRepository repository;
@PostMapping
public ResponseEntity&lt;Game&gt; newGame(@RequestBody Game novoGame) {
if(novoGame.getTitulo() != null) {
repository.save(novoGame);
return new ResponseEntity&lt;&gt;(HttpStatus.CREATED);
}
else {
return new ResponseEntity&lt;Game&gt;(novoGame, HttpStatus.UNPROCESSABLE_ENTITY);
}
}
@GetMapping(&quot;/{id}&quot;)
public ResponseEntity&lt;Game&gt; findGame(@PathVariable int id){
Optional&lt;Game&gt; gameObtido = repository.findById(id);
if(!gameObtido.isPresent()) {
return new ResponseEntity&lt;Game&gt;(HttpStatus.OK);
}
return new ResponseEntity&lt;Game&gt;(HttpStatus.NOT_FOUND);
}
@GetMapping
public Iterable&lt;Game&gt; listGames(){
return repository.findAll();
}
@DeleteMapping(&quot;/{id}&quot;)
public ResponseEntity&lt;Game&gt; deleteGame(@PathVariable int id){
Game gameObtido = repository.findById(id).orElse(null);
if(gameObtido != null) {
repository.delete(gameObtido);
return new ResponseEntity&lt;Game&gt;(gameObtido, HttpStatus.NO_CONTENT);
}
return new ResponseEntity&lt;Game&gt;(HttpStatus.NOT_FOUND);
}
@PutMapping(&quot;/update/{id}&quot;)
public ResponseEntity&lt;Game&gt; updateGame(@PathVariable int id,@RequestBody Game game){
Game existeGame = repository.findById(id).orElse(null);
if(existeGame != null) {
existeGame.setImgUrl(game.getImgUrl());
existeGame.setPreco(game.getPreco());
existeGame.setTitulo(game.getTitulo());
repository.save(existeGame);
return new ResponseEntity&lt;Game&gt;(existeGame, HttpStatus.OK);
}
return new ResponseEntity&lt;Game&gt;(HttpStatus.NOT_FOUND);
}
}

Game.java:

package com.game_store.si2.model;
@Entity @Getter @Setter @NoArgsConstructor
public class Game {
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String titulo;
private String ImgUrl;
private double preco;
private int numVendas;
}

GameRepository.java:

package com.game_store.si2.repository;
@RepositoryRestResource(collectionResourceRel = &quot;game&quot;, path = &quot;game&quot;)
public interface GameRepository extends CrudRepository&lt;Game, Integer&gt; {
}

pom.xml:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
&lt;parent&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
&lt;version&gt;2.3.3.RELEASE&lt;/version&gt;
&lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
&lt;/parent&gt;
&lt;groupId&gt;com.game_store&lt;/groupId&gt;
&lt;artifactId&gt;game_store&lt;/artifactId&gt;
&lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
&lt;name&gt;game_store&lt;/name&gt;
&lt;description&gt;Projeto de game store de SI2&lt;/description&gt;
&lt;properties&gt;
&lt;java.version&gt;1.8&lt;/java.version&gt;
&lt;/properties&gt;
&lt;dependencies&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-data-rest&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;com.h2database&lt;/groupId&gt;
&lt;artifactId&gt;h2&lt;/artifactId&gt;
&lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
&lt;artifactId&gt;lombok&lt;/artifactId&gt;
&lt;optional&gt;true&lt;/optional&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
&lt;scope&gt;test&lt;/scope&gt;
&lt;exclusions&gt;
&lt;exclusion&gt;
&lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
&lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
&lt;/exclusion&gt;
&lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;javax.persistence&lt;/groupId&gt;
&lt;artifactId&gt;javax.persistence-api&lt;/artifactId&gt;
&lt;version&gt;2.2&lt;/version&gt;
&lt;/dependency&gt;
&lt;/dependencies&gt;
&lt;build&gt;
&lt;plugins&gt;
&lt;plugin&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
&lt;/build&gt;
&lt;/project&gt;

GET and POST return:

{
&quot;timestamp&quot;: &quot;2020-09-10T03:41:47.478+00:00&quot;,
&quot;status&quot;: 404,
&quot;error&quot;: &quot;Not Found&quot;,
&quot;message&quot;: &quot;&quot;,
&quot;path&quot;: &quot;/game&quot;
}

答案1

得分: 1

你可以将下面的方法中的 @GetMapping() 替换为 @GetMapping,将 @PostMapping() 替换为 @PostMapping,就像这样:

@GetMapping
public Iterable<Game> listGames(){
     return repository.findAll();
}

@PostMapping
public ResponseEntity<Game> newGame(@RequestBody Game novoGame) {
    if(novoGame.getTitulo() != null) {
        repository.save(novoGame);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
    else {
        return new ResponseEntity<Game>(novoGame, HttpStatus.UNPROCESSABLE_ENTITY);
    }
}
英文:
You can replace @GetMapping() to @GetMapping and @PostMapping() to @PostMapping
in below method respectively like
@GetMapping
public Iterable&lt;Game&gt; listGames(){
return repository.findAll();
}
@PostMapping
public ResponseEntity&lt;Game&gt; newGame(@RequestBody Game novoGame) {
if(novoGame.getTitulo() != null) {
repository.save(novoGame);
return new ResponseEntity&lt;&gt;(HttpStatus.CREATED);
}
else {
return new ResponseEntity&lt;Game&gt;(novoGame, HttpStatus.UNPROCESSABLE_ENTITY);
}
}

答案2

得分: 0

使用 GetMappingPostMapping 的默认值,您可以使用以下方式:

@GetMapping
@PostMapping

或者

@GetMapping("")
@PostMapping("")
英文:

To use default value of GetMapping and PostMapping you can use

@GetMapping
@PostMapping

or

@GetMapping(&quot;&quot;)
@PostMapping(&quot;&quot;)

答案3

得分: 0

只需将@PostMapping()重命名为@PostMapping

英文:

just rename @PostMapping() to @PostMapping

huangapple
  • 本文由 发表于 2020年9月10日 11:49:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63822555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定