This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Invoking a servlet from core java program is simple.
Posted by Jay on October 28, 2001 at 12:21 PM
All you have to do is to request a URL. Put all the name, value pairs as you would normally have, and open a stream on it. Heres the code:
import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class SpecialServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println ("Hello " + req.getParameter("name") + ", this is SpecialServlet!"); out.close(); } }
The java program:
import java.net.*; import java.io.*; public class CmdLineApplication { public static void main (String args[]) { String line; try { URL url = new URL( "http://127.0.0.1/servlet/special?name=CmdLineApplication" ); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); line = in.readLine(); System.out.println( line ); in.close(); } catch (Exception e) { e.printStackTrace(); } } }
Place the servlet .class file in the WEB-INF/classes dir of your servlet engine. Run the other class on command line the usual way: java CmdLineApplication You should see the string from the servlet.
Replies:
|