In JSP new session is created by default, if non present, so you will always get non null session. You can disable that by adding following page directive to your page:

 <%@ page session="false" %>

JSPs create a session unless explicitly configured not to.Instead of checking for the existence of a session check for a value in the session.

When session calls invalidate() it removes that session from server context and all associated data with that session.When you make new request it creates new one and so you see null as the data because new session doesn’t have data in it

You should check for a logical attribute inside session to validate it user is logged in or not, instead of session itself

getSession(false) – will return current session if current session will not exist then it will NOT create new session.

Calling session.invalidate() removes the session from the registry. Calling getSession(false) afterwards will return null (note that getSession() or getSession(true) will create a new session in this case). In addition all session attributes bound to the session are removed. However if your code still has references to the session or any of its attributes then these will still be accessible:

  if(request.getSession() != null)
  {
    System.out.println("Session is Created for Each Request with Unique Session ID");
  }

  HttpSession session = request.getSession();
  session.setAttribute("Name", "Mugil");

  String Name = (String) session.getAttribute("Name");
  System.out.println(session.getId());
  System.out.println(session.getAttribute("Name"));

  session.invalidate();

  if(session == null)
  {
    System.out.println("session is Null");
  }

  if(request.getSession(false) == null)
  {
    System.out.println("request.getSession(false) is Null");
  }

  if(request.getSession() != null)
  {
    System.out.println("request.getSession() is Not Null");
  }

  System.out.println(session.getId());
  System.out.println(Name);    

Output

Session is Created for Each Request with Unique Session ID
7A46A65BCDC436030AA10385998F0272
Mugil
request.getSession(false) is Null
request.getSession() is Not Null
7A46A65BCDC436030AA10385998F0272
Mugil

Note
Session is created for each request. So if you are invalidating a session of login page in the next page you should check for existence of userName as session attribute instead of checking session is null because session can never be null

The problem is that the requested page is been loaded from the browser cache instead of straight from the server. You just need to instruct the browser to not cache all the restricted JSP. This way the browser is forced to request the page from the server instead of from the cache and hence all login checks on the server will be executed.

You can do this using a Filter which sets the necessary response headers in the doFilter() method:

@WebFilter
public class NoCacheFilter implements Filter 
{
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException 
   {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");       
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        response.setDateHeader("Expires", 0); // Proxies.
        chain.doFilter(req, res);
    }
    // ...
}

Map this Filter on an url-pattern of interest, for example *.jsp.

@WebFilter("*.jsp")

Or if you want to put this restriction on secured pages only, then you should specify an URL pattern which covers all those secured pages. For example, when they are all in the folder /app, then you need to specify the URL pattern of /app/*.

 @WebFilter("/app/*")

Even more, you can do this job in the same Filter as where you’re checking the presence of the logged-in user.

Complete Authentication Filter
The filter (the interceptor) shouldn’t check the validity of the username/password combo. That’s the responsibility of the servlet (the controller).

The filter should merely check if the user is logged-in or not (usually by just checking the presence of a session attribute) and then continue the request or block it by redirecting back to the login page.

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {    
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String loginURI = request.getContextPath() + "/login";

        boolean loggedIn = session != null && session.getAttribute("user") != null;
        boolean loginRequest = request.getRequestURI().equals(loginURI);

        if (loggedIn || loginRequest) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(loginURI);
        }
    }

    // ...
}

The servlet should collect the submitted data, find the associated User in database and if found then store it as a session attribute and then redirect to the home page, else redisplay the form with validation errors.

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @EJB
    private UserService userService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Map<String, String> messages = new HashMap<String, String>();

        if (username == null || username.isEmpty()) {
            messages.put("username", "Please enter username");
        }

        if (password == null || password.isEmpty()) {
            messages.put("password", "Please enter password");
        }

        if (messages.isEmpty()) {
            User user = userService.find(username, password);

            if (user != null) {
                request.getSession().setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/home");
                return;
            } else {
                messages.put("login", "Unknown login, please try again");
            }  
        }

        request.setAttribute("messages", messages);
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }
}

SessionId is used to keep track of request coming from the same client during a time duration.

URL rewriting
URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies. If you need to track Session from JSP pages, then you can use tag for URL-rewriting. It automatically encodes session identifier in URL.

Cookies
A cookie is a small amount of information sent by a servlet to a Web browser. A cookie is saved by the browser and later sent back to the server in subsequent requests. A cookie has a name, a single value, expiration date and optional attributes. A cookie’s value can uniquely identify a client. Since a client can disable cookies, this is not the most secure and fool-proof way to manage the session. If Cookies are disabled then you can fallback to URL rewriting to encode Session id e.g. JSESSIOINID into the URL itself.

Hidden Form fields
Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

HTTPS and SSL
Web browsers that support Secure Socket Layer communication can use SSL’s support via HTTPS for generating a unique session key as part of the encrypted conversation. Modern days online internet banking website, ticket booking websites, e-commerce retailers like Amazon and e-bay all use HTTPS to security transfer data and manage the session.