-2

I'm trying to redirect in different jsp page logged in user for example "Admin" and in a different view a non logged in user. Here is my method till now...

@RequestMapping(value = "/lidhOfruesKerkues", method = RequestMethod.POST)
    public ModelAndView lidhOfruesKerkues(@ModelAttribute("merrPersiperKerkues") Kerkues k, Ofrues ofrues,
            Authentication authResult) {
        ofruesService.addOfrues(ofrues);
        int kerkuesId = k.getKerkuesId();
        ofruesService.matchOfruesKerkues(kerkuesId);
        String role = authResult.getAuthorities().toString();
        if (role.contains("ROLE_ADMIN")) {
            return new ModelAndView("redirect:/adminHome");
        } 
        return new ModelAndView("redirect:/ofrojNdihmeView/getKerkuesAktiv");
    }

Error thrown is java.lang.NullPointerException: null that comes from "role" when I'm as a non logged in user. If I am logged in as ADMIN it works and redirects me as it should. Thanks in advance.

Mark B
  • 183,023
  • 24
  • 297
  • 295

1 Answers1

0

You need to add a null checks to your code, something like this:

String role = null;
if (authResult != null && authResult.getAuthorities() != null) {
    role = authResult.getAuthorities().toString();
}
if (role != null && role.contains("ROLE_ADMIN")) {
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • As I said, "role" is throwing that. The line just before if condition. – Perthupuethto Dec 30 '19 at 17:03
  • 1
    Saying "role" is throwing it was not enough information. In the future please include the actual line number instead of just mentioning a variable name that happens to be on the line. You need to add checks if `authResult` or `authResult.getAuthorities()` are `null`. – Mark B Dec 30 '19 at 17:06