我有这样的User
类:
@Data
@Entity
public class User {
@Id @GeneratedValue Long userID;
String eMail;
String passwordHash;
}
我有这样的数据:
[{"userID":1,"passwordHash":"asdasd","email":"admin@admin.com"},
{"userID":2,"passwordHash":"12345","email":"admin1asdasd@admin.com"}]
我的 Controller 类中有两种方法,一种是获取单个用户:
@GetMapping("/user/{id}")
User one(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
检索所有用户的其他方法:
@GetMapping("/user")
List<User> all() {
return repository.findAll();
}
在我的浏览器中,访问这个地址 - http://localhost:8080/user
,我可以看到这些数据。如果我转到http://localhost:8080/user/id我可以获得一个特定的值。
现在我的问题是如何访问像http://localhost:8080/user/email/passwordHash
这样的数据?我很确定这是不可能的,因为我没有以这种方式存储数据。
由于我的主要目标是验证登录,因此我已经在存储库界面中编写了一个@Query
。这是:
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.eMail = ?1 and u.passwordHash = ?2")
List<User> listByLoginCredential(String emailAddress,String passwordHash);
}
谁能告诉我该怎么做,使用这个接口(interface)的这个方法吗?
最佳答案
我认为你可以通过在 Controller 类中添加以下方法来实现你想要的:
@GetMapping("/user/{emailAddress}/{passwordHash}")
List<User> byMailAndPassword(@PathVariable String emailAddress, @PathVariable String passwordHash) {
return repository.listByLoginCredential(emailAddress, passwordHash)
}
另一方面,您说您的主要目标是验证登录,因此看起来您正在进行身份验证。如果你有时间,你应该考虑使用 spring security https://spring.io/guides/gs/securing-web/#initial 来做这件事。
关于java - 来自 Controller 的 Spring Boot 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57587172/