Calling a servlet from a java program

I could not find a forum for servlet hence am posting
here
I have a servlet that accepts prameters and
gives some out put .
I want to be able to call this servlet ( invoke )
from a Java Program .
How do i do that ..
Any sample code /pointer would be appreciated.
Deepa

hi
you can try this code.
URL url = new URL("http://localhost:8888/yourServlet?param1=value1");
URLConnection con = url.openConnection();
StringBuffer sBuf = new StringBuffer();
BufferedReader bReader = new BufferedReader(
new InputStreamReader(
con.getInputStream()));
String line = null;
while((line = bReader.readLine()) != null) {
sBuf.append(line);
System.out.println(sBuf);
hope this helps
Shrini

Similar Messages

  • Calling servlet from a java program

    Hi
    I need to call a servlet's doPost() method from a java program. I have a specific situation, where I need to call servlet from a java program. DUring this call I need to pass a file and two string to the servlet. Servelt after receiving the file and string uploads the file to the server at a specified location. I am stuck up as how to call servlet from a java program instead of a HTML or JSP.
    Can anyone help me to start with this.
    any suggestion is welcome.

    You have to establish a URLConnection with servlet from your java program.
    URL servletURL = new URL("http://localhost:8080/Myservlet?str1=abc&str2=def");
    URLConnection servletConnection = servletURL.openConnection();you can get the objectOutputStream
    ObjectOutputStream oos = new ObjectOutputStream (servletConnection.getOutputStream());
    oos.writeObject(your file object);-------------------------------------------------
    In the servlet u can get the strings using request.getParameter("str1");
    In the servlet u can get the strings using request.getParameter("str2");
    file = new ObjectInputStream (request.getInputStream()).readObject()a lot of resources are available on this ...
    hope this helps :)

  • Possibility of calling standard actions from a java program

    Hi ,
    I am working for a project where customer wants to have option of saving orders as draft only and later convert to order if need be. However since we do not want many drafts to reside on server there is a need to delete these at a specified time. For draft orders I am using order templates since they stay in the database without getting converted to orders. Now I do not know how to go about the deletion part.
    i need to write a program that would run on the server and which would fetch the templates (drafts) that have been created till a particular time and call the delete action of the template. Now the question is how do i call these actions from a java program where this java program will have to run on the server end (ie will be a backend process).
    Please suggest.
    Thanks
    Roopali

    hello roopali,
    you can create a separate thread that will run your
    code that will check for stale drafts and delete them.
    it is just like a session management program but here
    we will be looking over the drafts and not the session
    objects.
    now if you want the invocation of the action from another
    program, a socket program would suffice but opening ports
    will cause you network connections thru firewall.
    if you can make use of HTTP servlet as your service
    provider e.g., you can then just pass some action params
    to invoke it.
    regards
    jo

  • Calling a servlet from a Java Stored Procedure

    Hey,
    I'm trying to call a servlet from a Java Stored Procedure and I get an error.
    When I try to call the JSP-class from a main-method, everything works perfectly.
    Java Stored Procedure:
    public static void callServlet() {
    try {
    String servletURL = "http://127.0.0.1:7001/servletname";
    URL url = new URL(servletURL);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty("Pragma", "no-cache");
    conn.connect();
    ObjectInputStream ois = new ObjectInputStream(conn.getInputStream());
    Integer client = (Integer)ois.readObject();
    ois.close();
    System.out.println(client);
    conn.disconnect();
    } catch (Exception e) {
    e.printStackTrace();
    Servlet:
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    Integer id = new Integer(10);
    OutputStream os = response.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(id);
    oos.flush();
    oos.close();
    response.setStatus(0);
    Grant:
    call dbms_java.grant_permission( 'JAVA_USER', 'SYS:java.net.SocketPermission','localhost', 'resolve');
    call dbms_java.grant_permission( 'JAVA_USER','SYS:java.net.SocketPermission', '127.0.0.1:7001', 'connect,resolve');
    Package:
    CREATE OR REPLACE PACKAGE pck_jsp AS
    PROCEDURE callServlet();
    END pck_jsp;
    CREATE OR REPLACE PACKAGE BODY pck_jsp AS
    PROCEDURE callServlet()
    AS LANGUAGE JAVA
    NAME 'JSP.callServlet()';
    END pck_jsp;
    Architecture:
    AS: BEA WebLogic 8.1.2
    DB: Oracle 9i DB 2.0.4
    Exception:
    java.io.StreamCorruptedException: InputStream does not contain a serialized object
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java)
    The Servlet and the class work together perfectly, only when I make the call from
    within the database things go wrong.
    Can anybody help me.
    Thank in advance,
    Bart Laeremans
    ... Desperately seeking knowledge ...

    Look at HttpCallout.java in the following code sample
    http://www.oracle.com/technology/sample_code/tech/java/jsp/samples/jwcache/Readme.html
    Kuassi

  • Calling OCX Methods from a Java Program

    Hi All,
    Is it possible to call OCX methods from a Java program? If yes, can you please refer me to any documents or sample code to achieve this.
    All inputs are highly appreciated.
    Thanks
    Tarek

    JNI
    http://java.sun.com/docs/books/tutorial/native1.1/index.html

  • Calling another application from a java program

    Hi, Java ppl.
    I wanted to know how can I call another program say a help application or an exe from a java program. anyone with any advice or a piece of code would help.
    Thanks
    Pradeep

    I had the same situation and I tried the code that you sugested and it works. I was wondering, what am I expecting in the while loop that appears after the int inp; statement? Is some data going to be displayed on the screen? How essential is to have that while loop after the calling the exec() method?
    Sorry for the amount of questions, I never tried this before.
    Best regards,
    Luis E.

  • Calling jsp page from a java program

    Hello,
    Is it possible to call a JSP page from a java program? If so, please let me know how it is possible.
    I have a JSP page that inserts 10 records in a database based on the attribute given to the page. When the java program is executed all the 10 records need to be inserted.
    The JSP page is already running fine in Tomcat.
    Thanks and Regards,
    Prasanna.

    MVC has applied the standard of seperate your view , model and controller. I believe nobody will insert data from jsp page,better practice should be inserted from your database layer, normally is like DAO layer. so you should pass your data from jsp to your backend.
    hopefully it's help u

  • Calling an executable from a java program

    How can I call a compiled program from a java program. I have a fortran program, which I would like to call for execution from within my java program. My OS is linux.
    Thanks,
    An

    Not quite sure in the case of fortran program, but one thing can be done, call ur fortran program from a batch (.bat file) and call this .bat file from java ;
    try {
    Process p = Runtime.getRuntime().exec("run.bat");
    p.waitFor();
    catch( Exception e ) {
    }

  • Call ODI Scenario from a Java Program

    Hi,
    I would like to invoke the ODI Scenario from a Java Program. Is there any way i can do this?
    Please let me know if you have any posts related to this.
    Thanks,
    Mansur

    Check this ..
    How to run ODI scenario from java?

  • How choose between post and get when calling a servlet from a java class ??

    Hi !!
    I have an urgent question : in fact some java programs that call servlets are published on the web, and the principle is to make an url.openconnection() to reach the servlet.
    What I don't understand is how we choose if we want to call the get or the post method on the servlet ?????
    please answer very fast.....
    thanks...

    from the URL documentation of openConnection():
    "If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned."
    Obviously, in case of a http servlet, normally an instance of HttpURLConnection will be returned. If you don't change the request method, GET is the default.

  • Calling another class from a java program

    I tried to call the Server1.class from the password program, but I failed. The password program source code is as follows:
    class PasswordDialog extends java.awt.Dialog implements java.awt.event.ActionListener
         * Constructor. Create this visual dialog component.
         public PasswordDialog(java.awt.Frame parent, PasswordVerifier verifier)
              super(parent);
              addWindowListener(new WindowEventHandler());
              setLayout(new java.awt.FlowLayout());
              setSize(500, 100);
              this.verifier = verifier;
              add(useridField = new java.awt.TextField(10));
              add(passwordField = new java.awt.TextField(10));
              add(okButton = new java.awt.Button("Submit"));
              add(cancelButton = new java.awt.Button("Cancel"));
              okButton.addActionListener(this);
              cancelButton.addActionListener(this);
              passwordField.setEchoChar('*');
              useridField.requestFocus();
         public void actionPerformed(java.awt.event.ActionEvent e)
              if (e.getSource() == okButton)
                   // Invoke password verification callback
                   try
                        boolean result = verifier.verifyPassword(
                             useridField.getText(), passwordField.getText());
                        if (! result) return;     // verification failed; don't close this dialog
                   catch (Exception ex)
                        ex.printStackTrace();
                   // Close this dialog
                   System.out.println("I still can't call the Server1 class");
                   dispose();
              else if (e.getSource() == cancelButton)
                   dispose();
         class WindowEventHandler extends java.awt.event.WindowAdapter
              public void windowClosing(java.awt.event.WindowEvent e)
                   System.exit(0);
         // Private objects
         private PasswordVerifier verifier;
         private java.awt.TextField useridField;
         private java.awt.TextField passwordField;
         private java.awt.Button okButton;
         private java.awt.Button cancelButton;
    interface PasswordVerifier
         public boolean verifyPassword(String userid, String password) throws Exception;
    public class password implements PasswordVerifier
         * Main routine for testing only.
         public static void main(String[] args)
              password verifier = new password();
              java.awt.Frame f = new java.awt.Frame("Password Verifier");
              f.setSize(100, 100);
              f.show();
              PasswordDialog d = new PasswordDialog(f, verifier);
              d.show();
         public boolean verifyPassword(String userid, String password) throws Exception
              return (userid.equals("Albert") && password.equals("Einstein"));
    and the Server1.java is as follows:
    //Server Application
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    public class Server1 extends Frame implements ActionListener,Runnable,KeyListener
    ServerSocket s;
    Socket s1;
    BufferedReader br;
    BufferedWriter bw;
    TextField text;
    TextField name;
    Button exit,clear;
    Label label;
    List list;
    Panel p1=null;
    Panel p2=null;
    Panel sp21=null;
    Panel sp22=null;
    Panel jp=null;
    public void run()
              try{s1.setSoTimeout(1);}catch(Exception e){}
              while (true)
                   try{
    list.add(br.readLine());
                   }catch (Exception h){}
    if(list.getItemCount()==7)
    list.remove(0);
    public Server1(String m)
    {       super(m);
    jp=new Panel();
    p1=new Panel();
    p2=new Panel();
    sp21=new Panel();
    sp22=new Panel();
    jp.setLayout(new GridLayout(2,1));
    p1.setLayout(new GridLayout(1,1));
    p2.setLayout(new GridLayout(2,1));
    sp21.setLayout(new FlowLayout());
    sp22.setLayout(new FlowLayout());
    exit = new Button("Exit");
    clear = new Button("Clear");
    exit.addActionListener(this);
    clear.addActionListener(this);
    list = new List(50);
    text = new TextField(43);
    name = new TextField(10);
    label = new Label("Enter your name");
    name.addKeyListener(this);
    text.addKeyListener(this);
    p1.add(list);
    sp21.add(text);
    sp21.add(exit);
    sp22.add(label);
    sp22.add(name);
    sp22.add(clear);
    p2.add(sp21);
    p2.add(sp22);
    jp.add(p1);
    jp.add(p2);
    this.add(jp);
    setBackground(Color.orange);
    setSize(380,300);
    setLocation(0,0);
    setVisible(true);
    setResizable(false);
    name.requestFocus();
    try{
    s = new ServerSocket(786);
                   s1=s.accept();
                   br = new BufferedReader(new InputStreamReader(
                             s1.getInputStream()));
                   bw = new BufferedWriter(new OutputStreamWriter(
                             s1.getOutputStream()));
    bw.write("Welcome");bw.newLine();bw.flush();
                   Thread th;
                   th = new Thread(this);
                   th.start();
              }catch(Exception e){}
    public static void main(String args[])
    new Server1("Server");
         public void actionPerformed ( ActionEvent e)
    if (e.getSource().equals(exit))
                   System.exit(0);
    else if (e.getSource().equals(clear))
    { name.setText(" ");
    name.setEditable(true);
    public void keyPressed(KeyEvent ke) {
    if(text.equals(ke.getSource()))
    if(ke.getKeyCode()==KeyEvent.VK_ENTER)
    try{
    bw.write(name.getText()+">>"+text.getText());
                   bw.newLine();bw.flush();
                   }catch(Exception m){}
    list.add(name.getText()+">>"+text.getText());
    text.setText("");
    else if(name.equals(ke.getSource())) {
    if(ke.getKeyCode()==KeyEvent.VK_ENTER)
    name.setEditable(false);
    text.requestFocus();
    public void keyReleased(KeyEvent ke)
    //something
    public void keyTyped(KeyEvent ke)
    //something
    I tried to create a new object by typing:
    Server1 s = new Server1();
    then call the main function
    new Server1("Server");
    but it doesn't work. Anybody can help me with this?

    try
    Server1 s = new Server1();
    s.Server1("Server");
    or
    new Server1().Server1("Server");

  • How to send a file from a java program to a servlet and get a response

    Hi,
    How can I call a servlet from a standalone java program and send a file to a servlet using POST method and in return gets the status back from the servlet. Any help is appreciated any small sample will help.
    Thanks.

    Hi,
    I am trying the following sample I got from net and am getting the following error. Any help what I am doing wrongs:
    06/12/24 02:15:58 org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null
    06/12/24 02:15:58      at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:294)
    06/12/24 02:15:58      at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:268)
    06/12/24 02:15:58      at mypackage9.Servlet1.doPost(Servlet1.java:38)
    06/12/24 02:15:58      at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    06/12/24 02:15:58      at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    06/12/24 02:15:58      at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
    06/12/24 02:15:58      at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
    06/12/24 02:15:58      at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:663)
    06/12/24 02:15:58      at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:330)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:830)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:285)
    06/12/24 02:15:58      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:126)
    06/12/24 02:15:58      at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
    06/12/24 02:15:58      at java.lang.Thread.run(Thread.java:534)Here is the sample client code:
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.PostMethod;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    public class PostAFile {
        private static String url =
             "http://192.168.0.17:8988/Vulcan_Materials-ServletPost2-context-root/servlet/Servlet1";
        public static void main(String[] args) throws IOException {
            HttpClient client = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            client.setConnectionTimeout(8000);
            File f = new File("C:\\load.txt");
            System.out.println("File Length = " + f.length());
            postMethod.setRequestBody(new FileInputStream(f));
            int statusCode1 = client.executeMethod(postMethod);
            System.out.println("statusLine>>>" + postMethod.getStatusLine());
            postMethod.releaseConnection();
    }Here is the sample servlet code:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.PrintWriter;
    import java.io.IOException;
    import org.apache.commons.fileupload.DiskFileUpload;
    import org.apache.commons.fileupload.FileItem;
    import java.util.List;
    import java.util.Iterator;
    import java.io.File;
    public class Servlet1 extends HttpServlet
      private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
      public void init(ServletConfig config) throws ServletException
        super.init(config);
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        try
          response.setContentType(CONTENT_TYPE);
          PrintWriter out = response.getWriter();
          java.util.Enumeration e= request.getHeaderNames();
            while (e.hasMoreElements()) {
              String headerName=(String)e.nextElement();
              System.out.println(headerName +" = "+request.getHeader(headerName));
           //System.out.println("Content Type ="+request.getContentType());
            DiskFileUpload fu = new DiskFileUpload();
            // If file size exceeds, a FileUploadException will be thrown
            fu.setSizeMax(1000000);
            List fileItems = fu.parseRequest(request);
            Iterator itr = fileItems.iterator();
    System.out.println("***************************");
            while(itr.hasNext()) {
              FileItem fi = (FileItem)itr.next();
              //Check if not form field so as to only handle the file inputs
              //else condition handles the submit button input
              if(!fi.isFormField())
                System.out.println("\nNAME: "+fi.getName());
                System.out.println("SIZE: "+fi.getSize());
                //System.out.println(fi.getOutputStream().toString());
                File fNew= new File("C:\\", fi.getName());
                System.out.println(fNew.getAbsolutePath());
                fi.write(fNew);
              else
                System.out.println("Field ="+fi.getFieldName());
            out.println("SUCCESS123456: ");
          out.close();
        catch(Exception e)
          e.printStackTrace();
    }Any help on what is wrong.
    Thanks

  • Is it possible to call a method in a servlet from  a java script ?

    I need to do a dynamic html page . In the page i select some things and then these things must communicate whit a servlet because the servlet will do some DB querys and update the same webpage.
    So is it possible to actually call a method of a servlet from a java script? i want to do something that looks like this page:
    http://www.hebdo.net/v5/search/search.asp?rubno=4000&cregion=1011&sid=69DHOTQ30307151
    So when u select something in the first list the secodn list automaticly updates.
    thank you very much

    You can
    1. load all the options when loading the page and
    set second selection options when user selected
    the first; or
    2. reload the page when user select first selection
    by 'onChange' event; or
    3. using iframe so you only need to reload part of
    the page.

  • Calling a servlet from java

    How to call a servlet from java?
    your help is greatly appreciated..

    Welcome to the forum
    You seem to be misunderstanding something. Do some googling to learn what you need about servlets. Simplified, servlets are java code that's hosted by a web container, such as Tomcat. When a servlet gets called as a consequence of someone requesting a url from the container, it takes in a request object and a response object. All the magic is then in creating an appropriate response (e.g. html) for the incoming request.

  • Calling Servlet from a java prog?

    Hi all,
    I am calling servlet from a java prog (Java Agent in Lotus Notes) by using URL and URLConnection object. how can i trigger the Servlet By using doPost method .I have to send some parameter also.
    Thanx
    Muthu

    you need to open a connection to the servlet. Then you must call getInputStream() and getOutputStream() and use them in any way you see fit. I was trying this before and could not get POST to work unless I openned the input stream from the servlet. Strange... but doGet worked without openning the input stream???
    // open a connection....
    // write to the servlet
    servletConnection.getOutputStream().write("whatever");
    servletConnection.getOutputStream().flush();
    servletConnection.getOutputStream().close();
    // grab what the servlet sends back, required to do a post.
    byte [] in = new byte[100];
    servletConnection.getInputStream().read(in);
    servletConnection.getInputStream().close();

Maybe you are looking for

  • My bookmarks don't show even though the bookmark bond is turned on.

    The bookmarks haven't been deleted. I've tried turning the bookmark bond on and off. Unfortunately it didn't work.

  • How to use tv as a monitor with HDMI adapter

    with the HDMI adapter to thunderbolt plug the tv will display what is on my laptop monitor but only if I drag the screen to like 5 times its normal size. is there a way to just make it automaticly fit the tv everytime I want to use it as my monitor.

  • Questions concerning the Macintosh Operating System (very technical)

    I've recently learned all about how Windows based machines do various things such as memory management, processor management, disk scheduling algorithms, concurrent/parallel processing and performance evaluation/simulation. I'm interested in learning

  • Checking the file content in application server

    Hi, I am writing an XML file from the raw XSF data from a smartform auto generated function module through OPEN DATASET command in BINARY MODE. When I go to tcode AL11 to check the content of the XML file, I can see only the first few bytes of it as

  • NTP Server Configuration

    Dear All, I have setup NTP Server with basic steps provided by SUN. In my setup i would be using it for Solaris, WIndows and few OS and devices like Switches and Routers.. I am not sure what additional steps do i need to synch it with servers without