This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
How do we get Servlets or call them/their methods from another Servlet? I can't use <ServletContext>.getServlet() since it's deprecated (along with all related methods) and I refuse to use a deprecated method. Anyone know?
To be honest I don't know the answer. But am just curious why would you want to call any other method on servlet than get/post thro.' forward or include.
Joined: Jul 28, 2002
I just don't want to have to forward to a url every time I want to use a servlet that does processing. In asp there was a way that you could execute another asp page (like a servlet), passing it the request/response objects, but never leave the page you're on. That means you don't have to make a trip out to the browser. If I have a servlet that does some good stuff and can be hit either by URL or by just processing, I could do: //IN MY JSP PAGE getServlet( "DBServlet" ).doPost( ... ); //NEVER LEFT SO CAN FINISH //NO ERROR THROWN, EVERYTHING OK... out.println( blah, blah...); Also, I can have a DB servlet that has DB sepcific methods I can use as well as the doPost/get methods. I see tons of uses for this.
Originally posted by Robert Paris: If I have a servlet that does some good stuff and can be hit either by URL or by just processing, I could do: //IN MY JSP PAGE getServlet( "DBServlet" ).doPost( ... );
In that case, all you need to do is replace getServlet( "DBServlet" ).doPost( ... ); with request.getRequestDispatcher( "/DBServlet" ).include(request,response) ;. You can also specify any parameters to DBServlet via query string as request.getRequestDispatcher( "/DBServlet?param1=value1" ).include(request,response); However, note that you cannot explictily specify POST or GET methods to the included servlet in this way. The included servlet 'sees' the same method, POST or GET, that was sent to the original servlet. To send a POST request specifically, you can extend HttpSerlvetRequestWrapper, implement HttpSerlvetRequestWrapper.getMethod() and pass an instance of that subclass to the include() method. I am not sure about the exact details of what can go wrong if you change the method from GET to POST as I haven't come across such a requirement to try it out myself. -j
in addition, request.getRequestDispatcher(...).forward(request, response) is also handled on the server-side and would not require a trip to the browser. It is unlike that of the response.sendRediredt(...) method where a redirect message has to be sent to the browser that then executes it.