我想为我的spring应用程序创建一个login方法。但是当我试图调用getUserByAuthentication
方法时,我得到了一个空指针异常。下面是我的代码:调用错误的函数:
@PostMapping(path = "/online")
public ResponseEntity<?> onlineRequest(@RequestBody OnlineRequest onlineRequest) {
User user = null;
UserManager userManager = new UserManager();
user = userManager.getUserByAuthentication(onlineRequest.getUsername(), onlineRequest.getPassword());
if (user!=null){
user.setLatestTimeStamp(System.currentTimeMillis());
return new ResponseEntity<>("You are now online, Enjoy!", HttpStatus.OK);
} else {
return new ResponseEntity<>("Invalid login", HttpStatus.valueOf(403));
}
}
按身份验证类获取用户:
public class UserManager {
@Autowired
private UserRepository userRepository;
public User getUserByID(int id){
return userRepository.findById(id).get();
}
public User getUserByAuthentication(String name, String password){
Iterable<User> userList = userRepository.findAll();
ArrayList<User> users = new ArrayList<>();
userList.forEach(users::add);
User user = null;
for (User u : users){
if (u.getUsername().equals(name) && u.getPassword().equals(password)){
user = u;
}
}
return user;
}
}
储存库:
@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}
使用者类别:
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//Initialize
private String username;
private String password;
private boolean hasAccess;
ArrayList<Integer> inChannels;
long latestTimeStamp;
public long getLatestTimeStamp() {
return latestTimeStamp;
}
public void setLatestTimeStamp(long latestTimeStamp) {
this.latestTimeStamp = latestTimeStamp;
}
public ArrayList<Integer> getInChannels() {
return inChannels;
}
public void setInChannels(ArrayList<Integer> inChannels) {
this.inChannels = inChannels;
}
public Long getId() {
return id;
}
public User() {
}
public boolean hasAccess() {
return hasAccess;
}
public void setAccess(boolean hasAccess) {
this.hasAccess = hasAccess;
}
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;
}
}
2条答案
按热度按时间1rhkuytd1#
如果没有在spring中定义组件的注解之一,就不能使用
@Autowired
,所以在您的情况下,可以在UserManager
上使用@Service
,如下所示:也不要在方法中使用
static
,那么就必须在控制器中注入UserManager
组件,就像处理仓库一样:然后您可以用途:
isr3a4wc2#
我通过在存储库接口中添加find函数来修复它。