Calling a servlet thru'  a Java class

Hi,
How can I write a Java class that calls/invokes a servlet?
Thnks

I blv you can do some thing like this to invoke a servlet
URL test = new URL(myURL);
where myURL should contain the complete URL of your servlet
test.openStream();
check more docs on the URL class

Similar Messages

  • 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 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

  • Call a local program in Java class on Win

    Hi
    I'm now working on a Java project. It is needed to call a local program in Java class.
    Following is the local program's source code:
    #include <stdio.h>
    main()
        char s[100];
        printf("Please input\n");
        scanf("%s", s);
        printf("Output: %s\n", s);
    } I build this simlpe C program to a exe file named TEST.EXE
    Then, I called the exe in my java class which was like following:
    final Process p = Runtime.getRuntime().exec("test.exe > a.txt");
    writer = new PrintWriter(p.getOutputStream());
    writer.println("12345\n");
    writer.close();
    p.waitFor();But after I ran the Java, it seemed not what I hope to get in a.txt. the string "12345" had not been read by the program, and not been writen to a.txt.
    Following is what appeard in a.txt:
    Please input!
    Output: Is there any error in my Java code?
    thanks!
    Edited by: JingZ on Aug 20, 2008 9:05 AM

    All above is my testing.
    In fact, my project is to encrypt/decrypt by Gnu PG.
    I need to execute a gpg command like following
    gpg -r Luna --encrypt test.txt
    I could execute this command line in CMD normaly:
    C:\WP_ECL~1.4\TESTCE~1>gpg -r 8104EFB8 --encrypt test.txt
    gpg: 997D0744: There is no assurance this key belongs to the named user
    pub  4096g/997D0744 2002-07-31 Baker &Taylor Inc. <[email protected]>
    Primary key fingerprint: BBBC F196 C1D5 CF26 170F  D1FB 870A 3F60 8104 EFB8
          Subkey fingerprint: C161 4C33 F15C 5347 FD09  C2BE 8CC6 2302 997D 0744
    It is NOT certain that the key belongs to the person named
    in the user ID.  If you *really* know what you are doing,
    you may answer the next question with yes.
    Use this key anyway? (y/N) y
    C:\WP_ECL~1.4\TESTCE~1>Please pay attention to the line which I have to type a 'y' to confirm.
    This make me have to invoke this command in Java class like following(in my understanding):
    final Process p = Runtime.getRuntime().exec("cmd /C gpg -r Luna --encrypt test.txt");
    writer = new PrintWriter(p.getOutputStream());
    writer.println("y");
    writer.close();
    p.waitFor();But while the java code was being run, it would be blocked, waiting, waiting and waiting.
    But this method was succeed in my test which invoked test.exe above.
    I cannot understand what difference exists between my test.exe and gpg.
    thanks.

  • Calling Servlet from a java class

    Hi,
    I don�t know what I�m doing wrong...
    I try to call a servlet located in a tomcat webserver, from a class, and capture its output. I use an URLConnection object... Everything is all right when I want to get an html page, but, it reports an IOException (FileNotFoundException) when the requested resource is a servlet.
    This servlet is working correctly.
    Can�t I use an URLConnection to access servlets?
    Cheers

    try setting up the user agent property of HTTP protocol to a browsers,its worth a shot.
    Cheers
    Khalid

  • Calling a servlet method from another class

    hi...
    if i make a servlet (that keeps the log for website users' logins and logouts, for example) and i want a method that adds an entry into a logfile, for example:
    public void log(String line) {
    //put "line" into some log file...
    and then i set this servlet to loadonstartup, how can i call the log() function from other classes or servlets? can i do it without making the servlet an entry in servletContext?
    im sorry if i'm not being very clear, the caffeine's getting to me...
    thanks
    lazlo

    I don't know, why would you do that anyway? Just make an ordinary class, not a servlet, and make "log" a static method in that class. (If you need initialization, use a static initializer.) Put that class where the real servlet can see it and call it from there.

  • Calling OAM WLST Commands from java class

    Hi all,
    is there any idea how to call OAM related WLST commands from java class ?.
    what are the required jar files ?
    thanks

    Hi,
    As per my understanding in OAM you will have only two major .py file startscript.py and stopscript.py file which will start nodemanger connect and start Admin and managed server similarly in stop it will stop managed server Admin server and then last nodemanager.
    these all done through wlst command using nmConnect(), nmStart (), nmKill() and shutdown etc.
    What exactly you are looking to get from java code.
    Regards,
    kal

  • Calling Same C program from Java Classes

    Hi!
    Can anyone let me know how to call the same C program using JNI from multiple Java Classes/programs?.
    Cheers
    Sai

    JNI creates a shared library.
    Any application that needs to can use the shared library at the same time.
    Ideally you use the same interface that you created for one application via JNI in the other applications.

  • 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

  • How to destroy a populated field (thru a java class) in a jsp

    i m workin on jfp frmwrk....i m stuck somewhr....actualy wat my jsp is doin dat
    it simply showin a error msg..wen a customer makes an error while inputtin data in a form,
    but wen he makes som othr error...d same error msg is shown on d jsp....but i hv alreday defined a
    diffrnt msg fr dat error.

    Start writing normal human readable English sentences, then we'll look what we can do for you.

  • Calling a servlet in java class

    Hello,
    I try to call a servlet from java class
    but is dose not work
    what should be the problem
       public void callServlet()
              try
                            // xxservlet is the servlet name
                   URL url = new URL("http://www.mydomain.com/xxservlet");
                   URLConnection hpCon = url.openConnection();
                   hpCon.setDoOutput(true);
                   OutputStreamWriter out = new OutputStreamWriter(hpCon.getOutputStream());
                   out.write("This Is a Test");
                   out.flush();
                   out.close();
              }catch(Exception ex){ex.printStackTrace();}     
    // My Servlet  is in package servlets
    public class XXServlet extends HttpServlet
        public void service(HttpServletRequest req, HttpServletResponse resp) {
            try {
                 ServletInputStream sin = req.getInputStream();
                 int len = req.getContentLength();
                    byte[] input = new byte[len];
                    ServletInputStream sin = req.getInputStream();
                   int c, count = 0 ;
                   while ((c = sin.read(input, count, input.length-count)) != -1) {
                       count +=c;
                  sin.close();
                  String inString = new String(input);
                  System.out.println("Servlet is running ...."+inString);
            } catch (IOException e) {
                try{
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    resp.getWriter().print(e.getMessage());
                    resp.getWriter().close();
                } catch (IOException ioe) {
    // web.xml
    <servlet>
           <servlet-name>xxservlet</servlet-name>
           <servlet-class>servlets.XXServlet</servlet-class>
        </servlet>
       <servlet-mapping>
        <servlet-name>xxservlet</servlet-name>
        <url-pattern>/xxservlet</url-pattern>
      </servlet-mapping>
    }regards
    Edited by: the_Orient on Mar 30, 2009 3:16 AM

    I have start servlet from brwoser only to test that servlet works fine
    A gain what I need
    I want to call a servlet from a javs class
    URL url = new URL("http://www.mydomain.com/myservlet");
      URLConnection hpCon = url.openConnection();
      hpCon.setDoOutput(true);
      OutputStreamWriter out = new OutputStreamWriter(hpCon.getOutputStream());
      out.write("Hello Woprld");
      out.flush();
      out.close();// Servlet
    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
            try {
                  String xp =req.getSession().getServletContext().getRealPath("/");
                  File f = new File(xp+"/students/info.txt");
                  f.createNewFile();
            } catch (IOException e) {
                try{
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    resp.getWriter().print(e.getMessage());
                    resp.getWriter().close();
                } catch (IOException ioe) {
    problem file can not be created
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
    }I hope that is clear

  • Calling another java class from a servlet

    I am trying to write a web based form handling system (for a college project)
    I have a servlet that responds to a user request for a form. I have another java program (HTMOut) that parses the xml file for the form and produces HTML output. When I call the HTMOut from the servlet it crashes the webserver (Tomcat). But if I call HTMOut from an ordinary java class it runs fine. If I call another test program from my servlet that works too.
    Any ideas?

    where does your HTMOut output? A file or a stream? I think it is better that HTMOut can output to a stream you can set externally.

  • Call java class by using servlet

    i written simple servlet with doGet(0. I need call java class when i run servlet
    my requirement is when i start the server i will call servlet it will redirect to another page.
    but before that servlet will run java class. which i have written externally.
    i need to run java class by using servlet then it will redirect to another page.
    could you give the proper solution

    You don't call classes - you call methods.
    There's nothing special about servlets except the requirement that they implement HttpServlet. Servlets and other classes they interact with all get compiled into WEB-INF/classes on the server.
    To forward a request to, say, "other.jsp" you do:
    getServletContext().getRequestDispatcher("/other.jsp").forward(request,response);

  • Java calling a servlet...

    Hi,
    Is there a way to call a servlet from a Java standalone class (of course I want to pass to the servlet parameters and to retrieve results from the servlet) ?
    Thanks a lot.
    Regards.

    Hi Guru,
    Thanks for the reply.
    In my serlvet I wrote:
    response.getWriter().write("in the doGet method");
    In my Java class, I wrote the following :
                   URL url = new URL("http://server:port//Servlet1/theservlet");
                   BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                   String inputLine;
                   while ((inputLine = in.readLine()) != null)
                        System.out.println(inputLine);
                   in.close();
    I do get the String "in the doGet method".
    But what if I wanted to send Objects ?
    Is there a way ?
    I cannot user session of course....
    Any idea will be welcome.
    Thanks in advance.

  • How to call a servlet  by  java standalone application

    //program related to calling a servlet by java standalone application and printing the response on console
    import java.io.*;
    import java.util.*;
    import java.lang.Object;
    import java.net.*;
    public class Program
         public static void main(String s[])
         System.out.println("Hello this programm defines about how to call a servlet with a java application ");
         try{
              URL servlet = new URL("http://localhost:8080/anchor/studentform.html");
              URLConnection conn=servlet.openConnection();
              conn.setDoOutput(true);
              InputStreamReader isr=new InputStreamReader(conn.getInputStream());
              BufferedReader br = new BufferedReader(isr);
              String str =br.readLine();
              System.out.println("Source code is" +str);          
         catch(IOException e)
         System.out.println("exception is" +e);
    i am able to read only one line of the form, please help me out to read the whole form (file)

    You are only reading one line? Why aren't you reading the data in a loop? E.g. a while loop. (Keep reading till readLine returns null)
    Kaj

Maybe you are looking for

  • PR/PO release process

    Need help SAP gurus!!! =) Our company has many approvers, so I maintained the appropriate release codes and strategies for the PR/PO release process. Now, they will have to release it using ME55. In the transaction, you will input the appropriate rel

  • UNDO Tables Space File deleted accidently

    Dear All, I performed following actions on my Oracle 11g Database under Windows 32-bits OS. CREATE UNDO TABLESPACE UNDOTBS2 DATAFILE 'C:\app\oradata\ABCD\undotbs2.dbf' SIZE 10 M AUTOEXTEND OFF ; ALTER SYSTEM SET undo_tablespace = UNDOTBS2; shutdown i

  • Different Versions of CR DLL ??

    Hello, in a viewer project with: Visual Studio 2008 (9.0.21022.8 RTM) Crystal Reports 2008 SP3 + FixPack 3.1 (CR Developer 12.3.1.684) For example: in Visual Studio Name: CrystalDecisions.CrystalReports.Engine Typ: .NET Version: 12.0.2000.0 Local cop

  • Purchase Order item - plant not available

    Hi, when I'm creating a purchase order the plant (Field name NAME1, Data element MEPO_EWERK) I want to select on the item level is not available. I get a list of plants, but the one I'm looking for is not displayed. I guess I have missed some basic c

  • Field Selection in Service Entry Sheet

    I want to restrict the user to make any changes in the WBS element field while creating the Service entry sheet for a service PO. Can someone guide me on the same. Regards, Ashish