http://pdf.coreservlets.com/Session-Tracking.pdf
Please refer bove link. In that PDF you will get good example at the end of the book.
By default, session-tracking is based on cookies that are stored in the browser’s memory,
not written to disk. Thus, unless the servlet explicitly reads the incoming
JSESSIONID cookie, sets the maximum age and path, and sends it back out, quitting
the browser results in the session being broken: the client will not be able to access
the session again. The problem, however, is that the server does not know that the
browser was closed and thus the server has to maintain the session in memory until
the inactive interval has been exceeded.
// In Servlet
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) resp;
HttpServletRequest httpReq = (HttpServletRequest) req;
long currTime = System.currentTimeMillis();
long expiryTime = currTime + session.getMaxInactiveInterval() * 1000;
Cookie cookie = new Cookie("serverTime", "" + currTime);
cookie.setPath("/");
httpResp.addCookie(cookie);
if (httpReq.getRemoteUser() != null) {
cookie = new Cookie("sessionExpiry", "" + expiryTime);
} else {
cookie = new Cookie("sessionExpiry", "" + currTime);
}
cookie.setPath("/");
httpResponse.addCookie(cookie);
filterChain.doFilter(req, resp);
}