< strong>Репозиторий
Код: Выделить всё
package com.example.crudv1.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.crudv1.model.User;
@Repository
public interface UserRepository extends JpaRepository {
Optional findByUsername(String username);
}
Код: Выделить всё
package com.example.crudv1.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.crudv1.model.User;
import com.example.crudv1.repository.UserRepository;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void registerUser(String username, String password)
{
User newUser = new User();
newUser.setUsername(username);
newUser.setPassword(password);
userRepository.save(newUser);
}
//1.Dodawanie nowego użytkownika
public User add(User user) {
return userRepository.save(user);
}
//2.Znalezienie użytkownika po ID
public Optional getUserById(Long id){
return userRepository.findById(id);
}
//3 Pobranie wszystkich użytkowników
public List getAllUsers(){
return userRepository.findAll();
}
public User updateUser(Long id, User updatedUser) {
return userRepository.findById(id).map(user ->{
user.setUsername(updatedUser.getUsername());
user.setPassword(updatedUser.getPassword());
return userRepository.save(user);
}).orElseThrow(()-> new RuntimeException("User not found with id " + id));
}
public boolean authenticateUser(String username, String password) {
Optional user = userRepository.findByUsername(username);
return user.isPresent() && user.get().getPassword().equals(password);
}
public void deleteUserById(Long id) {
userRepository.deleteById(id);
}
public boolean doesUserExist(Long id) {
return userRepository.existsById(id);
}
public long getUserCount() {
return userRepository.count();
}
public List addmultipleUsers(List users){
return userRepository.saveAll(users);
}
public List getUsersByIds(List ids){
return userRepository.findAllById(ids);
}
public void deleteAllUsers() {
userRepository.deleteAll();
}
public Optional getUserByUsername(String username) {
return userRepository.findByUsername(username);
}
}
Код: Выделить всё
package com.example.crudv1.model;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Код: Выделить всё
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.crudv1.model.User;
import com.example.crudv1.service.UserService;
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/register")
public ResponseEntity register(@RequestBody User user) {
userService.registerUser(user.getUsername(), user.getPassword());
return ResponseEntity.ok("User registered successfully!");
}
@PostMapping("/login")
public ResponseEntity login(@RequestBody User user) {
boolean isAuthenticated = userService.authenticateUser(user.getUsername(), user.getPassword());
if (isAuthenticated) {
return ResponseEntity.ok("Login successful!");
} else {
return ResponseEntity.status(401).body("Invalid credentials");
}
}
}
Код: Выделить всё
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.crudv1.repository.*")
@EntityScan(basePackages = "com.example.crudv1.model.*")
@ComponentScan(basePackages = {"com.example.crudv1.service.*", "com.example.crudv1.controller.*"})
public class Crudv1Application {
public static void main(String[] args) {
SpringApplication.run(Crudv1Application.class, args);
}
}
Версия Spring Boot: [3.4.1]
UserController находится в правильном пакете com.example.crudv1.controller.
Приложение запускается без ошибки.
Другие конечные точки в моем приложении (например, /api/login) также приводят к ошибке 404.
Я проверил порт и убедился, что приложение работает. правильно.
Может ли кто-нибудь подсказать, почему я получаю ошибку 404 при попытке доступа к конечным точкам POST?
Журнал из приложения https:/ /pastebin.com/NGb5PAdL
Журнал почтальона { "timestamp": "2025-01-18T11:51:17.084+00:00", "status": 404, «ошибка»: «Не найден», «путь»: «/api/register»
Подробнее здесь: https://stackoverflow.com/questions/793 ... pplication