how to prevent servlet from being invoked directly through browser

Viewed 2304

I was working on a web project using java servlet and jsp pages. In one of the servlet we have RequestDispatcher method and which is calling another servlet.

@WebServlet("/Demo")
public class DemoServlet extends HttpServlet {  

    public void doGet(HttpServletRequest req, HttpServletResponse res)  
            throws ServletException, IOException {  
        res.sendRedirect("testing"); //calling other servlet 
    }  
}  



    @WebServlet("/testing")
    public class TestingServlet extends HttpServlet {  

        public void doGet(HttpServletRequest req, HttpServletResponse res)  
                throws ServletException, IOException {  
                response.setContentType("text/html;charset=UTF-8");  
                PrintWriter out = response.getWriter();
                out.println("Hello World");

        }  
    }  

So, now I wanted to prevent contextRoot/testing from being invoked directly from the browser but instead only let it invoked from the other servlet(Demo)

Please suggest me if there is any way to do that.

3 Answers

Couple of techniques exist:

  • Look at writing a HTTP Request Filter. You can then inspect the incoming request and the url and reject it if the pattern matches the servlet paths that you do not want to be invoked directly.

  • Another mechanism is to use the security constraints in your web.xml to allow access to various paths in your application only to authorized users/roles. Look at <security-constraint> tag in web.xml

One approach is to check the caller's ip using ServletRequest.getRemoteAddr() and rejects it if it's not called locally

public void doGet(HttpServletRequest req, HttpServletResponse res)  
            throws ServletException, IOException {  
  if(!req.getRemoteAddr().equals("127.0.0.1")) { // reject }
}

However this method wouldn't work legitimate caller (eg: proxy) is also using the same ip.

Related