java - 当前登录的用户返回 Null,即使它显示当前用户信息

标签 java spring spring-boot authentication thymeleaf

在我的 Spring 项目中,我可以注册用户并显示当前用户信息,但是在我的控制台中,当前用户返回 null,即使它在数据库中找到它并显示用户详细信息。

我可以将一个主题对象添加到我的数据库中,当我尝试将该主题添加到用户实体中的主题列表中时,它会将当前用户返回为空。 这是我的“addSubjectController”

    @Controller
 @RequestMapping("/addsubject")
 public class AddSubjectController {


@Autowired
private SubjectRepository subjectRepository;
private UserRepository userRepository;


@ModelAttribute("subject")
public Subject subject() {
    return new Subject();
}

@GetMapping
public String showSubjectForm(Model model) {
    return "addSubject";
}

@PostMapping
public String addNewSubject(@ModelAttribute("subject") @Valid @RequestBody Subject subject,UserRegistrationDto userDto, BindingResult result, Model model) {

    subjectRepository.save(subject);
    model.addAttribute("subjectName", subject.getSubjectName());
    model.addAttribute("subjectGradeGoal", subject.getSubjectGradeGoal());

    Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
    String email = loggedInUser.getName();    //It cannot find the loggedInUser

    User user = userRepository.findByEmailAddress(email); //The error is happening at this line

    user.addSubject(subject);
userRepository.save(user);
    return "userProfile1";

}

在我的添加主题 Controller 中,此行发生错误: 用户 user = userRepository.findByEmailAddress(email);

因为它说当前用户不存在于 userRepostory 中,即使用户在其中,所以它只是找不到当前登录的用户。

这是我的用户实体

@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "emailAddress"))
public class User implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
//@NotBlank

@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public List<Subject> subject;



@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(
        name = "users_roles",
        joinColumns = @JoinColumn(
                name = "user_userId", referencedColumnName = "userId"),
        inverseJoinColumns = @JoinColumn(
                name = "role_id", referencedColumnName = "id"))

public Collection<Role> roles;

public List<Subject> getSubject() {
    if (subject==null)
        subject = new ArrayList<Subject>();

    return subject;
}

private String username;

//@NotBlank
private String password;

//@NotBlank
private String firstName;

//@NotBlank
private String surname;

//@NotBlank
private int age;

//@NotBlank
private double height;

//@NotBlank
private double weight;

//@NotBlank
private String emailAddress;

//@NotBlank
private String gender;

//@NotBlank
private String dob;

Boolean studentStatus;

public User() {
}
      }

public User(Long userId, List<Subject> subject, Collection<Role> roles,              String username, String password,
        String firstName, String surname, int age, double height, double weight, String emailAddress, String gender,
        String dob, Boolean studentStatus) {
    super();
    this.userId = userId;
    this.subject = subject;
    this.roles = roles;
    this.username = username;
    this.password = password;
    this.firstName = firstName;
    this.surname = surname;
    this.age = age;
    this.height = height;
    this.weight = weight;
    this.emailAddress = emailAddress;
    this.gender = gender;
    this.dob = dob;
    this.studentStatus = studentStatus;
}

public Long getUserId() {
    return userId;
}

public void setUserId(Long userId) {
    this.userId = userId;
}
return subject;

public void setSubject(List<Subject> subject) {
    this.subject = subject;
}

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;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

public double getHeight() {
    return height;
}

public void setHeight(double height) {
    this.height = height;
}

public double getWeight() {
    return weight;
}

public void setWeight(double weight) {
    this.weight = weight;
}

public String getEmailAddress() {
    return emailAddress;
}

public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
}

public String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public Boolean getStudentStatus() {
    return studentStatus;
}

public void setStudentStatus(Boolean studentStatus) {
    this.studentStatus = studentStatus;
} 

@Override
public String toString() {
    return "User{" +
            "id=" + userId +
            ", firstName='" + firstName + '\'' +
            ", surname='" + surname + '\'' +
            ", email='" + emailAddress + '\'' +
            ", password='" + "*********" + '\'' +
            ", roles=" + roles +
            '}';
}

public Collection<Role> getRoles() {
    return roles;
}

public void setRoles(Collection<Role> roles) {
    this.roles = roles;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public boolean isAccountNonExpired() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean isAccountNonLocked() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean isCredentialsNonExpired() {
    // TODO Auto-generated method stub
    return false;
}

@Override
public boolean isEnabled() {
    // TODO Auto-generated method stub
    return false;
}



    public void addSubject(Subject Subject){

        getSubject().add(Subject);
    }

这是我的科目

 @Entity
  public class Subject implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long subjectId;

@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public List<Exam> exam;

@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public List<Assignment> assignment;

private String subjectName;

private Double subjectGradeGoal;


private Double subjectResults;
exams/assignments is 20%
private Double maxSubRemMarks;

public List<Exam> getExam() {
    if (exam==null)
        exam = new ArrayList<Exam>();

    return exam;
}

public List<Assignment> getAssignment() {
    if (assignment==null)
        assignment = new ArrayList<Assignment>();

    return assignment;
}


public Subject() {
    super();
    this.subjectId = subjectId;
    this.exam = exam;
    this.assignment = assignment;
    this.subjectName = subjectName;
    this.subjectGradeGoal = subjectGradeGoal;
    this.subjectResults = subjectResults;
    this.maxSubRemMarks = maxSubRemMarks;
}

public Long getSubjectId() {
    return subjectId;
}

public void setSubjectId(Long subjectId) {
    this.subjectId = subjectId;
}

public void setExam(List<Exam> exam) {
    this.exam = exam;
}

public void setAssignment(List<Assignment> assignment) {
    this.assignment = assignment;
}

public String getSubjectName() {
    return subjectName;
}

public void setSubjectName(String subjectName) {
    this.subjectName = subjectName;
}

public Double getSubjectGradeGoal() {
    return subjectGradeGoal;
}

public void setSubjectGradeGoal(Double subjectGradeGoal) {
    this.subjectGradeGoal = subjectGradeGoal;
}

public Double getSubjectResults() {
    return subjectResults;
}

public void setSubjectResults(Double subjectResults) {
    this.subjectResults = subjectResults;
}

public Double getMaxSubRemMarks() {
    return maxSubRemMarks;
}

public void setMaxSubRemMarks(Double maxSubRemMarks) {
    this.maxSubRemMarks = maxSubRemMarks;
}

public void add(UserRepository userR) {
    // TODO Auto-generated method stub

}

public void addExam(Exam exam){

    getExam().add(exam);
}


public void addAssignment(Assignment assignment){

    getAssignment().add(assignment);
}

https://memorynotfound.com/spring-security-user-registration-example-thymeleaf/

这是我用来实现登录的登录和注册教程的链接。

最佳答案

在上面添加@Autowired

私有(private) UserRepository userRepository;

这将告诉 Spring 有关存储库的信息。如果您还没有这样做,您还需要使用 @Repository 注释您的 UserRepository 类。

或者,您可以创建一个构造函数,而不是使用字段注入(inject)进行 Autowiring 。

关于java - 当前登录的用户返回 Null,即使它显示当前用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829333/

相关文章:

java - eclipse spring 中正确的文件路径是什么

java - 如何将 war 文件添加到另一个 java web 应用程序依赖项?

spring - Actor 模型模式: Limiting number of concurrent running actors

java - org.springframework.beans.factory.UnsatisfiedDependencyException : Unsatisfied dependency expressed through method 'anyMethodName' parameter 0:

java - 如何 Autowiring 动态类

java - src/main/resources 文件被 src/test/resources 覆盖

java - Spring Boot中Kotlin Controller 类可以访问Java服务类吗

java - 将两个 ToggleButtons 绑定(bind)到一个 BooleanProperty

java - 使用包含的工作区项目运行 Eclipse 插件测试

java - 仅使用 AWS 免费套餐的 Spring Boot 项目