spring 无法使用Postman或通过键入URL从Sping Boot API获取数据

omjgkv6w  于 2023-03-11  发布在  Spring
关注(0)|答案(2)|浏览(146)

我正在做一个项目,我试图通过名称获取用户数据。到目前为止,我可以成功地将我的Json数据发布到我的H2数据库中。但是,通过在URL中键入ID#获取数据是唯一有效的方法。到目前为止,我停止在userService.java中使用我预期的函数public List<User> getUserByTheName(String name),因为它根本不起作用。
我无法获取所有数据,也无法使用Controller.java中的函数public List<User> getUserByName(@PathVariable("name") String name)按名称获取用户数据。Postman无法获取任何用户数据,http://localhost:8080/users无法显示所有用户数据,http://localhost:8080/user/name/{user}无法显示任何数据。我只能在屏幕上获取error 500
我不确定是什么问题,也不知道应该遵循什么样的线索。发布数据可以正常工作,但获取数据不行。我可以在URL中按ID#搜索,但不能在URL中按名称搜索。
My Project Folder Hierarchy
Main.java

package com.geektext;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class Main extends SpringBootServletInitializer {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Started ...");
        SpringApplication.run(Main.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Main.class);
    }
}

Controller.java

package com.geektext.controller;

import java.util.List;
import java.util.stream.Collectors;

// Imports needed to create RESTful API, do not edit.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.PathVariable;  
//import org.springframework.web.bind.annotation.PostMapping;  
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 com.geektext.user.User;
import com.geektext.userService.userService; 

// RESTful Controller
@RestController
public class Controller {
    
    
    @Autowired
    userService userService;
    
    
    // Create a @GetMapping that retrieves all user details from the database   
    @GetMapping("/users")
    public List<User> getAllUsers() {
        List<User> list =  userService.getAllUser();
        return list;
    }
    
    // Create a @GetMapping that retrieves the detail of a specific student by id
    @GetMapping(path ="/user/{id}")
    public User getUser(@PathVariable("id") int id) {
        return userService.getUserById(id);
    }
    
    // Create a @GetMapping that retrieves the detail of a specific student by name
    @GetMapping(value = "/user/name/{name}")
    public List<User> getUserByName(@PathVariable("name") String name) {
        return userService.getAllUser().stream().filter(n -> n.getUser_name().matches(name)).collect(Collectors.toList());
    }
    
    // Create a @DeleteMapping that deletes a specific student
    @DeleteMapping(path ="/user/{id}")
    public void deleteUser(@PathVariable("id") int id) {
        userService.deleteData(id);
    }
    
    // Create a @PostMapping that posts the detail of a specific student
    //@PostMapping(path = "/user")
    @RequestMapping(value = "/user", method = {RequestMethod.POST})
    public int saveUser(@RequestBody User user) {
        //System.out.print("print me");
        userService.saveData(user);
        return user.getUser_id();   
    }
    
}

userService.java

package com.geektext.userService;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.geektext.user.User;
import com.geektext.userRepository.UserRepository;
import com.geektext.userRepository.UserRepositoryImpl;

@Service
public class userService extends UserRepositoryImpl {
    
    @Autowired
    UserRepository userRepository;
    UserRepositoryImpl userRepositoryImpl;
    
    // Function to query all user data
    public List<User> getAllUser() {
        List<User> users = new ArrayList<>();
        userRepository.findAll().forEach(user -> users.add(user));
        return users;
    }
    
    
    // Function to query one specific user
    public User getUserById(int id) {
        return userRepository.findById(id).orElseGet(null);
    }
    
    
    // Function to save or update a user
    public void saveData(User user) {
        userRepository.save(user);
    }
    
    
    // Function to delete a specific user by id
    public void deleteData(int id) {
        userRepository.deleteById(id);
    }

    //@Override
    public List<User> getUserByTheName(String name) {       
        return userRepositoryImpl.findAllUsers(name);
    }

}

UserRepository.java

package com.geektext.userRepository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;

import com.geektext.user.User;

public interface UserRepository extends JpaRepository<User, Integer> {
    public List<User> findAllUsers(String userName);
    public List<User> getUserByName(Iterable<User> iterable, String userName);
}

UserRepositoryCustom.java

package com.geektext.userRepository;

import java.util.List;

import com.geektext.user.User;

public interface UserRepositoryCustom {
    public List<User> findAllUsers(String userName);
    public List<User> getUserByName(Iterable<User> iterable, String userName);

}

UserRepositoryImpl.java

package com.geektext.userRepository;

import java.util.ArrayList;
import java.util.List;

import com.geektext.user.User;

public class UserRepositoryImpl implements UserRepositoryCustom {
    UserRepository userRepository;
    UserRepositoryCustom userRepoCust;
    User user;
    
    public List<User> findAllUsers(String userName) {
        Iterable<User> findAllIterable = userRepository.findAll();
        return getUserByName(findAllIterable, userName);
    }

    public List<User> getUserByName(Iterable<User> iterable, String userName) {
        List<User> listOfStudents = new ArrayList<>();
        for (User user : iterable) {
            if (user.getUser_name().equalsIgnoreCase(userName)) {
                System.out.print(user.getUser_name());
                listOfStudents.add(user);
            }   
        }
        return listOfStudents;
    }
}

User.java

package com.geektext.user;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity  
@Table
public class User {
    //mark id as primary key  
        @Id  
        //defining user_id as column name  
        @Column  
        private int user_id;
        //defining user_name as column name  
        @Column  
        private String user_name;
        //defining user_password as column name  
        @Column  
        private String user_password;
        //defining user_email_address as column name   
        @Column  
        private String user_email_address;
        //defining user_home_address as column name   
        @Column  
        private String user_home_address;
        
        
        public String getUser_email_address() {
            return user_email_address;
        }
        public void setUser_email_address(String user_email_address) {
            this.user_email_address = user_email_address;
        }
        public String getUser_home_address() {
            return user_home_address;
        }
        public void setUser_home_address(String user_home_address) {
            this.user_home_address = user_home_address;
        }
        public int getUser_id() {
            return user_id;
        }
        public void setUser_id(int user_id) {
            this.user_id = user_id;
        }
        public String getUser_name() {
            return user_name;
        }
        public void setUser_name(String user_name) {
            this.user_name = user_name;
        }
        public String getUser_password() {
            return user_password;
        }
        public void setUser_password(String user_password) {
            this.user_password = user_password;
        }
        
}

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.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>
t3psigkw

t3psigkw1#

我想为这个帖子道歉。我打开了我的程序来显示堆栈跟踪(昨天没有,但我想显示我的500和404),并测试了一切。它工作。获取所有用户和获取特定用户。我不确定我做了什么,除了重新启动,因为我昨晚关闭了我的电脑。
在此期间,我没有更改任何代码。我只是打开计算机,打开Eclipse,运行程序,将测试信息作为Json发布,并试图获取信息。
一切正常。抱歉,我不知道发生了什么。

h5qlskok

h5qlskok2#

我认为这是一种超自然现象...??

相关问题