jspservletsweb-inf

Servlet can't access .jsp file inside WEB-INF


So I am using annotation (not web.xml). My servlet looks like this (very simple, if the user types FooUser and FooLast in the form, it shows Welcome.jsp

Otherwise redirects to the same page Login.jsp.

@WebServlet("/ServletLogin")
public class ServletLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(request.getParameter("Username").equals("FooUser") && request.getParameter("Lastname").equals("FooLast")) {
            RequestDispatcher rd=request.getRequestDispatcher("/WEB-INF/Welcome.jsp");
            rd.forward(request,response);
        }
        else {
            RequestDispatcher rd=request.getRequestDispatcher("Login.jsp");  
            rd.forward(request,response);
        }
    }
}

And my Login.jsp looks like this

<!DOCTYPE html>
<html lang="en">
<body class="login">
    <div>
        <form action="ServletLogin" method="post">
            <h1>Login Form</h1>
            <div>
                <input type="text" class="form-control" placeholder="Username"
                    name="Username" required="" />
            </div>
            <div>
                <input type="password" class="form-control" placeholder="Password"
                    name="Password" required="" />
            </div>
            <div>
                <input class="btn btn-info" type="submit" value="Log in" />
            </div>
        </form>
    </div>
    </div>
    </div>
</body>
</html>

Solution

  • Remove the beginning forward slash:

     RequestDispatcher rd=request.getRequestDispatcher("WEB-INF/Welcome.jsp");
    

    or try this:

    RequestDispatcher rd=request.getRequestDispatcher("../WEB-INF/Welcome.jsp");
    

    or try get context first:

    RequestDispatcher rd=getServletContext().getRequestDispatcher( "WEB-INF/Welcome.jsp" );