Java.Servlet.How can we prevent direct access to a JSP page from a browser?

Excellent and very practical question!
There are several ways to prevent users from directly accessing a JSP page from a browser.

Here’s a structured explanation:


🔥 1. Place JSPs under WEB-INF/ Folder

  • Files inside WEB-INF cannot be accessed directly via a URL.
  • Only servlets or controllers can forward a request to them internally.

📂 Folder structure:

/webapp
   ├── WEB-INF
   │     ├── jsp
   │          ├── secretPage.jsp
   └── index.jsp

If you put your secretPage.jsp inside /WEB-INF/jsp/, then:

  • URL like http://example.com/WEB-INF/jsp/secretPage.jsp → ❌ Access Denied (HTTP 404)
  • But from a Servlet:
request.getRequestDispatcher("/WEB-INF/jsp/secretPage.jsp").forward(request, response);

→ ✅ Allowed

Best and most common practice in real projects!

🔥 2. Use Servlet Authentication (Filter or Security Constraint)

  • Create a Filter that checks every request.
  • If someone tries to access a protected JSP without proper login/session, redirect them or block the access.

Example Filter:

@WebFilter("/secure/*")
public class AuthenticationFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(false);
        
        if (session == null || session.getAttribute("user") == null) {
            ((HttpServletResponse) response).sendRedirect("/login.jsp");
        } else {
            chain.doFilter(request, response); // User is logged in
        }
    }
}

Only authenticated users can access /secure/* JSPs.

🔥 3. Use <security-constraint> in web.xml

You can define URL patterns that require authentication.

Example:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Protected Pages</web-resource-name>
        <url-pattern>/secure/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>authenticatedUser</role-name>
    </auth-constraint>
</security-constraint>

This way the server will block direct access unless users are authenticated and have the correct role.

🔥 4. Programmatic Check Inside JSP (not recommended)

You could manually add Java code at the top of your JSP:

<%
    if (session.getAttribute("user") == null) {
        response.sendRedirect("login.jsp");
    }
%>

❗ But this is ugly, mixes Java with HTML, and harder to maintain.
Better to handle security in filters or servlets.

📢 In professional projects, the best way is:

Put JSPs inside WEB-INF/
Control access via servlets + filters.

That way, JSPs are treated only as view templates, not as web-accessible resources.

This entry was posted in Без рубрики. Bookmark the permalink.