When you mention any return type in the method signature apart from
void, at the end of the method execution the method should return a
value.
Your code is not obeying that rule.
Let's see what's happening in your code.
if (user != null) {
// (1) inside if block
} else
return new ModelAndView("oops", "user", user);
If user is null then condition will be false so the execution control will be passed to else block which will return the instance of ModelAndView("oops", "user", user); so no issues.
If user is not null then the condition will be true so the execution control will be passed into the inside of (1) if block
In the inside of (1) if block the program will write the log and then execution control will be passed to 2nd if condition.
Now let's see the second condition,
if (user.getUsername().equals("jon")){
return new ModelAndView("echo", "user", user);
}
Here if username equals to "jon" then condition will be true. Then the execution control will come inside of (2) if block. Here program control will execute new ModelAndView( "echo", "user", user ); and return the instance. No issues.
Here comes the tricking point if the username is not equals to "jon" then as no else is presented the execution control comes out of the (1) if block and reach the end of the method.
As there is no statements which return either the instance of ModelAndView or null the compiler will through an error.
So, I suggest you to deal what to be return if username is not equal to "jon" like below. And don't add return null; at the end as it may can cause some runtime exceptions;
public ModelAndView postLoginPage(@ModelAttribute("user") User user, ModelMap model,
HttpServletRequest req, HttpServletResponse res) {
if (user != null) {
logger.log(Level.INFO, "\n\n [*][*][*][*][*] user not null ");
if (user.getUsername().equals("jon")){
return new ModelAndView("echo", "user", user);
} else{ // to avoid compilation error
return new ModelAndView("user is not jon", "user", user);
}
} else
return new ModelAndView("oops", "user", user);
}
). I don't think the question was about that.