Servlet Calls another Servlet, Returns an Object

Is it possible to call another servlet (which is loaded through
          Load-on-startup) from another servlet. The return should be an Object.
          I know I am kind of asking for a procedural way of programming.
          Example : Servlet "IamReady" is loaded and gets a request with binary
          data. It replies with a Binary Object.
          Servlet "serviceCall" calls IamReady to get the resoponse.
          I know that there are forward (using requestDispatcher) and "include"
          directives to have another servlet service calling servlet.
          Also, if I define a method in the (generic servlet) does each call to
          methos is executed in different thread (like doPost and doGet).
          Thanks.
          Chris
          

"Michael Reiche" <[email protected]> wrote in message news:<[email protected]>...
          Thank you Michael,
          > It is possible to call a servlet from a servlet.
          >
          > You can 'return' an object by putting it in the httpRequest.
          You mean httpResponse.
          >
          > The call is NOT executed in a separate thread.
          >
          > From this post (and the other post about a connection pool) - I wonder if
          > you really need to be using servlets. I couldn't think of a good reason why
          > the connection pool needs to be a servlet.
          Are you suggesting I should just have a class. Reason I have it as
          servlet, b'caz I do a load-on-startup and do initialiazation etc. in
          the init method. May be if you suggest how I can do it otherwise, I
          would like to implement it that way.
          Thanks again.
          >
          > Mike
          >
          > "MOL" <[email protected]> wrote in message
          > news:[email protected]...
          > > Is it possible to call another servlet (which is loaded through
          > > Load-on-startup) from another servlet. The return should be an Object.
          > > I know I am kind of asking for a procedural way of programming.
          > >
          > > Example : Servlet "IamReady" is loaded and gets a request with binary
          > > data. It replies with a Binary Object.
          > >
          > > Servlet "serviceCall" calls IamReady to get the resoponse.
          > >
          > > I know that there are forward (using requestDispatcher) and "include"
          > > directives to have another servlet service calling servlet.
          > >
          > > Also, if I define a method in the (generic servlet) does each call to
          > > methos is executed in different thread (like doPost and doGet).
          > >
          > > Thanks.
          > >
          > > Chris
          

Similar Messages

  • Servlets calls another servlet

    servlets calls another servlet ...how to do it ? whats the efficient way ?
    class myservlet extends HttpServlet
    // i want to call a servlet situated at another machine in the LAN whose, IP // 123.123.45.66 (say)
    the servlet which is situated in another machine
    remoteservlet extends HttpServlet
    doPost(...)
    how do i call ?
    few of the way i found by searching the forum.
    but i would like to know the good way in my situation.

    res.sendRedirect("LoginServlet?="+req.getRequestURI())
    i tested this. it does not work.
    my servlet wants to call another servlet which is
    active on IP xxx.ddd.ffff.zzz in the LAN .
    whats the way ?
    res.sendRedirect("http://xxx.ddd.ffff.zzz:<portnumber>/<context_name>/<servlet_regd_name">);The request and response objects are generated anew for that Servlet. There's no two ways about it, IMO.
    cheers,
    ram.

  • Servlet calling another servlet in diff J2EE app

    Hi.
    Can a servlet load another servlet in different J2EE application ?
    If so, could you show me how ?
    Code example would be much appreicated.
    Thanks.

    Call the other servlet's absolute url thro' urlconnection.
    URL url=new URL("http://server:port/servlet/otherservlet");
    InputStream in=url.openConnection();
    Other servlet will be loaded. Read response if you want to.

  • Servlet calling another servlet

    hi,
    I am writing a web-application which requires one servlet (on main server) to call another servlet (on a remote server).
    The main servlet needs to call the remote one and send some parameters to it.
    The remote servlet would be sending back XML data which is to be used by the central servlet. I tried using XML-RPC but it does'nt seem to support sending in NATIVE XML data.
    I also tried by creating URL, but did not find a way to add parameters to it !!!
    Could anyone please tell me how to call another servlet (along with sending POST/GET parameters) and get the results back into the calling servlet ?
    Any suggestions would be greatly appreciated.
    Thanks !
    Ajoy

    one possible solution would be to create an own socket connection (this would be a like a Post request) and than exchange data as you like.

  • A servlet calling another servlet on diff machine

    plzzzz help me on how i will call a servlet which is running
    on different machine from one machine. and how i will call a servlet
    which is running in different context on the same machine

    To call a servlet on a different machine you can use the HttpURLConnection class. Search the forum for details on how to do this.
    Or you can use the JSTL c:include tag. (or is it c:import?)
    To call a servlet on the same machine in a different context you use
    getServletContext().getServletContext(url)
    where url is the url to the servlet in the other context. Then you can use the RequestDispatcher to forward the request to the other servlet.

  • How can Servlet includel another servlet?

    I want to have a servlet calling another servlet in the middle of code... how to do that ?
    eg
    Servlet 1 print
    line1..
    line2...
    <-- here include Servlet2 to print line 3 and line 4 -->
    then servlet 1 continue to print
    line 5
    line6

    request.getRequestDispatcher("/servlet/MyServlet").include(request, response);

  • I want to send a response from the servlet and then call another servlet.

    Hi,
    I want to send a response from the servlet and then call another servlet. can this happen. Here is my scenario.
    1. Capture all the information from a form including an Email address and submit it to a servlet.
    2. Now send a message to the browser that the request will be processed and mailed.
    3. Now execute the request and give a mail to the mentioned Email.
    Can this be done in any way even by calling another servlet from within a servlet or any other way.
    Can any one Please help me out.
    Thanks,
    Ramesh

    Maybe that will help you (This is registration sample):
    1.You have Registration.html;
    2.You have Registration servlet;
    3.You have CheckUser servlet;
    4.And last you have Dispatcher between all.
    See the code:
    Registration.html
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <HTML>
      <HEAD>
        <TITLE>Hello registration</TITLE>
      </HEAD>
      <BODY>
      <H1>Entry</H1>
    <FORM ACTION="helloservlet" METHOD="POST">
    <LEFT>
    User: <INPUT TYPE="TEXT" NAME="login" SIZE=10><BR>
    Password: <INPUT TYPE="PASSWORD" NAME="password" SIZE=10><BR>
    <P>
    <TABLE CELLSPACING=1>
    <TR>
    <TH><SMALL>
    <INPUT TYPE="SUBMIT" NAME="logon" VALUE="Entry">
    </SMALL>
    <TH><SMALL>
    <INPUT TYPE="SUBMIT" NAME="registration" VALUE="Registration">
    </SMALL>
    </TABLE>
    </LEFT>
    </FORM>
    <BR>
      </BODY>
    </HTML>
    Dispatcher.java
    package mybeans;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Dispatcher extends HttpServlet {
        protected void forward(String address, HttpServletRequest request,
                               HttpServletResponse response)
                               throws ServletException, IOException {
                                   RequestDispatcher dispatcher = getServletContext().
                                   getRequestDispatcher(address);
                                   dispatcher.forward(request, response);
    Registration.java
    package mybeans;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Registration extends Dispatcher {
        public String getServletInfo() {
            return "Registration servlet";
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext ctx = getServletContext();
            if(request.getParameter("logon") != null) {          
                this.forward("/CheckUser", request, response);
            else if (request.getParameter("registration") != null)  {         
                this.forward("/registration.html", request, response);
    CheckUser.java
    package mybeans;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class CheckUser extends Dispatcher {
        Connection conn;
        Statement stat;
        ResultSet rs;
          String cur_UserName;
        public static String cur_UserSurname;;
        String cur_UserOtchestvo;
        public String getServletInfo() {
            return "Registration servlet";
        public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            try{
                ServletContext ctx = getServletContext();
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:oci:@eugenz","SYSTEM", "manager");
                stat = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
               String queryDB = "SELECT ID, Login, Password FROM TLogon WHERE Login = ? AND Password = ?";
                PreparedStatement ps = conn.prepareStatement(queryDB); 
               User user = new User();
            user.setLogin(request.getParameter("login"));
            String cur_Login = user.getLogin();
            ps.setString(1, cur_Login);
            user.setPassword(request.getParameter("password"));
            String cur_Password = user.getPassword();
            ps.setString(2, cur_Password);
         Password = admin");
            rs = ps.executeQuery();
                 String sn = "Zatoka";
            String n = "Eugen";
            String queryPeople = "SELECT ID, Surname FROM People WHERE ID = ?";
           PreparedStatement psPeople = conn.prepareStatement(queryPeople);
                      if(rs.next()) {
                int logonID = rs.getInt("ID");
                psPeople.setInt(1, logonID);
                rs = psPeople.executeQuery();
                rs.next();
                       user.setSurname(rs.getString("Surname"));
              FROM TLogon, People WHERE TLogon.ID = People.ID";
                       ctx.setAttribute("user", user);
                this.forward("/successLogin.jsp", request, response);
            this.forward("/registration.html", request, response);
            catch(Exception exception) {
    }CheckUser.java maybe incorrect, but it's not serious, because see the principe (conception).
    Main is Dispatcher.java. This class is dispatcher between all servlets.

  • Calling another servlet from a servlet

    I'm working on a servlet and would like to know how to
    call another servlet, by clicking on a form button
    or a hyperlink that was generated from the first servlet,
    is it only possible if the second servlet is called
    in an shtml page? Can you please give me an example
    of how to do this not using shtml pages?
    (I'm working with JDeveloper 2.0)
    When will the book be out for JDeveloper 2.0?
    We're also having problems deploying the servlet
    to the Java Web Server (1.1.3)
    It seems to have a problem connecting to the database.
    We get the first page of the servlet but the
    second page is generated from the doPost()
    and connects to the database using oracle JDBC thin
    gives a http 500 internal server error ,
    and we followed the instructions from JDeveloper
    can the problem be caused from the connection string that
    I used in the servlet:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    DriverManager.registerDriver(
    new oracle.jdbc.driver.OracleDriver());
    con = DriverManager.getConnection(
    "jdbc:oracle:thin:@(description=(address=
    (host=10.10.10.53)(protocol=tcp)(port=1521))
    (connect_data=(sid=OR8A)))",
    "im_dev","im_dev");
    or the configuration of the web server?
    (web server: Solaris 2.7 running on Intel)
    null

    Hi
    The sample acme video demo in JDeveloper does something similar.
    It has main Servlet "WebAppServlet.java" which overides the
    doPost and doGet methods and this methods calls someother java
    classes do perform some specific business logic which return a
    html page in a String format to "WebAppServlet.java".
    Open the samples directory in JDEveloper 2.0 with WebApp_81.jws
    to look at the source code.
    Steps to run the sample are included in the help system.
    regards
    argyro (guest) wrote:
    : I'm working on a servlet and would like to know how to
    : call another servlet, by clicking on a form button
    : or a hyperlink that was generated from the first servlet,
    : is it only possible if the second servlet is called
    : in an shtml page? Can you please give me an example
    : of how to do this not using shtml pages?
    : (I'm working with JDeveloper 2.0)
    : When will the book be out for JDeveloper 2.0?
    : We're also having problems deploying the servlet
    : to the Java Web Server (1.1.3)
    : It seems to have a problem connecting to the database.
    : We get the first page of the servlet but the
    : second page is generated from the doPost()
    : and connects to the database using oracle JDBC thin
    : gives a http 500 internal server error ,
    : and we followed the instructions from JDeveloper
    : can the problem be caused from the connection string that
    : I used in the servlet:
    : Class.forName("oracle.jdbc.driver.OracleDriver");
    : DriverManager.registerDriver(
    : new oracle.jdbc.driver.OracleDriver());
    : con = DriverManager.getConnection(
    : "jdbc:oracle:thin:@(description=(address=
    : (host=10.10.10.53)(protocol=tcp)(port=1521))
    : (connect_data=(sid=OR8A)))",
    : "im_dev","im_dev");
    : or the configuration of the web server?
    : (web server: Solaris 2.7 running on Intel)
    null

  • Calling a servlet from another servlet?

    Hi
    I would like to know that how can I call one Servlet from another Servlet. I have tried getServlet() method of ServletContext but it has been deprecated. I want to call a specific method of the other Servlet, is there any other way?
    Thanks

    I should have seen it from your previous post :(
    Code of Servlet 1:
    public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws
    ServletException, IOException
    RequestDispatcher rDispatch = null ;
    rDispatch = getServletConfig
    ().getServletContext().getRequestDispatcher
    ("/Servlet2") ;
    rDispatch.forward(request, response) ;
    System.out.println("Back in 1");
    I assume Servlets 1and 2 are in same web app and you've mapped your servlet2 to /Servlet2 in your web.xml
    make it as
    rDispatch = request.getRequestDispatcher("/Servlet2");
    rDispatch.forward(request,response);
    Nothin's wrong with yer servlet2

  • How to calling another servlet in a servlet

    In my servlet named TransferServlet I want call another servlet named PublisherServlet. So I wrote codes :
    objURL = new URL("http://localhost:8080/servlet/PublisherServlet") ;
    hucConnection = (HttpURLConnection)objURL.openConnection() ;
    hucConnection.setDoOutput(true) ;
    hucConnection.setUseCaches(false) ;
    hucConnection.setRequestMethod("POST") ;
    hucConnection.connect() ;
    but i can't invoke PublisherServlet. Why ? pls help
    Thanks a lot

    you do not need hucConnection.connect(); hucConnection = (HttpURLConnection)objURL.openConnection() does this.
    You need to use hucConnection.getOutputStream() and write to the stream to post and if you wanted a response you would need to read from hucConnection.getInputStream()

  • Passing parameter value via href in a servlet to another servlet

    Hi
    I have this issue with passing a value from one servlet to another servlet. the situation is is this.
    i have a servlet tstret.java which say..pulls out all the employee_id(s) from a table and displays it as hyperlinks( using the anchor tag.).
    now when i click on the hyperlink say T001 , The control is passed to another servlet which pulls out all the info about employee id T001.
    the problem i have is in the tstret.java servlet. i am passing the employee_id as a parameter in the href path itself as shown below.
    out.println("<td ><a href=\"http://localhost:7000/servlets-examples/accept_requisition.html?id="+[u]rs.getString(1)[/u]+"\" ><em>"+rs.getString(1)+"</em></a></td>");now if you see the code i am trying to pass the employee_id by attaching it to a variable id and passing it with the url, it gives me a sql exception saying no data found .
    if i pass a string say "rajiv" which i defined at the begining of code then i am able to pass it to the next servlet/html.
    the full code is as follows
    file : tstret.java
    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class tstret extends HttpServlet
         PrintWriter out;
         String[] employee_identity;
         public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
              try
              response.setContentType("text/html");
              out = response.getWriter();
              String session_name="SHOBA";//request.getParameter("session_name");
              out.println("<html><head><title> My Jobs </title></head>");
              out.println("<body bgColor=#ececec leftMargin=10>");
              out.println("<table align=center>");
              out.println("<tr align=center><td><img src=\"http://localhost:7000/servlets-examples/images/topbar.gif\"></td></tr>");
              out.println("<td>Jobs for : "+session_name+"</td>");
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection connection = DriverManager.getConnection("jdbc:odbc:tst","scott","tiger");
              Statement statement=connection.createStatement();
              ResultSet rs= statement.executeQuery("select req_no from require_info where sent_to = " + "\'" + session_name + "\'");
    //          out.println("Jobs for : "+session_name);
              while(rs.next())
              /*     String[] get_id={"shoba","ping","ting","ving"};
                   for(int i=0;i<get_id.length;i++)
                   out.println(" <tr align=\"center\">");
              //     out.println("<td><a href=\"servlet/testhyper\" name="+rs.getString(1)+"><em>"+rs.getString(1)+"</em></a></td>");
                   out.println("<td ><a href=\"http://localhost:7000/servlets-examples/accept_requisition.html?id="+rs.getString(1)+"\" ><em>"+rs.getString(1)+"</em></a></td>");
                   out.println("</tr>");
                   out.println("<br>");
              }catch(SQLException se){out.println("sqlexception"+se);}
              catch(ClassNotFoundException ce){out.println("cnfexception"+ce);}
              out.println("</table></body></html>");
         public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
              doGet(request, response);
              Can some one help me and see if there is anything i missing or doing wrong.
    thanks in advance

    Try storing the id at the top of the loop, then using that for the URL and the link text, instead of calling rs.getString(1) twice:
      while(rs.next())
        String emp_id = rs.getString(1);
        out.println(" <tr align=\"center\">");
        out.println("<td ><a href=\"accept_requisition.html?id="+emp_id+"\" ><em>"+emp_id+"</em></a></td>");
        out.println("</tr>");
        out.println("<br />");
      }

  • Different ways to invoke a servlet from another servlets?

    Hello,
    I am a bit confused today. I was thinking about all the ways by which I can invoke a servlet from another servlets. I know it can be done by creating an instance of the 2nd servlet in the 1st one. Is there any other way? such as say.... RequestDispatcher perhaps?
    Here is an example to illustrate my point. I have a login.jsp which submits to login.do. login.do search through database and first authenticate email and then the corresponding password. Now its time for displayGame.do. So here how do i do? if it was a displayGame.jsp then i could have used Redirection or Forward but when it is servlets? Can I still go for Redirection or Forward??
    Thank you for reading this confused post. :-)

    if it was a displayGame.jsp then i could have used Redirection or Forward but when it is servlets?Question: do you know what a JSP becomes when you first run it?
    Answer: a servlet.
    So yes, you can use a RequestDispatcher to forward/redirect to a servlet OR a JSP, whatever you like.

  • How to call a specific method in a servlet from another servlet

    Hi peeps, this post is kinda linked to my other thread but more direct !!
    I need to call a method from another servlet and retrieve info/objects from that method and manipulate them in the originating servlet .... how can I do it ?
    Assume the originating servlet is called Control and the servlet/method I want to access is DAO/login.
    I can create an object of the DAO class, say newDAO, and access the login method by newDAO.login(username, password). Then how do I get the returned info from the DAO ??
    Can I use the RequestDispatcher to INCLUDE the call to the DAO class method "login" ???
    Cheers
    Kevin

    Thanks for the reply.
    So if I have a method in my DAO class called login() and I want to call it from my control servlet, what would the syntax be ?
    getrequestdispatcher.include(newDAO.login())
    where newDAO is an instance of the class DAO, would that be correct ?? I'd simply pass the request object as a parameter in the login method and to retrieve the results of login() the requestdispatcher.include method will return whatever I set as an attribute to the request object, do I have that right ?!!!!
    Kevin

  • What is the best way to call a servlet from another servlet?

    I have a project with 9 servlets (class project). The way I have been moving from servlet to servlet is like this
    doPost(...)
    {      response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>Functions</title>");
    out.println(f"<form name=frm6 method=post action=/servlet2");
    out.println("<input type=submit name='btn' value='servlet2'>");
    out.println("</form>");
    So I have these 9 servlets - I call any 8 of them from the first servlet so I have 8 buttons on 8 forms <form=frm1, frm2, ...frm8 method = post...> But when I bring up the first servlet only 6 buttons show up. I was thinking about using hyperlinks instead, but I would like to do this with buttons. I wanted to do this with javascript and the location object, but I was advised to use jsp. I just want to move from one servlet to the next. Any suggestions appreciated for the best/preferred method for moving from one servlet to the next.
    Thanks

    I think you may need some clarification of terminology etc..
    First off, JSP isn't an alternative to javascript, it's an alternative to coding a servlet. A JSP is a mixture of java code and HTML and is translated into a servlet by the system. JSPs are primarilly for generating HTML pages with variable content. JSPs very frequently generate HTML which includes Javascript.
    You probably shouldn't think of what you're doing as one servlet invoking another, that does happen; a servlet can transfer an transaction to another servlet or JSP. In fact it's standard practice that a servlet does the logical stuff (like interpretting form data) then transfers to a JSP to generate the response page. However in this case it's the browser that can invoke one of the 8 servlets, the first servlet merely creates the page from which they are invoked.
    It's not obvious why only some of your buttons are showing up. In a case like this use the "view source" option on your browser to find out what HTML the servlet is actually delivering. What's wrong should be evident from that.
    You can put a hyperlink arround a button, or an image. Mostly people turn up their noses at the buttons supplied by HTML and use their own images for buttons. You
    can do somthing like this:
    <img src="/images/button3.png" border="0">
    (Of course this arrives as a GET transaction not a POST).
    Or you can do a bit of javascript like:
    <img src="/images/button3.png" style="Cursor: pointer;"
    onclick="document.locations.href='/servlet3';">

  • Calling another servlet in other server

    Hi - a quick newbie question -
    I need to call a servlet sitting on another server via http.
    I'm thinking of doing following..
    URL url = new URL("http",HOSTNAME_,PORT_, "/sp/xmlBuilderRates?" + urlParams );
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    // now how would I pass back output stream? to the original response object?
    uc.getOutputStream();
    Thanks

    I was looking to find a way to somehow relay child's servlet's output to current response object's output - streaming
    Maybe something like
    URL url = new URL("http","nyfddapp02",8889,"/sp/xmlReport?" + urlParams );
    BufferedReader in = new BufferedReader( new InputStreamReader( url.openStream()));
    String line;
    while( ( line = in.readLine()) != null )
    out.println( line );
    out.flush();

Maybe you are looking for

  • Help Adding Hard Drives

    Am trying to add a Seagate 250MB internal HD to a SIGG Ultra ATA133/100 Pro PCI card to the secondary IDE channel. I have a 200GB attached to the primary IDE channel which is running with no problems. I also have a HDD installed in the OEM uchannel w

  • Client Security Password manager not working

    Hi All, Have a T500 (model 2081CTO) running Win 7 Prof, with fingerprint reader.  Had installed and had working Enhanced Client Security, was web aspect of capturing / prompting userids and passwords just fine. Needed to reset IE8 to default.  That s

  • Very strange ethernet problem with iMac G5

    Thanks in advance for your help. I am helping my boss dust the cobwebs out of our network infrastructure (I work for a relatively small company in Michigan). In doing so, I unplugged all the ethernet cables out of our Linksys 24-port 10/100 switch an

  • Mac Pro 2008 - original memory

    My originl memory finally bit the dust on my mac pro 2008. I pulled them and replaced with my other third party ram and back up and running. does anyone know if Apple has a lifetime warranty on their ram? I heard they did? Will they replace the bad o

  • Please switch to a wi-fi connection to play this p...

    Hello I have an N8. When I try to use the BBC Iplayer it gives the following error: "please switch to a wi-fi connection to play this programme" I have connected to my home Wi-Fi, but the problem remains. Could anyone offer some advice or tips for th