我想使用Spring和Angular实现用户身份验证。我尝试过:
@PostMapping("request")
public ResponseEntity<?> resetRequest(@RequestBody PasswordResetDTO resetDTO) {
return userRepository.findByUsername(resetDTO.getName()).map(user -> {
if (!user.getEmail().equals(resetDTO.getEmail())) {
return new ResponseEntity<>("NAME_AND_EMAIL_MISMATCH", HttpStatus.BAD_REQUEST);
}
resetHandler.sendResetMail(user);
return ok(resetDTO);
})
.orElseGet(() -> notFound().build());
}
接口:
public interface UserRepository extends CrudRepository<Users, Integer> {
Optional<Users> findByUsername(String username);
Optional<Users> findByEmail(String email);
Optional<Users> findByResetCode(String code);
}
Impl:
@Override
public Optional<Users> findByUsername(String username) {
String hql = "select e from " + Users.class.getName() + " e where e.login = ?";
Query query = entityManager.createQuery(hql).setParameter(0, username);
Optional<Users> users = (Optional<Users>) query.getSingleResult();
return users;
}
但是我得到Users cannot be cast to java.base/java.util.Optional
实现此目标的正确方法是什么?我应该使用Optional还是仅使用null检查?
答案 0 :(得分:1)
首先,如JB Nizet建议的那样,使用类型化查询。如果不确定数据库是否会始终有查询记录,请第二次使用getResultList
(因为您使用的是可选记录,所以您可能没有)。
此处已更新findByUsername
:
@Override
public Optional<Users> findByUsername(String username) {
String hql = "select e from " + Users.class.getName() + " e where e.login = ?";
TypedQuery<Users> query = entityManager.createQuery(hql, Users.class).setParameter(0, username);
List<Users> users = query.getResultList();
return users.isEmpty() ? Optional.empty() : Optional.of( users.get(0) );
}
答案 1 :(得分:-1)
public Optional<User> editUser(int id) {
return userRepository.findById(id);
}
@RequestMapping("/edit-user")
public String editUser(@RequestParam int id, HttpServletRequest request) {
Optional<User> user = userService.editUser(id);
System.out.println("user = "+user);
request.setAttribute("users", user);
request.setAttribute("mode", "MODE_UPDATE");
return "welcomepage";
}