Search code examples
javaspringspring-bootjava-ee-6

how can't I update my user profile with new information?


I want to update my user profile if the String loginExist = null or loginExist.equals(principal.getName())

the problem is that I get NullPointerException.

this is my code:

// update profile
@RequestMapping(value = "/updateRH", method = RequestMethod.POST)
public ModelAndView updateRH(Principal principal, @ModelAttribute("user") user user) {
    ModelAndView mv = new ModelAndView();
    String loginExist = "";
    user rh = RhRepo.findByUsername(principal.getName());
    try {
        loginExist = userRepo.findCountUsername(user.getUsername());
    } catch (Exception e) {

    }
    System.out.println(loginExist);

    if (loginExist.equals(null) || loginExist.equals(principal.getName())) {
        user.setId(RhRepo.findByUsername(principal.getName()).getId());
        user.setPwd(encoder.encode(user.getPwd()));
        RhRepo.save(user);
    } else {
        String msg = "Username Deja exist !!!";
        mv.addObject("msg", msg);
    }

    mv.addObject("rh", rh);
    mv.setViewName("rhprofile");
    return mv;
}

Solution

  • loginExist.equals(null) will throw NPE if loginExist is null as you are trying to call a method from a null object.

    Use :-

    loginExist == null

    instead.