Threadsafe servlet code?

Hi,
Im developing a sevlet accesing an enterprise system using HTTP. I am using the Apache HttpClient package and have a questing regarding thread safety. The classes are like below:
EnterpriseClient.java:
public class EnterpriseClient
private HttpClient client;
MultiThreadedHttpConnectionManager connectionManager = null;
public void create()
// create a thread safe HttpClient.
connectionManager = new MultiThreadedHttpConnectionManager();
client = new HttpClient(connectionManager);
public String getEnterpriseData(String msisdn)
PostMethod post = new PostMethod("....");
String result = post.getResponseBodyAsString();
return result;
public String setEnterpriseData(String msisdn, Strign data)
PostMethod post = new PostMethod("....");
post.setMessageBody(data);
String result = post.getResponseBodyAsString();
return result;
EnterpriseServlet.java:
public class EnterpriseServlet extends HttpServlet {
EnterpriseClient myClient = null;
public void init() throws ServletException
myClient = new EnterpriseClient ();
myClient .create();
public void doPost(...) {
// get enterprise data
String reply = myClient.getEnterpriseData(id);
// analyze data
// set enterprise data
String reply = myClient.setEnterpriseData(id, data);
Would this code qualify as thread safe? This is not the actual code, just used to illustrate the design.
HttpClient docs: http://jakarta.apache.org/commons/httpclient/preference-api.html
Any input would be appreciated.

I don't know the design or intention of the HttpClient but the way you have it designed now is that all users and threads share the same myClient object. Is that what you expected?

Similar Messages

  • Flush parameter of jsp:include has no effect on servlet code

    I am running 9.0.3 and my jsp code looks like:
    <jsp:include page =".." flush="false"/>
    but the resulting servlet code is:
    pageContext.include( __url);
    Which defaults to flushing the buffer!
    Does anyone know a work around or if Oracle is going to fix this?
    Thanks,
    Mike

    Try:
    public class ...  extends ...
        private static final boolean antialias = Boolean.getBoolean ("swing.aatext");
        private static Map hintsMap = null;
        @SuppressWarnings("unchecked")
        static final Map getHints() {
           if (hintsMap == null) {
                hintsMap = (Map)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); //NOI18N
                 if (hintsMap == null) {
                    hintsMap = new HashMap();
                     if (antialias) {
                          hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
           return hintsMap;
    ... later in class ...
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.addRenderingHints(getHints());
            super.paintComponent(g);
            ...needed this so custom paint would use AA. In my app I wrote text in my component and it was not AA, this turned it on.
    I don't think I had the same problem you, as my jlabels were always aa.
    Edited by: 805835 on Oct 27, 2010 5:06 PM
    Edited by: 805835 on Oct 27, 2010 5:07 PM

  • How to retrieve "env-entry" in servlet code

    i have a pretty straight-forward web app, which contains a servlet, among other things. the web app is packaged in .war, and it in turn is part of a .ear file. i am using WAS 640 sneak preview on windows xp.
    in the web.xml file, i added the following lines:
    <env-entry>
      <description>some texts</description>
      <env-entry-name>myapp.home</env-entry-name>
      <env-entry-type>java.lang.String</env-entry-type>
      <env-entry-value>c:/myapp</env-entry-value>
    </env-entry>
    in my servlet code, i try to retrieve the value for "myapp.home" like this:
    try
    Context ctx = new InitialContext();
    home = (String) ctx.lookup("java:comp/env/myapp.home");
    } catch (Exception ex) {
    ex.printStackTrace();
    after .ear is deployed, i can see in the JDNI Registry (using Visual Admin Tool), myapp.home is added to the tree:
    webContainer
      -applications
        --myCompany.com
          ---myEarFileName
    myWebAppRoot
    java:comp
    env
    myapp.home
    the entry has the correct class name and object value.
    when the servlet code that performs the jndi lookup is called, i get an exception:
    com.sap.engine.services.jndi.persistent.exceptions.NameNotFoundException: Path to object does not exist at : java:comp
    ??? QUESTIONS:
    #1 what am i doing wrong?
    #2 if the lookup name must contain the entire jndi tree as listed above, then how can this code be portable to other app servers?
    thoughts are greatly appreciated.

    thanks for the hints, but unfortunately they didn't work.
    1. after switching the order of value and type in env-entry, rebuild/redeplpoy, same exception. the ordering  probably didn't matter since even with the reversed order, the name and value showed up correctly under the jndi tree.
    2. well, i tried giving it the full path, starting with 'webContainer', then 'applications' etc, separated by forward slash. now the exception says path to webContainer is not found.
    so what gives? are there no standards?

  • How to translate this statement to java servlet code

    INSERT INTO table_name (column1, column2,...)
    VALUES (value1, value2,....)

    You wouldn't translate that statement to servlet code. The idea doesn't make any sense. However you might include it in a servlet; read the tutorial that zadok linked to.

  • Compiling servlet code

    I m new to servlets.
    I just copied a servlet code from servlet Help.Then tried to compile with it JDK1.3.But it showing error.It is not compiling package Javax .What may be the possible error.

    Right, the javax.servlet packages are not part of J2SE.
    You'll need a servlet engine to run your servlets/JSPs. It'll have the servlet.jar containing the javax.servlet packages. You'll have to add that to your CLASSPATH when you compile.
    I'd recommend Tomcat as your servlet engine. It's capable and free:
    http://jakrata.apache.org/tomcat
    %

  • Help translating a servlet code to bean

    hi all
    i'd like to translate a servlet code to bean code
    the servlet, called from the <img src""> tag in my web page retrieves an images from a database and, setting the response content-type to "image" returns the image.
    i'd like to do it through the common getXxx/setXxx methods of a bean
    how to do it?
    that's the servlet's code:
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
            response.setContentType("text/html");
            ServletOutputStream out = response.getOutputStream();
            try
                Connection connection=(Connection)getServletContext().getAttribute("connection");
                Statement s=connection.createStatement();
                response.setContentType("image/jpeg");           
                ResultSet rs=s.executeQuery("select "+request.getParameter("col")+" from products where id="+request.getParameter("id"));           
                while(rs.next())
                    out.write(rs.getBytes(request.getParameter("col")));
            catch(SQLException s)
                response.setContentType("text/html");           
            catch(NullPointerException n)
            out.close();
        } thanx in advance
    sandro

    try this:
    <%
    response.setContentType("text/html");
    try {
    Connection connection=(Connection)application.getAttribute"connection");
       Statement s=connection.createStatement();
       response.setContentType("image/jpeg");
       ResultSet rs=s.executeQuery("select "+
                  request.getParameter("col")+
                 " from products where id="+
                  request.getParameter("id"));
       while(rs.next()) {
    %>
          <%= rs.getBytes(request.getParameter"col"))) %>
    <%
    } catch(SQLException s) {
       response.setContentType("text/html");
    } catch(NullPointerException n) {
    %>

  • Running a servlet code over Tomcat 4.1

    MY HTML CODE THAT CALLS THE SERVLET:
    <html>
    <body>
    <form method="post"action="http://localhost:1234/examples/servlets/program">
    Name : <input type=text name="text1">
    <input type="submit">
    </form>
    </body>
    </html>
    MY SERVLET CODE THAT I HAVE ALREADY SUCCESSFULY EXECUTED ON TOMCAT 3.2.1:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class program extends HttpServlet
    public void service(HttpServletRequest
    req,HttpServletResponse res)throws
    IOException,ServletException
    PrintWriter out= res.getWriter();
    out.println("Hello World!");
    String str= req.getParameter("text1");
    out.println("WElcome:"+str);
    out.close();
    1.==>Any body please tell what all classpaths I have to set here?
    2.==>Do I need to write any xml file for running this code ..if yes then please tell what to write in the xml code and where to save it.
    3.==>Please tell me where to save my servlet code and html code in Tomcat 4.1
    4.==> Do I need any batch file during its execution and lastly how to execute it in Tomcat 4.1...
    I have already successfully executed the program in Tomcat 3.2.1
    5==> Please check if my codes are OK to run over Tomcat 4.1

    You should get in the habit of creating war files ( Web Archive file ).
    You can deploy a war file to any servlet container like tomcat.
    Maven2 is a nice tool that helps you build war files.
    Here is an article on how to get started.
    http://www.javaworld.com/javaworld/jw-12-2005/jw-1205-maven.html

  • Running a servlet code in Tomcat 4.1 or higher

    MY HTML CODE THAT CALLS THE SERVLET:
    <html>
    <body>
    <form method="post"action="http://localhost:1234/examples/servlets/program">
    Name : <input type=text name="text1"><br><br><br>
    <input type="submit">
    </form>
    </body>
    </html>
    MY SERVLET CODE THAT I HAVE ALREADY SUCCESSFULY EXECUTED ON TOMCAT 3.2.1:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class program extends HttpServlet
    public void service(HttpServletRequest
    req,HttpServletResponse res)throws
    IOException,ServletException
    PrintWriter out= res.getWriter();
    out.println("Hello World!");
    String str= req.getParameter("text1");
    out.println("WElcome:"+str);
    out.close();
    Please tell me the exact class paths to set or any batch file to be made,where to save the servlet and html codes.Also do i need to write any other to execute the above servlet in tomcat 4.1 or higher i.e any xml file etc and if yes then please let me know the code and where to save it.
    Please also verify the method of executing this servlet.

    http://forum.java.sun.com/thread.jspa?threadID=5237132&tstart=15

  • Closing  a browser with the help of servlet code

    Is it possible to close a browser by using servlet code?
    If so please help me with code.
    Thanks

    This is really a javascript question, but it's:
    window.close()

  • How to disable client cookie using Servlet code

    Hi All,
              I want to disable the client cookie using JSP or servlet code.Is it possible how I can do it.
              Thanks in Advance .

    Hi,
              first of all, the URL rewriting option (URLRewritingEnabled) in the weblogic.xml must be set to true.
              Now, for all first-timer web requests the BEA WLS always uses URL rewriting in addition to cookies to see wether the browser accepts cookies or not.
              I would try to rip of all of the cookies in the header, then flush the response to force the http header to be written.
              I have never tried it and has no idea if it will work, however the teory behind supports the idea.
              This will not work for toggling session tracking mechanism from a session already established with cookies, the session will be lost if attempted to do this without the URL-rewriting enabled on the page.
              - Anders M.

  • Sample controler. servlet code wanted

    Dear All
    Can some one please mail me a sample controler.jsp / Servlet code preferable a professional one with session tracking.
    [email protected]
    Thanks in Advance

    Try Struts from jakarta.apache.org
    It blows out any other controller from the planet
    HTH
    Trajano Roberto

  • Simple servlet code

    Forum wellwishers giv some simple easy to understand Servlet Codes for JServlet beginners an especially me with the code explanation.
    Tks
    MichelFdO M

    Start reading part II of the Java EE tutorial: http://java.sun.com/javaee/5/docs/tutorial/doc/bnadp.html
    Servlets are covered in chapter 4 and on.

  • Sample Servlet code that connects to Microsoft SQL 2008

    Does anybody have sample Servlet code that connects to a Microsoft SQL 2008 Resource Pool?
    Thank you.

    JDBC is used to talk to databases. Not database utilities. As an example SSIS is not a database.
    So the question would be is the 2008 "Resource Governor" (of which "Resource Pools" are part) a utility or a database entity?
    [http://technet.microsoft.com/en-us/library/bb933866.aspx]
    I would guess that it isn't a database entity.
    Thus the only way to access it is if a database entity allows you do access it. And for that you would need to look for SQL Server system proc(s).

  • Nedd to find basic servlet code

    Java novice
    I need basic servlet code that will capture the input of one form field and write it to a flat file on the server. Servlet will be called in html form action. Any good sources to start with? It appears that this is so basic that I've had trouble finding anything out there.
    Thanks

    If what you want is to learn the basic stuff invloved in doing what you want to do.
    Just follow the java servlet tutorial and io tutorial (You can use google to reach those)

  • Whats wrong with this servlet code..?no error in log

    hello guys..hope one of you can help....
    i have 2 servlet classes. one receives form data sent from a jsp page, then create a form object containing all the inputs.. that object is then added to the session ..
    also, it construct a User object containing info about the present user and add it to the session.. IUser and Form are inner to the main class.
    the first servlet (check) seems to work fine.. but the problem occurs with the second servlet...i have inserted some printl statements to help me identify how far it goes and it seems that the whole code of the second servlet(update) is almost redundant....I dont get any error message ..simply a blank page which is of course of no help to me...
    I hate inserting long code here but i would be pleased if anyone could tell me of a way to find out about the actual problem..program compiles fine but..it just freezes at runtime
    ..here is part of the code..whats wrong?
    HttpSession session=request.getSession();
         User user2=(User)session.getAttribute("person");
         Form fr=(Form)session.getAttribute("form");
         System.out.println("User and Form created");
         int uid=user2.getId(); //class User contain the getId method
         String uname=user2.getName();
         System.out.println("Data for user retrieved");
         String goTo=fr.getC();
         String password = fr.getP();
    String email=fr.getE();
    String newName=fr.getN();
    System.out.println("data from form retrieved");
    thanks

    the first servlet was indeed supposed to ass all those attributes...
    but the thing is that the data being retrieved later were not of the type expected...
    i have now decided to proceed differently but I am a bit curious to lean more about something that you mentionned in relation to servlet listeners..i never thought of the need to remove all those attribute when the session times out...
    I thought that it was doned automatically with a call to session.invalidate().
    is that not the case?
    thanks

Maybe you are looking for

  • Null check for a bind variable in view criteria

    Hi, Greetings. I am using Jdeveloper 11.1.2.0. I have a view object, LocationsView, for locations table of the XE database. I want to apply a condition, ((:bind_var is null) or (:bind_var is not null and location_id = :bind_var), in this LocationsVie

  • Submit via Job- problem in code

    I need to convert the PR to PO automatically, we can do this by me59n, so iam scheduling the job for the me59n program. here iam using Badi's, iam getting the PR, plant, vendor from IM_Eban from the method of Badi, reading this in internal table, zeb

  • OS  X Freezes as it starts

    Dear Friends, Please help me in resolving this problem. I have a MAC G4. OS X is installed on it. The OS freezes as it starts up. No icon appears on the desktop. I have the Restore CD and the Mac OS X installation CDs. I have data on the MAC. Vicken

  • Increment  variable in a txt file

    Hello hello [[]] =) Just wondering if is it possible to change on string to another , inside a txt file. The problem is: Someone ask a question , choose the number of answers, write those answers and send it to a comboBox ( the answers) . The person

  • Stop image from loading once it has been requested.

    I am working on an applet for viewing information on maps. I load a background map and then data is displayed over the map. The map loads in tiles, as the user drags the map additional tiles are loaded in the new location. The user can also zoom in t