简体   繁体   中英

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

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.

So the problem is user.getUsername() . the user is null and trying to get its username causes a NullPointerWxception.

add a check before that call, try this:

if (user != null) {
    loginExist = userRepo.findCountUsername(user.getUsername());
}

otherwise (if it is null), you need to create the user before trying to find it from repository.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM