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.

Similar Messages

  • Calling external servlet from java stored procedure

    Hello,
    I need to call an external servlet which is in 9iAS server ( unix box) from Java Stored procedure in oracle database.
    Can anybody give me an idea? is it possible?
    Thanks,
    Viswa

    I am trying the same. Here is URL which will help u.
    http://otn.oracle.com/sample_code/tech/java/jsp/samples/wsclient/Readme.html
    Let me know when you run servlet successfully.
    Regards
    Satish

  • Problem while calling servlet from java bean

    I am trying to call a servlet from java bean in cep.
    My java bean:
    package com.bea.wlevs.example.algotrading;
    import com.bea.wlevs.ede.api.StreamSink;
    import com.bea.wlevs.example.algotrading.event.MarketEvent;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Unmarshaller;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.StringReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    public class MarketEventBean implements StreamSink {
         String s=null;
         public void onInsertEvent(Object event) {
              if (event instanceof MarketEvent) {
                   MarketEvent marketEvent = (MarketEvent) event;
                   try {
                        JAXBContext cxt = JAXBContext.newInstance(MarketEvent.class);
                        Unmarshaller unmarsh = cxt.createUnmarshaller();
                        StringReader strReader = new StringReader(marketEvent.getString_1());
                        MarketEvent obj = (MarketEvent) unmarsh.unmarshal(strReader);
                        s=obj.getSymbol();
                        System.out.println("data: " + s);
                   } catch(Exception e) {
                        e.printStackTrace();
                   try {
                        System.out.println("test1");
         URL url = new URL("http://172.18.21.94:7001/AppServletrecv-Model-context-root/ReceiveServlet");
         URLConnection conn = url.openConnection();
              System.out.println("test2");
         conn.setDoOutput(true);
              System.out.println("test3");
         BufferedWriter out =
         new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
         out.write("symbol="+s);
              System.out.println("test4");
         out.flush();
         System.out.println("test5");
         out.close();
         System.out.println("test6");
         BufferedReader in =
         new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
              System.out.println("test7");
         String response;
         while ( (response = in.readLine()) != null ) {
         System.out.println( response );
         in.close();
         catch ( MalformedURLException ex ) {
         // a real program would need to handle this exception
         catch ( IOException ex ) {
         // a real program would need to handle this exception
    My servlet code:
    package model;
    import javax.servlet.http.HttpServlet;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class ReceiveServlet extends HttpServlet {
    private final static String _SYMBOL = "symbol";
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
    * Get the value of form parameter
    // private final static String USERNAME = "username";
    String symbol = request.getParameter( _SYMBOL );
    * Set the content type(MIME Type) of the response.
    response.setContentType("text/html");
    * Write the HTML to the response
    try {
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title> A very simple servlet example</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Hello " + symbol +"</h1>");
    out.println("</body>");
    out.println("</html>");
    out.close();
    } catch (IOException e) {
    Web.xml:
    <?xml version = '1.0' encoding = 'windows-1252'?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
    <servlet>
    <servlet-name>ReceiveServlet</servlet-name>
    <servlet-class>model.ReceiveServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ReceiveServlet</servlet-name>
    <url-pattern>/ReceiveServlet</url-pattern>
    </servlet-mapping>
    </web-app>
    My servlet is running in weblogic server.
    But when I am running this program in weblogic server side there is no log.
    Edited by: 856272 on Jun 23, 2011 6:43 AM

    I would run both sides in a debugger and see what code is getting invoked

  • Calling servlet from java page flow

    Hi,
    I need to call servelt class from the <netui:anchor ..> tag of my jpf.
    i have mapped this servlet class in the web.xml.
    please tell us how to invoke servlet from the netui:anchor tag from the jpf action
    method.
    thanks
    shashi

    I am calling a Servlet from JAVA Class as I am using IDE: Eclipse. The Problem is below
    URL url = new URL(ServletPath);
    URLConnection connet = url.openConnection();Why should the Servlet running in different Runtime print on your Eclipse Runtime. Please be more clear about the question.

  • Calling Servlet from Java Class in eclipse

    Hi ,
    I am calling a Servlet from JAVA Class as I am using IDE: Eclipse. The Problem is below
    URL url = new URL(ServletPath);
    URLConnection connet = url.openConnection();
    I am using the above code in JAVA to Connect to Servlet I have given Print statement in Servlet such that whenever it calls it prints on Console but when I try to run the code the Statement is not printed in the Console of eclipse I think URL connection is not able to establish any connection ..... if any has solution for this please reply
    Thanks & Regards,
    Arvind

    I am calling a Servlet from JAVA Class as I am using IDE: Eclipse. The Problem is below
    URL url = new URL(ServletPath);
    URLConnection connet = url.openConnection();Why should the Servlet running in different Runtime print on your Eclipse Runtime. Please be more clear about the question.

  • 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 servlet from Java

    Hello!
    I need to send XML file to servlet from Java. I generate XML in general java class.
    Is there any way how to call servlet directly from Java without using a page with form? I need to send it by post method. I need some java alternative to Microsoft.XMLHTTP object.
    Thanks

    Try this part of the Networking tutorial:
    http://java.sun.com/docs/books/tutorial/networking/urls/index.html
    It might be the answer to your question.

  • 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 a servlet from a servlet?

    Is it possible to call one servlet from another servlet?

    You should use servlets to process requests. If what you're asking for is to execute a piece of logic within a servlet before its finished processing the request, then you should consider using a regular java class instead of a servlet. If you just want to send the request information to another servlet you can use getRequestDipatcher().forward(..) method. Keep in mind that by doing so you'll interupt the current servlet.
    Regards,
    D.

  • Calling a Servlet from a JSP within Portal Portlet

    We've created a JSP that calls a Servlet when the form is submitted. The servlet handles the request, does some basic processing and then forwards back to a JSP. This works fine outside of Portal.
    What needs to be done in order for this to work within a portlet in Portal? We can get to the first JSP which is in a portlet, but as soon as we click the submit button (which tries to call the servlet) we get the basic page not found error. We need to click the button, go to the servlet and have the servlet forward back to our portlet.
    I know this is not the ideal way of using Portal however...
    Any ideas?
    Thanks!
    -Teri Kemple
    [email protected]

    I was wondering is there any way I can call a servlet from jsp? There are two scenarios here
    1 - if the jsp is currently being executed/evaluated on the server, then you can use <jsp:include> to "call" a servlet, or <jsp:forward> to cancel the jsp and transfer the control to the servlet.
    2 - if the page is already loaded and running in the client, then the only way to call a servlet is making a HTTP request as from any other html page. Jave code does not execute on the client, so you have to use html/javascript at that point.
    Calling a servlet within another servlet.
    lets say one servlet maintains all dynamic html. I call this servlet from another servlet to create a dynamic page and then insert values into it.Close, but the standard pattern is the reverse of that. What normally happens is you retrieve the values to put in the page, and then call the page, passing in those values. Thats why often you get a servlet/actionbean getting called, which then forwards to a JSP to display the result. The servlet/bean loads all the values required into scope, and then the JSP presents the data.

  • Question? calling a servlet from EJB.

    Can anyone tell me how I would go about calling a servlet
    from a session bean that’s running in the same J2EE application.
    Application server is Oracle10g.
    Thanks.

    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.

  • How to call a servlet from another servlet

    hi everybody,
    i have a problem, i have to call one servlet from another one.
    Everything works on my pc, but when i install the application on the customer's server i got an error about an Uknown URL followed by the name of the machine.
    Wjat i do is the folloqing :
    String urlString = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"+servletName;
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    the variable servletName is the name of the servlet i have to call.
    Is there another way to call the servlet ?
    All the servlet are installed in the same server.
    Any suggestion ?
    Cheers.
    Stefano

    Sweep is correct about requestDispatcher being another approach for inter-servlet delegation; the only issue that i recall with this approach is that it defaults the method of the destination servlet to the one it was called from...for example, calling servlet2 from within servlet1.post() resulted in the dispatcher attempting to utilize servlet2.post() - i believe that i searched for a parameterize solution to no avail :( (ended up handling the request by placing a "fake" doPost() in servlet2 that simply called servlet2.doGet())
    however, if your application is functioning correctly on your pc/webserver then the problem may be external to servlet communication (e.g. client webserver's ports not configured or blocked, missing runtime classes, etc.)
    my suggestion would be to set aside the programmatic concerns for the moment - what is the response if you open a browser on a client's machine and access the URL in question (i.e. http://clientserver:port/stefanoServlet)? If it will not respond to access in this manner then it certainly won't when your application calls for it.
    It's possible that there is a coding error but, given the info supplied, i'd start examining the environment, first. Let us know if you have any luck with the test i recommended or not (please provide abundant detail). Or, if you've found the solution then you may want to post back with a quick blub so the next person knows how to escape the trap.
    D

  • How can i call a servlet from a servlet ?

    Hello,
    Can i call a Servlet from within a Servlet ?
    and is it "right thing" to Do ?
    Thanks

    JMO, but I wouldn't do it like this.
    Don't have a remote object like a servlet doing database queries for your app. That will mean TWO network hops for every query if the database resides on another machine. The network is the biggest bottleneck you've got.
    Write a JavaBean that does the database stuff for you and just have the first servlet instantiate it when it needs it. A Bean has a better chance of being reused, too. Write a TableGateway or DAO for your object.
    Or write an EJB to do it.
    The only time I've done a servlet-to-servlet connection like that was for one servlet running in a DMZ that would authenticate a user and then forward the request to another servlet running inside the second firewall.
    I wouldn't encapsulate database query logic in a servlet like that. JMO - MOD

  • Curious thing while calling a procedure from Java !...

    Hi !. My name is Agustin and my doubt would be the following one... I am working for a e-business comp and they asked me to call a procedure from java... The code is the following one:
    CallableStatement cs = null;
    System.out.println("Fecha Nro. 1: " + paramFechaDesde);
    System.out.println("Fecha Nro. 2: " + paramFechaHasta);
    try
    cs = getDBTransaction().createCallableStatement("{call paq_w_ListadoSiniestralidadART. p_sinsiniest(?,?,?,?) }",0);
    cs.registerOutParameter(4,OracleTypes.VARCHAR);
    cs.setInt(1,paramContrato.intValue());
    cs.setString(2,paramFechaDesde);
    cs.setString(3,paramFechaHasta);
    cs.setString(4,paramNombreArchivo);
    cs.executeQuery();
    String nomArchivo = cs.getString(4);
    System.out.println("### " + nomArchivo +" ###");
    catch(SQLException e)
    The weird thing is that, I was expecting a big big exception but the only thing I got is
    ### Error ###
    The String I am expecting is a file's name !; so I am a little bit confused...
    Also I didn't know where to post so If it's in the wrong category... I apologize !... If anyone need more details, I'll be checking out... The account I am working on is an Insurance company, who is the one who provide access to the DB and the procedures... So I can't check what's inside...

    Please provide your Java and OS versions, the JDBC jar file and the Oracle DB version being used when you post.
    >
    I was expecting a big big exception
    >
    Then why do you have an empty exception block? That just makes it disappear so you won't see one if it happens.
    And your code has
    cs.registerOutParameter(4,OracleTypes.VARCHAR);
    cs.setString(4,paramNombreArchivo);You use 'registerOutParameter' for an OUT parameter and the 'setXXX' methods for other parameters.
    Remove the 'setSTring' for the OUT parameter.
    Then as malcollmmc already said
    >
    Sounds like the PL/SQL is returning "Error" as the 4th parameter of the call
    >
    The actual value returned by PL/SQL is strictly determined by the PL/SQL code and Java and JDBC are not involved.
    Fix the code problems, retest, and folllowup with whoever wrote the code if it still returns ERROR.

  • Call .bat file from java code

    I need to call an application that uses a .bat file to execute from a java program. Is that possible?
    This is the .bat file:
    importcli.exe ciaf2735 C:\Importcli\files\SAI2735*.txt  
    importcli.exe ciaf2735 C:\Importcli\files\CI2735*.txt  
    importcli.exe ciaf2735 C:\Importcli\files\SC2735*.txt  
    importcli.exe db1800 C:\Importcli\files\*.mdb

    magaupe wrote:
    I need to call an application that uses a .bat file to execute from a java program. Is that possible?
    This is the .bat file:
    importcli.exe ciaf2735 C:\Importcli\files\SAI2735*.txt  
    importcli.exe ciaf2735 C:\Importcli\files\CI2735*.txt  
    importcli.exe ciaf2735 C:\Importcli\files\SC2735*.txt  
    importcli.exe db1800 C:\Importcli\files\*.mdb
    Hmmm, I wonder what would happen if there were a web search engine and you could research like this:
    [http://www.google.com/search?hl=en&q=call+.bat+file+from+java]

Maybe you are looking for

  • How to i share music or video from my computer to iphone without using itunes

    how to i share my music or video from my pc to my iphone and my itunes is not open in my pc

  • Legacy Trial Balance - best way to get totals into SAP

    Hi Folks, I have a query relating to the data migration of Finance items. What is the best process for updating the new SAP system with the legacy trial balance? Do you journal in the Opening Trial Balance posting sub ledger items to a Data Load acco

  • Safari slow to connect

    As a new iMac user, I have been using Safari frequently. However, ever since it was shut down due to vacation, and re-booted, whenever it goes into sleep mode I have difficulty getting Safari back. It will state: "you are not connected to the interne

  • Aperture 3 and focus points

    I uncovered something with Apple's Aperture 3 that I can't find documented anywhere: namely that using the "Show Focus Points" feature changes how it displays the information depending on the focusing mode the camera is in. At least with my Nikon D2H

  • ACTIVATION WINDOWS TO GO

    I am working with a small charity organization that requires the activation of 7 Windows To Go flash drives. However, the suggested KMS activation method has a minimum threshold of 20 which makes no sense for a small business or organization! I notic