Can I call a CGI script from a servlet?
Created May 4, 2012
Shirish Bathe [The following example works if the script is located behind a web server (either remote, or running on the same machine). But if you're using a standalone Java web server, and want to run (e.g.) a Perl CGI, is there any way to use System.exec() to invoke the script with the correct parameters? -Alex]
Yes, you can call CGI Script from a servlet. You can write your servlet as if it is sending data from browser. (Either using POST/ GET Method)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); try{ // Put you URL/CGI here !!! URL url = new URL("http://localhost:8080/CgiRedir"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintStream outStream = new PrintStream(connection.getOutputStream()); //Sending parameter to URL/CGI outStream.println("dataname=" + URLEncoder.encode("Shirish")+"&datavalue=" + URLEncoder.encode("Bathe")); //outStream.println("dataname=Shirish&datavalue=Bathe"); outStream.flush(); outStream.close(); // reading from URL DataInputStream inStream; String inputLine; inStream = new DataInputStream(connection.getInputStream()); while (null != (inputLine = inStream.readLine())) { //System.out.println(inputLine); out.println(inputLine); } inStream.close(); } catch (MalformedURLException me) { System.err.println("MalformedURLException: " + me); } catch (IOException ioe) { System.err.println("IOException: " + ioe); }For detail please visit : http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html.
Hope this will solve your problem.