Reputation: 441
In my Spring project I can register users and display the current users information however in my console the current user is returning null even though it is finding it in the database and displaying the users details.
I can add a subject object to my database and when I try to add that subject to a list of subjects in the user entity it is returning the current user as null. This is my "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";
}
In my add subject controller the error is happening at this line: User user = userRepository.findByEmailAddress(email);
because it is saying the current user doesn't exist in the userRepostory even though the user is in there, so it just cannot find the current logged in user.
This is my user entity
@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);
}
This is my subject class
@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/
That is a link to the login and registration tutorial I used to implement my login.
Upvotes: 2
Views: 603
Reputation: 9155
Add @Autowired
above
private UserRepository userRepository;
This will tell Spring about the repository. You'll also want to annotate your UserRepository
class with @Repository
if you haven't done so already.
Alternatively, you can create a constructor instead of using field injection for your autowiring.
Upvotes: 1