I can’t get a list of users from the database.I am assuming userService.allUsers () = null. But why? I have no idea. Since there are users in the database. Please tell me what is wrong with my code? It does not give me any errors in the logs. AdminController
JavaScript
x
@Controller
@RequestMapping("/forAdmin")
public class AdminController {
@Autowired
private UserService userService;
@GetMapping("/")
public String index(Model model) {
return "index";
}
@GetMapping("/forAdmin")
public String userList(Model model) {
Iterable<User> allUser = userService.allUsers();
if(allUser != null){
model.addAttribute("allUsers", allUser);
} else {
return "redirect:/index";
}
return "forAdmin";
}
Class UserService
JavaScript
@Service
public class UserService implements UserDetailsService {
@PersistenceContext
private EntityManager em;
@Autowired
public UserRepository userRepository;
@Autowired
public RoleRepository roleRepository;
@Autowired
public BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("Пользователь не найден");
}
return user;
}
public User findUserById(Long userId) {
Optional<User> userFromDb = userRepository.findById(userId);
return userFromDb.orElse(new User());
}
public List<User> allUsers() {
return userRepository.findAll();
}
public boolean saveUser(User user) {
User userFromDB = userRepository.findByUsername(user.getUsername());
if (userFromDB != null) {
return false;
}
user.setUsername(user.getUsername());
user.setRoles(Collections.singleton(new Role(1L, "ROLE_USER")));
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
userRepository.save(user);
return true;
}
public boolean deleteUser(Long userId) {
if (userRepository.findById(userId).isPresent()) {
userRepository.deleteById(userId);
return true;
}
return false;
}
}
ForAdmin.html
JavaScript
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:c=""
xmlns:el="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>forAdmin</title>
</head>
<body>
<h2> Admin Page</h2>
<a th:href="@{/index}">Main</a>
<div th:each= "el :${allUsers}">
<p th:text="${el.id}" />
<p th:text="${el.username}" />
</div>
</body>
</html>
Interface UserRepository
@Component
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
I do not even understand why nothing is written to me in the logs, as if the data does not reach thymeleaf.Tell me what is wrong with my code?
Advertisement
Answer
Actually i might already know what your problem is – you have defined the endpoint forAdmin
twice: once at class level and once again with @GetMapping
. The resulting endpoint is localhost/forAdmin/forAdmin
and of course if you have been using localhost/forAdmin
the endpoint wouldn’t get loaded