Connection between 2 servlets

I have two servlets. In my 1st servlet I loaded my driver and connected to my database. In my second servlet I'd also like to execute sql statetements. Do I have to connect to the driver again and write Statement,Connection lines again?
Isn't there a way to use a query?
Thanks

You may consider using the connection pooling facilities provided by the server you use.
Here's a resource that gives an into into connection pools
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/conpool.html
Cheers,
Ram.

Similar Messages

  • DB connection between Two servlets

    Hi,
    I have Two servlets, servlet1,servlet2.
    In servlet1, I have written Connection Pooling using java class and In the INIT method I'm writing the database connection,
    My Question is, How to use the same DB connection in servlet2 ?
    here is my code (some portion) :
    public class abc_internal extends HttpServlet
    { private ConnectionPool pool;
    Statement stmt = null;
    Statement stmt1 = null;
    Statement stmt2 = null;
    ResultSet abc = null;
    ResultSet Name_Header = null;
    private static final String CONTENT_TYPE = "text/html; charset=windows-1252";
    public void init(ServletConfig config) throws ServletException
    try
    pool = new ConnectionPool("oracle.jdbc.driver.OracleDriver","jdbc:oracle:thin:@IPADDRESS:1526:DB NAME","USERNAME","PASSWORD",5);
    }catch(Exception e)
    throw new UnavailableException("Couldn't create Connection Pool.....");
    PLEASE Help me...
    Thanks in advance.

    Thanks for the reply... I'm new to Java...I would appreciate, if you can show me as a example for the above code...
    Thanks.

  • Share database connection between servlets

    hello,
    i need help to know if the following code works well.
    The intention is to share a unique JDBC database connection with all servlets of my application.
    //************************ file Conexao.java ***********************
    // this class makes a databse connection
    import java.sql.*;
    public class Conexao
    Connection conex;
    public void conecta()
    try
    Class.forName("interbase.interclient.Driver");
    conex = DriverManager.getConnection("jdbc:interbase://localhost/c:\\temp\\Kuala.gdb","SYSDBA","masterkey");
    catch(ClassNotFoundException ex) { }
    catch(SQLException ex) { }
    public void desconecta()
    try
    { conex.close(); }
    catch(SQLException ex) { }
    //****************** file SetConnectionContext ****************
    // this class creates an instance of Conexao class and invokes the
    // conecta() method. After, obtain the ServletContext object and
    // set the attribute "conecta" to the ServletContext
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class SetConnectionContext extends HttpServlet
    Conexao connection = null;
    public void init()
    connection = new Conexao();
    connection.conecta();
    ServletContext context = getServletContext();
    context.setAttribute("conecta", connection);
    public void destroy()
    { connection.desconecta(); }
    public void doGet (HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    response.setContentType("text/html");
    PrintWriter saida = response.getWriter();
    saida.println("<H1>objeto connection atribuido no contexto</H1>");
    //****************** file GetConnectionContext.java ******************
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class GetConnectionContext extends HttpServlet
    public void doGet (HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    response.setContentType("text/html");
    PrintWriter saida = response.getWriter();
    ServletContext context = getServletContext();
    Conexao con = (Conexao) context.getAttribute("conecta");
    try {
    Statement comando = con.conex.createStatement();
    ResultSet rs = comando.executeQuery("SELECT * FROM kl_campanha");
    while( rs.next() )
    int codCampanha = rs.getInt("codCampanha");
    saida.println("<h3>"+codCampanha+"</h3>");
    catch(Exception e) { }

    I understand the use of a static variable.
    But if i want to share a database connection object (a
    instance varible instead of class variable) that is
    instantiate once and saved in a ServletContext
    attribute,
    and afterwards the other servlets can get
    the object through the ServletContext attribute and
    use it. This will works well? i did tests with the
    code and everything apparently works.
    How does a new connection (different user) get the old context?

  • Regarding connection between front end HTML and back end SQL 7.0

    Hi!!
    I am working on the project 'ERM'. I have designed 12 forms using HTML. Can u please give me brief idea how to establish the connection between a back end and front end i.e. between HTML and SQL 7.0. If possible can u provide me the source code for the same.
    I will be very thankful to you.
    Thanks,
    Jigar.

    Read up about multi-tier applications.
    You need servlet and JSPs for the server-side presentation layer, some classes for the business logic, and some mor for the persistence layer either using JDBC or some framework like Hibernate.

  • Open connections between AS Java and AS ABAP when using JRA

    Hi, we have a problem with open connections and hope that someone here could give me hint where to find a solution.
    The situation is that we open a connection from a Java application to an AS ABAP. In detail, the application first connects to a statefull session bean on the AS Java by RMI. The bean communicates with the associated AS ABAP by the Java Resource Adapter (JRA).
    All interactions between all components work correctly. But even after we close the application, manually close of the connections (on side of the AS Java) , remove all created and used session beans there are still open connections between the AS ABAP and the AS Java.
    The transaction smgw (Gateway Monitor) shows open connections from jlaunch to our local SAP gateway using the internal communication protocol. Obviously, the established connections are not closed, even when they are open for a week or longer.
    After opening 100 connections, the AS ABAP denies additional connection attempts.
    We have been able to close all open connections by restarting the AS Java or by restarting the Connector over the Visual Administrator (path: Cluster – Server – Services – Connector Container – “select the right connector” – stop / start).
    We have developed our application similar to the tutorial from [https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/ad09cd07-0a01-0010-93a9-933e247d3ba4]
    Can someone explain to us why the connections stay open for so long? Is there no timeout mechanism? Or is there some way to close the connections from our Java application?

    Hello,
    maybe someone can help us with our problem.
    We have developed our application similar to the tutorial from https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/ad09cd07-0a01-0010-93a9-933e247d3ba4 and it was running without problem with the SP12, now we change our system to SP16 and we are having the problem described in note 1083348, but as you can see, for us it was working with SP12 and now it doesn't work with SP16....
    Here is part of our code....
        public List getAll() {
            String functionName = "bla";
            try {
                openConnection();
                MappedRecord response = (MappedRecord) interaction.execute(null, request);
                MappedRecord record = (MappedRecord) response.get("E_S_RETURN_CODE");
                if (((String) record.get("RETURN_CODE")).equalsIgnoreCase("E")) {
                    throw new SQLException((String) record.get("RETURN_TXT"));
            catch (ResourceException exc) {
                throw new EJBException(".");
            catch (SQLException exc) {
                throw new EJBException(".");
            finally {
                closeConnection();
        protected void openConnection() {
            try {
                connection = connectionFactory.getConnection();
                interaction = connection.createInteraction();
            catch (ResourceException exc) {
                interaction = null;
                connection = null;
                throw new EJBException(getExceptionText(exc));
      protected void closeConnection() {
           try {
                if (interaction != null) {
                    interaction.close();
                if (connection != null) {
                    connection.close();
            catch (ResourceException exc) {
                throw new EJBException(".");
    With that code we are getting this error: "Connection handle is already closed and no longer associated with a managed connection" everytime we try to close the connection in the method closeConnection().
    We were thinking that maybe we should not close the connections, because the were already close, and tried not to close the connection (connection.close()), but then after a few time we are getting the following error, because we are not closing the connections:
    Connection to ABAP System could not be opened, because the Connection Factory returns "Cannot get connection for 120 seconds. Possible reasons: 1) Connections are cached within SystemThread(can be any server service or any code invoked within SystemThread in the SAP J2EE Engine), 2) The pool size of adapter "eis/..." is not enough according to the current load of the system or 3) The specified time to wait for connection is not enough according to the pool size and current load of the system. In case 1) the solution is to check for cached connections using the Connector Service list-conns command, in case 2) to increase the size of the pool and in case 3) to increase the time to wait for connection property. In case of application thread, there is an automatic mechanism which detects unclosed connections and unfinished transactions.". Please check the connection defined for the Connection Factory of the Java Resource Adapter with JNDI name...
    Any help?

  • Testing the connectivity between Integration Directory&  Integration Reposi

    Hi Experts,
    I am verifying  the configured PI7.0 server,but i am not able to fine the Integration scenarios at the stage :
            (Testing the connectivity between Integration Directory and
             Integration Repositor)
    In Integration Directory Configuration  screen when i click on tools----
    >Transfer Integration Scenario from Integration Repository’.
    it is displaying the dialog box with question mark sign,when i click this sign it is displaying another dialog box adn displaying as NO OBEJCTS FOUND.
    So can any body help me in this matter. with detail procedure with  steps in sequence order.
    I appreciate the accurate and soon reply
    Thanks in Advance
    regards
    Ken

    > Hi Barry ,
    >
    > Thanks for the Immediate reply.
    > Could you  pls send me how to create BPM  in IR  with
    > step by step
    > Then how to call that in ID.
    >
    > Please send me the detail procedure  with steps.
    >
    > Thansks in Advance
    >
    > regards
    > ken
    You do not need to do that.  Import the BASIS and ABAP Content, and these are already included. 
    Why work harder than you need to
    If you want to create a BPM, then follow one of the how to guides:
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/40697f5e-088d-2910-6592-cefedf19860e
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/d46b9b90-0201-0010-ef92-9964c1bc98e1

  • SNC connection between two SAProuter

    Hi Guys,
    Please give me the procedure to establish the SNC connectivity between two SAProuter.
    Thanks and Regards,
    Atul

    Hi Atul,
    have tried the SDN Search Function with "snc AND saprouter"? It gave me this Links:
    SNC User Guide:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sapportals.km.docs/documents/a1-8-4/snc user guide.pdf
    Configure Secure Network Communication SNC:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sapportals.km.docs/documents/a1-8-4/configure secure network communication snc.pdf
    Regards
    Gregor

  • DSN-less Connection in a Servlet

    hai,
    I am using the following DSN-less Connection in a servlet. It is working fine in as
    a stand alone application. But it is not working in a a servlet.It is throwing DSN name too
    long exception.
    dsn="DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:\\db1.mdb";
              try
              System.out.println("DSN-less connection.......................");
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:"+dsn);
              if(con!=null)
                   System.out.println("Connected");
              else
                   System.out.println("Not Connected");
              st=con.createStatement();
              System.out.println("connected.........................");
              catch(Exception e)
              {   e.printStackTrace();
    Please give me the details why it is not working.
    I am using jdk1.3 and jsdk2.0.
    bye
    -raja

    Dear jschell,
    I am very thankful to u for being my problem solved.
    As u said the problem is with the syntax and with environment.
    I have changed the syntax in connection string by inserting a
    space in between
    DRIVER={Microsoft Access Driver and (*.mdb)};DBQ=c:\\db1.mdb";
    and running the servlet in servletrunner it is working.
    Now to run the same servlet using a webserver I need to configure it properly.
    I am usning Java Web Server. Earlier I installed JDK1.2 on my system and
    now I changed it to JDK1.3. There r some problems while uninstalling JDK1.2.
    May be the JWS is using the jdk1.2 runtime environment.
    Pleaselet me clear this.
    Thanks a lot for all the help u have done so far.....
    -raja

  • Setting up a https connection between SAP CRM and genesys gplus adapter

    Hello All-
    We are integrating SAP CRM with genesys mysap gplus adapter. We are struck in setting up a https connection between sap and gplus adapter.
    Can anyone here help me out in this like how to get the SSL Protocol, keystore, keystore password,truststore and truststore password.
    Information abt Adapters server certificate. Do we need to configure the adapter for the proxy also?
    Any additional comment will help. Thanks in advance!

    Hello Vinod,
    Please refer the following OSS notes 564085.
    Please reward if helpful.
    regards,
    Muralidhar Prasad.C

  • Connection between SDM client and server is broken

    Dear All,
    First of all this is what I have
    -NW04 SPS 17
    -NWDS Version: 7.0.09 Build id: 200608262203
    -using VPN connection
    -telnet on port 57018 is succesfull
    I can login to SDM server (from NWDS and from SDM GUI) I can see the state of SDM(green light), restart it, can navigate through tabs in GUI, but every time I am trying to deploy an ear i have this error:
    Deployment exception : Filetransfer failed: Error received from server: Connection between SDM client and server is broken
    Inner exception was :
    Filetransfer failed: Error received from server: Connection between SDM client and server is broken
    I have already read a lot of topics,blogs,notes but didn't find the solution.
    Can anybody help me?
    Best Regards

    Having same issue. Nothing helped so far... Using NWDS 7.0 SP18.
    I have turned SDM tracing on and this is what I see on client side after sending first data package:
    com.sap.sdm.is.cs.cmd.client.impl.CmdClientImpl: debug "20120224140253 0280/17 Client: finished sending string part"
    com.sap.sdm.is.cs.cmd.client.impl.CmdClientImpl: debug "20120224140253 0280/0 Client: receive String part from Server"
    com.sap.sdm.is.cs.cmd.client.impl.CmdClientImpl.receiveFromServer(NetComm ..): Entering method
    com.sap.bc.cts.tp.net.NetComm.receive(): Entering method
    com.sap.bc.cts.tp.net.NetComm: debug "Method "receive(char[])" could not read all requested bytes. There are still 12 bytes to read"
    com.sap.bc.cts.tp.net.NetComm: debug "Caught IOException during read of header bytes (-1,          43):Connection reset"
    com.sap.bc.cts.tp.net.NetComm: debug "  throwing IOException(net.id_000001)"
    com.sap.bc.cts.tp.net.NetComm.receive(): Exiting method
    com.sap.sdm.is.cs.cmd.client.impl.CmdClientImpl: Exiting method
    com.sap.sdm.is.cs.cmd.client.impl.CmdClientImpl: debug "20120224140253 0281/1 Client: connection was broken"
    com.sap.sdm.is.cs.cmd.client.impl.CmdClientImpl: Exiting method
    com.sap.sdm.is.cs.cmd.client.impl.CmdClientImpl: debug "20120224140253 0281/0 Client: finshed sendAndReceive"
    com.sap.sdm.is.cs.cmd.client.impl.CmdClientImpl: Exiting method
    My connection on server is still active so I have to restart SDM server to reset and try it again.
    Anyone have idea whats happening?
    Edited by: skyrma on Feb 24, 2012 2:46 PM
    Edited by: skyrma on Feb 24, 2012 2:47 PM
    Edited by: skyrma on Feb 24, 2012 2:47 PM

  • Connection between O and BP is missing

    Hi,
      When i check inconsistency for a user, i am getting " Connection between "O" and "BP" is missing. When i check the Org.unit in PPOSA_BBP, i could see no BP exists for that Org.unit where user is assigned. I have replicated the org.unit from HR system but yet the BP hasnt been generated. Can you please share your idea on this.
    Regards,
    Prasath J

    Hi Prasath,
    This might be because you need to assign the user to a Purchasing Organisation or a Purchasing Group. If the user do not have BP created then you can do this by using tcode USERS_GEN.
    Go to USERS_GEN and follow below steps :
    1. Select Create User From Existing SU01 user
    2. Enter the org id of the POrg or Pgroup under which you want to assign the user
    3. Select country and execute
    4. In next window one popup will occur, select Area Of User
    5. In next popup enter the user id
    6. Next select the user and click Ok.
    7. This will create a BP and CP for the user and assigns the BP to the Org id of the POrg or Pgroup.
    8. Now check the consistency of the user it will show all green.
    It might give you error like eMail id for BP XXXXX is missing if the SU01 profile of the user does not contain any user id but it is not critical.
    You can open the BP in BP tcode and enter the email id of the user.
    Let us know if it solves your issue.
    Regards,
    Mayur

  • (Trouble printing) Trouble with connection between Macbook Pro and Hp Deskjet 1510.

    Trouble with connection between Macbook Pro and Hp Deskjet 1510. (Nothing Prints).
    I have a Macbook Pro and am having difficulty printing documents from ‘Pages' from my Hp Deskjet 1510. I have installed the necessary software for the printer and it is connected via USB. Every time I try to print the printer icon comes up as it should, 'printing' and then 'job completed' and then the icon disappears. (Nothing is printed.) I thought it might be something to do with Pages compatibility with the printer but exporting the document to Word or making it a PDF doesn’t change anything. I don’t have Microsoft Word on my computer. The scanner does work and when I printed a ‘Test Page’ that worked too.
    Let me know if you know why this is happening.

    With these settings the network now works flawlessly, however, when i have my ethernet cable plugged in, my internet access via my airport card(on the macbook pro) is no longer available. Hoping you can tell me why this would be with this info i've provided.
    Educated guess. The networking devices have priorities as to which are used. The standard order is that Ethernet has a higher priority than Airport.
    While your Ethernet is unplugged it is inactive and the Mac ignores it. Once you plug it in, the Mac sees that it is active and switches traffic to that interface.
    I actually take advantage of this feature at home, but configuring my Airport and Ethernet with identical fixed IP addresses. Normally I'll use Airport, but if I'm copying a huge file and I want faster performance, I'll just walk my MacBook (previously iBook, previously Powerbook) over to my Ethernet switch and plug in my MacBook. Magically, the Mac detects that the Ethernet is active and continues the file transfer uninterrupted over the faster 100baseT Ethernet connection. When the transfer is finished, or if I really need to move back to the Comfy Chair, I unplug the Ethernet cable, and all activity reverts back to the Airport, all without disrupting any existing networking connections.
    You on the other hand have totally different settings for your Ethernet and your Airport, so when you switch to Ethernet, you basically loose your Airport connections.
    Something you can try:
    System Preferences -> Network
    Gear icon on the bottom left, next to the [+] [-] icons.
    Select *Set Service Order...*
    Now Drag the network interfaces into the perfer priority order you want. In this case put Airport above Ethernet.
    NOTE: You may want to create a new Network Location for this, instead of messing with your normal home Location (which is most likely the default Automatic. That way you have your original you can always fall back to.

  • Connection between CRM back end and ASP front end website for Ecommerce

    Hi All,
    I want to establish the connection between a ASP website and CRM back end server(we are replacing th existing ERP back end system with SAP CRM ).
    I want to know whether I have to go with XI or any other connectors provided by SAP to establsih the communication between the existing ASP website and CRM back end server..
    Can anyone please help me out.
    Thank you,

    Okay here is the general concept for your scenario:
    -You will call standard/custom RFC's(could be BAPI's) in the CRM system from the existing application. 
    -You will need to write a new model layer in your ASP application that calls the RFC layer in CRM
    -You decide what data you want to use from CRM in your application
    Let's assume at minimum you will want to use the product master, business partner master, and business transactions.  You will need RFC's/BAPI's for every interaction point where you will consume/publish data to CRM.
    So when an user creates an order from your e-commerce site, you will need to support saving an order in CRM.  This is example of how you need to map out each function in your existing site to a part of the CRM system.  Since we don't know what your site currently does, this is something you would have to do.
    Once you have mapped out the business level data to the CRM system, then you can evaluate where you will need a BAPI and/or RFC call.  Once that is done, then you can look at the CRM system and see what standard pieces can be called.  Then everything else is custom development.  Your ASP application will call CRM via RFC. 
    It is possible to do what you want to do, but it is going to require a lot mapping work and a fair amount of development effort to integrate the two pieces.  I don't know if you might be better off looking at the SAP Internet Sales Solution instead so you could focus only customizing that application, instead of worrying about an integration problem.  It just depends on how much special functionality your existing e-commerce site has today.
    My general recommendation would be for you to hire a consultant that has done an SAP e-commerce project using SAP CRM in the past and let them guide you on the implementation issues.  An on-site resource could better answer your "high-level" questions.
    However if you have more questions please ask and I will try to answer to the best of my knowledge.
    Good luck,
    Stephen

  • How can I get connection between VC and back end ABAP system

    Hi, I'm developing the kits in the VC platform, and I need to access the back end system designed by ABAP. For example, the system provides some public functions(not web services), and I hope when I click the "search" button, the VC front can call the remote functions and get the data from the back end system. In addition to that, the most important is I must keep the connection real-time. How can I do it?

    Thanks for your help. At present, my VC version is 7.1.4 which isn't installed in the portal server but in local machine, and I'm new in the VC. What I want is when I click the "search" button(in the properties pannel), I can get the data from the remote server. I know the VC 6 provides similar functions, but the current version doesn't. Could you explain the details of how to get and keep the connection between them? Thanks so much.

  • Connection between Structure Field and Table Field

    Hello everybody,
    I'm trying to find a connection between a field in the structure and the actual filed in the table of the database. For example in the structure CAUFVD you have the field PLNNR. This information is stored in the table AFFL in the field PLNNR.
    In the transaction SE84 you can display a structure with all it's fields but I don't see anywhere from which table and field the information is gathered.
    Can you please help me in finding the connection between the structure field and the table field in the database in which the displayed information is stored?
    Thanks and best regards,
    CALIN Marius-Bogdan
    SAP - PP-KeyUser

    Double-click on the structure field and you can do a where-used to find the codepoints, interface usage, etc.  You might find it that way.  You could also look at the flow logic of your screen and try to trace it back.  Otherwise, you'd have to use watchpoints, the debugger, runtime analysis or various other developer tools to find the data population.  If you are a user and not a developer as your signature indicates, you might need to find a developer for this.  Sometimes, it can be incredibly frustrating with SAP because the data field will be handed off 4 or 5 times before it actually reaches its destination field.  Unfortunately, I haven't worked with PP in at least 10 years so I can't give you a better answer; maybe someone else can.

Maybe you are looking for

  • Password Change on Pix 515e

    All, I inherited a PIX that I need to change the passwords to. Currently it has: enable password xxx passwd adfasdfnen encrypted I am wanting to remove these two passwords and create a username and password for the login. If I enter the command no en

  • ALV grid display in a particular format

    Hi, Could you please tell me how do i display the alv grid in this particular format : col1           |         col2               |           col3          |       col4             | abc1          |         def1               | - |---- |           

  • Cannot get Win8 Pro computer run the Connect a Computer to the Server Wizard (computerconnector) of Essentials 2012

    I've spent 1/2 the day trying to troubleshoot this problem and finally give up. My client has a Windows Server 2012 Essentials server (with all updates installed - no errors in error logs nor SFC /SCANNOW).  Purchased a new Windows 8 Pro computer, wh

  • Revert to Apple's choice for mail app fonts

    I had difficulty reading the tiny text in the message pane on the OS X Mail app, so I played around with the font and font size in an attempt to find something better. That had mixed results, but I found the width doesn't adjest when using general la

  • HELP ME! Embedding Graphics in Reports.

    I am trying to embed an Oracle Graph (from Graphics) in a report, but when I try to run the report I get a REP-0075 error followed by an OG-01603 "Unable to create PL/SQL Development Environment Context" Error. Then when I click OK, I get another err