Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Friday, September 4, 2026

Java: Prevent Browser Back After Logout

How to Prevent Browser Back After Logout

I found many problems and questions related to logout/signout. One common problem is that after logout, the browser's Back button allows the user to go back to a previously visited page.

Once a user logs out, they should not be able to access the previously logged-in page without logging in again.

To avoid this problem, we can prevent the browser from using cached copies of protected pages and check whether the user's session is still valid.

Steps

1. Invalidate the Session

When the user logs out, invalidate the session:

session.invalidate();

This removes the session and its associated attributes.

Note: If the application uses other session attributes that must remain available, do not invalidate the session without considering the application's session design. In a normal login/logout flow, however, invalidating the authenticated session is the preferred approach. 

2. Set Cache-Control Headers on Protected Pages

Set the following headers on pages that contain protected information:

// Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control", "no-cache");

// Prevents the response from being stored in the cache
response.setHeader("Cache-Control", "no-store");

// Causes the cached response to be considered expired
response.setDateHeader("Expires", 0);

// HTTP 1.0 backward compatibility
response.setHeader("Pragma", "no-cache");

You can also combine the Cache-Control directives:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");

3. Check the Session Before Showing the Page

Before displaying a protected page, check whether the user is logged in.

For example:

Object facultyList = session.getAttribute("facultyList");

if (facultyList == null) {
    response.sendRedirect("index.jsp");
    return;
}

// Continue with the normal page processing

This ensures that the application checks the user's session on the server before allowing access to the protected page.

Important Note

The browser's Back button cannot be disabled from a Java/JSP application.

The purpose of these steps is different: after logout, the application should no longer allow access to protected resources, and appropriate cache-control headers help prevent previously viewed protected content from being reused from the browser cache.

For larger applications, authentication checks are usually better handled centrally using a Servlet Filter or a security framework rather than repeating the session check in every JSP page.


Java: Sending Data from JSP to Servlet

Sending Data from Jsp to Servlet or Communication between Jsp & Servlet , we need certain things like
  • A JSP File
  •  Deployment Descriptor (web.xml)
  • A Servlet File (Normal Java File)

Jsp File (index.jsp)
<form action="test1" method="get">
    <label>Name:</label>
    <input type="text" name="txtname">
    <input type="submit" value="Submit">
</form>




Servlet File (test1.java)

Note: In this example, the form uses the GET method, so the Servlet handles the request in doGet(). If the form uses POST, the Servlet should generally handle it in doPost(). The service() method is responsible for dispatching HTTP requests to methods such as doGet() and doPost(), so application code normally overrides doGet() or doPost() rather than overriding service() directly.

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/test1")
public class Test1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");

        String name = request.getParameter("txtname");

        PrintWriter out = response.getWriter();
        out.println("<h2>Hi, I am " + name + "</h2>");
    }
}

Alternative: Using web.xml

Instead of using @WebServlet, the Servlet can be mapped using the web.xml deployment descriptor. This approach is common in older Java EE applications and is still supported.

<servlet> <servlet-name>test1</servlet-name> <servlet-class>Test1</servlet-class> </servlet> <servlet-mapping> <servlet-name>test1</servlet-name> <url-pattern>/test1</url-pattern> </servlet-mapping>

The url-pattern defines the URL path used to access the Servlet. In this example, the JSP form uses action="test1", which corresponds to the /test1 Servlet mapping.



Note: In web.xml url-pattern is the path for browser ,so any name can be used (not /test1). we need & tag for run & map a servlet to the path. But, Url-pattern must match with the form action .

Legacy Java EE note: If you are working with an older application running on Tomcat 9 or earlier, you may see imports such as javax.servlet.http.HttpServlet. Tomcat 10 and later use jakarta.servlet.http.HttpServlet, so applications may require migration when moving from Tomcat 9 to Tomcat 10+