AJAX calling a servlet's synchronized doPost method

Hi all. This problem has been bugging me for a week already and still no solution in sight...
Anyway, buttons in a page I'm creating uses AJAX to call a servlet's synchronized doPost method. Once a button is clicked, the servlet calls another java class which does some back end processing. Once the called java program is finished running, the page is updated telling the user that the selected backend process has finished running. It works fine if I just run one backend process at a time...however, if try to run another backend process while the previous backend process is still running, even if the backend process is finished, the page doesn't get updated with the message informing the user that the job is finished. The page only gets updated once all the jobs have finished running. What I want to happen is that whenever a job gets finished, the page gets updated.

Yeah, it has
something to do with the threads. However, I had to
synchronize the doPost method because if the doPost
method isn't synchronized, running 2 or more back end
processes simultaneously would result in the previous
backend processes being terminated, only the last
back end process would be run successfully.Yea! that's what I wanted to say! most of the time there are critical sections in your code when concurrency is there, you need to recognize them and synchronize only the critical sections.
I don't think synchronizing the whole dopost method is a better way to deal with concurrency issues. It defeats the purpose of spawning a new thread for each request(it's my personal opinion, I may be wrong).
But I got one contradiction from one member of sun forum, he says spawning thread from a servlet is not a good practice according to java EE specification. But I don't think there is any way out other than this, to deal with this scenario. I am waiting for further suggestions, so keep an eye on this thread:
http://forum.java.sun.com/thread.jspa?threadID=5149048
~cheers~

Similar Messages

  • Jave servlets- doget() and dopost() methods.

    Iam trying to learn servlets but got confused on these doget() and dopost() methods usage. I just want to know generally what does these methods do in general (like the doget() sets the header..but what about dopost()?). I saw some example code where doget() is called within a dopost()method so Iam not clear about their purposes.
    I'd appreciate any help possible. Thank you.

    The doPost() and doGet() (also doHead() etc.) methods are all designed to handle specific HTTP request types. eg: doGet() handles HTTP GET requests (requests caused by common HTML links or typing a URL in your browser's address bar) while POST handles HTTP POST requests (commonly generated by HTML form submissions).
    When you see an example of a serlvet's doGet() being called within it's doPost(), it is because, at least for part of the processing, the servlet will be treating the two request types the same way.

  • Calling doGet() from in the doPost() method.

    What is the conditions we have to cheak to call doGet() method from doPost().

    doGet() using for request.getParameter(). the exact story is u want to get some data form html (or) data bases. it is usefu

  • Large requrest paramter in ajax call servlet

    HI
    I want to pass large requrest paramter in ajax call to servlet which has got lot of character ,when i passing i get unknow error in ie n aborted error in mozilla any help...

    HI
    I want to pass large requrest paramter in ajax call to servlet which has got lot of character ,when i passing i get unknow error in ie n aborted error in mozilla any help...

  • Calling a servlet from HTML

    Is it possible to call a class/servlet from a front-end web page (web page is in HTML form not java form) given that I created my servlet to be executed per class? If there is, can you give me a sample code snippet on how to do this?
    An example on how I call a class in my servlet:
    coordinate c = new coordinate();
    boolean a = c.plot(x,y);
    //do somethingBackground:
    I have already finished creating the server side code for a website and I chose to call a class inside the doPost() method. The class called will be responsible for executing the logic.
    The problem arrives when the web designer created a webpage that requires more than 1 function to be called per page. Since I'm using doPost() which requires the form to be submitted, is there a way to know which submit button is clicked and thus execute the correct function?
    I have a plan that I can fall back to which is to change my code so that it will read variables from the URL instead of thru a method call, but it will take more time since there are a lot of methods. I just thought I ask here if there is a way to accomplish the above so that I can save my code from this mess.
    Thanks,

    My servlet is structured in a way that it calls a method with values that it acquires from the webpage. (The initial plan was to enclose the HTML inside a servlet, but was changed so now I need to incorporate my servlets/services inside the HTML)
    Like in my example, on the coordinate class x and y are acquired from input boxes located in the web page then invoked the method plot(x,y). Since it will be HTML main and servlet sub, I need a way to call plot(x,y) from an HTML page. Or are you saying that my option would be to just create an intermediary servlet that would acquire the input and then call my class to process.

  • Problem with multiple Ajax calls to the same Servlet

    Hi,
    I am new to AJAX. I have a requirement where in, i have to make ajax calls to the same servlet in an infinite loop and check for an application context attribute to refresh the contents in the JSP.I am using the following script in JSP. The problem is i am not able to invoke the servlet more than one time.But I am able to go through the script at specific time interval using setInterval() function of Javascript and able to get alerts.But the problem is with xmlhttp.open("Get", url, true);. Its not getting called more than one time, even though i make multiple calls to the function.
    *<script type="text/javascript">*
    var xmlhttp
    var resp
    function fAjax()
    alert("Here");
    xmlhttp=null;
    resp=null;
    // code for Mozilla, etc.
    if (window.XMLHttpRequest)
    xmlhttp=new XMLHttpRequest();
    // code for IE
    else if (window.ActiveXObject)
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    if (xmlhttp!=null)
    xmlhttp.onreadystatechange=state_Change;
    xmlhttp.open("GET","/PSAPBackOffice/TestServlet",true);
    xmlhttp.send(null);
    else
    alert("Your browser does not support XMLHTTP.")
    function state_Change()
    // if xmlhttp shows "loaded"
    if (xmlhttp.readyState==4)
    // if "OK"
    if (xmlhttp.status==200)
         resp=xmlhttp.responseText;
         //alert(resp);
         if (resp=="CALL"){
         form.method="GET";
         form.action="/Project/Details.jsp          
    form.submit();
    else
    alert("Problem retrieving XML data")
    function callTimer(){
         setInterval("fAjax()",5000);
    *</script>*
    *Code for Servlet here:*
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
    ServletContext objContext= getServletContext();
         String value;
         synchronized (objContext) {
                   value=(String) objContext.getAttribute("Flag");
                        if(value==null){
                        else if(value.equals("Done")){
                             response.setContentType(CONTENT_TYPE);
                             PrintWriter out = null;
                                  try {
                                       out = response.getWriter();
                                  } catch (IOException e) {
                                       // TODO Auto-generated catch block
                                       e.printStackTrace();
                                                                } catch (NullPointerException npe) {
                                       // TODO Auto-generated catch block
                                       npe.printStackTrace();
                             objContext.setAttribute("Flag","No");
                             out.println("CALL");
    Can someone figureout the problem or mistake and help me out.Its urgent and please help me in this regard.Thanks in Advance !

    I'm not sure I'm following you. The mapping from URL to servlet can contain anything you want. So you could have the URL /blah/blah/blah that, with a mapping something like /blah/* would pass all requests with that URL pattern to your servlet - no one has to know it is a servlet. Your servlet could then parse the URL to see what it has to do or you could pass parameters as part of the URL or as hidden fields.

  • Write a servlet without doGet() and doPost() methods

    Hi,
    Can we write a servlet without doGet() and doPost() methods ?

    public class MyCoolServlet extends HttpServlet
    public void init(ServletConfig servletConfig) throws ServletException
    public void service(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
    // your code here
    }Just an example on how to do it.
    A servlet is loaded by server (before any request). It will run the init function. Then pick up an request, spawn a thread and put this servlet code into the thread, give it session, request and response objects, then call serivce.
    Remember that init is called before, outside the thread, while service is inside the thread and the last to be called. Nice place to put your code.
    If you need to have some sort of init function to be called first on every request PR USER, then make your own function, and call it first in service method.
    Stuff that are put in init() function might only get runned once in the entire server lifetime. Until restart.

  • DoGet() & doPost() methods in servlets

    If we have method=�Get� in <form> tag and the servlet is having only the doPost() method then how the servlet handles the request? Is it possible or not?
    If we have method=�Post� in <form> tag and the servlet is having only the doGet() method then how the servlet handles the request? Is it possible or not?

    Usually business logic for get and post requests is the same, so this managed with additional process method called from doGet() and doPost().
    Something like
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {...}
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            processRequest(request, response);
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            processRequest(request, response);
        }

  • Why Do We Have To Call super.init(config); in init() method of servlet?

    Hi, everyone..
    I wonder why we call super.init(config) in init method of servlet... If i dont call it ; when i try to get servletcontext in service method it throws java.lang.NullPointerException...when we call super.init() , what is happening behind the scene? If anybody has a technical explanation for my question , i will be very pleased...
    THX FOR YOUR FUTURE REPLIES IN ADVANCE....

    I am sorry about the uppercases and i dont want to seem smart on java forums... Anyway, m8 this is the thing that i know... i meant; for instance when we override doGet or doPost method ; we dont need to override init method; but the server loads the servlet and we can get the context of the servlet in these methods easily by calling getServletContext() method; however when we want to call service method implicitly by jndi, servlet needs to be loaded and init method must call its parent...(i also write down in web.xml <load-on-startup>.... for that servlet).
    thx for your replies in advance....

  • Servlet doPost() method and "HTTP Status 404 - /HelloPost" error

    hi all
    i've a problem with doPost(...) method. i use Tomcat4.1 version and in root folder i store Form.html where i use a doGet() method and in WEB-INI>>classes i store Hello.class file for doGet() method. it works normally. but when i write a Form1.html for doPost() method with "<FORM METHOD=POST ACTION="/HelloPost">" line and store as same folder as Form.html and HelloPost.class in WEB-INI>>classes folder. its not working and showing a error
    "HTTP Status 404 - /HelloPost"
    error type =Status error.
    message=/HelloPost
    description =The requested resource (/HelloPost) is not available
    if anyone of u know what the problem is.. then plz inform me... it will help me a lot to learn servlet.
    thnx a lot
    Arif

    Your post is very hard to read. The next time try to be more accurate.
    i store Form.html where i use a doGet() method That makes no sense.
    I think you have a form with method="GET"
    and in WEB-INI>>classes i store Hello.class file for doGet() method. you have a Servlet called Hello which handles doGet(Request, Response) calls and whose class file you've put into WEB-INF/classes
    but when i write a Form1.html for doPost() method with "<FORM METHOD=POST ACTION="/HelloPost">" line and store as same folder as Form.html and HelloPost.class in WEB-INI>>classes folderIt's not enough to put a class file which has the same name as the action of your form into the folder WEB-INF/classes. The class must implement the (Http)Servlet Interface and you have to configure the servlet in the web.xml file.
    From where did you get the working Hello example code ?
    Look at the Chapter 11: Java Servlet Technology of the J2EE 1.4 Tutorial to learn how to write Servlets.

  • Help : Calling a Servlet.doPost from a HTML Form (404 Error !!!)

    All
    I trying to make a call to a doPost method of a servlet from the doGet method of the same servlet.
    The call is made from an HTML form, so
    *<form name="input" action="servlet/deleteAlertPage" method="post">*
    ======================================================================
    The web.xml file entry is as follows:
    *<servlet>*
    *<servlet-name>deleteAlertPage</servlet-name>*
    *<servlet-class>bsp.perceptive.custom.webapp.deleteAlert.deleteAlertPage</servlet-class>*
    *<load-on-startup>0</load-on-startup>*
    *</servlet>*
    *<servlet-mapping>*
    *<servlet-name>deleteAlertPage</servlet-name>*
    *<url-pattern>/deleteAlertPage</url-pattern>*
    *</servlet-mapping>*
    So when I run my Servlet from my JDeveloper, I do see the “doGet” method getting executed successfully and I see my HTML from appearing on a browser page.
    As soon as I press the submit button, where I want the “doPost” method to get executed, I get the following error:
    Error 404--Not Found
    From RFC 2068 Hypertext Transfer Protocol -- HTTP/1.1:
    *10.4.5 404 Not Found*
    The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent.
    If the server does not wish to make this information available to the client, the status code 403 (Forbidden) can be used instead.
    The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource
    is permanently unavailable and has no forwarding address.
    Any ideas ? Is my Servlet Setup and Execution Correct ?
    Any help is appreciated.
    My JDeveloper Version is the latest release :
    About
    Oracle JDeveloper 11g Release 1 11.1.1.2.0
    Studio Edition Version 11.1.1.2.0
    Build JDEVADF_11.1.1.2.0_GENERIC_091029.2229.5536
    Copyright © 1997, 2009 Oracle and/or its affiliates. All rights reserved.
    IDE Version: 11.1.1.2.36.55.36
    Product ID: oracle.jdeveloper
    Product Version: 11.1.1.2.36.55.36
    Any help and advice is greatly appreciated.
    Regards
    patrice

    John
    I got it to work !!
    I had to place the application name in the action value also I had to change the port number, from 8080 to be 7101.
    However
    It was not that straight forward, because when I created my web Application I gave it the application Name of "BSPCustPerWebApps" and Project Name of "BSPCustPerWebApps"and this is reflected in my JDeveloper folder structure: "....\mywork\BSPCustPerWebApps\BSPCustPerWebApps\src\bsp\perceptive\custom\webapp\deleteAlert"
    now when I run my Servlet initially I noticed that Browser URL is saying : http://localhost:7101/BSPCustPerWebApps-BSPCustPerWebApps-context-root/deleteAlertPage
    which means that the web application is : BSPCustPerWebApps-BSPCustPerWebApps-context-root
    so I changed my action value to be
    action="http://localhost:7101/BSPCustPerWebApps-BSPCustPerWebApps-context-root/deleteAlertPage"
    and that worked.
    Weblogic must have created/defauled the application name using the application name and project name that I gave duriung the servlet creation.
    Is there a way of changing the application name to be something shorter and more meaningfull ?
    Also I did not want to hard code the server name, port etc in the action value, so again is there way of making this to be derived ?
    Do you know how to access the WebLogic Console ? , considering I have only installed JDev, which has an embedded weblogic server.
    Thanks for your help.

  • Synchronous versus Asynchronous Ajax calls

    Hello Apex gurus,
    I have a page which uses synchronous Ajax and seems that once in a while the browser freezes. I suppose this happens when the server takes a little longer to respond. I read this article:
    http://www.oreillynet.com/xml/blog/2007/01/do_sync_calls_freeze_browsers.html
    and I wanted to reproduce the test. So at the top of my on demand process I put
    DBMS_LOCK.sleep(10);
    I expected this to freeze the browser for about 10 sec but make no difference in terms of what the response is.
    It seems though that the response is null. I also have:
    EXCEPTION
    WHEN OTHERS THEN
    htp.p(SQLERRM);
    to capture any errors but no error message is returned either.
    Can somebody explain what is going on here and as a second question: if I make the synchronous call to asynchronous is this going to solve the browser freezing problem.
    George

    Hello,
    Please check if the following can help you –
    Re: Ajax and Threading
    Re: spinning/loading image for ajax call
    Regards,
    Arie.

  • Issue while making a AJAX call to a servlet in ALUI.

    Hi,
    The problem scenario is :
    I log into the portal using "http://147.149.132.93:7001/portal/server.pt"
    i have two instances of applications which have same files but provide different functionality one on 147.149.132.93 and other on 147.149.132.102 .
    I have configured my portlet that points to the application on 147.149.132.102 , when i make a ajax call to a servlet using the relative path for the aaplication , in normal scenario the ajax should make call to the servlert on the 147.149.132.102 but this does not happen and ajax makes call to the servlet on the machine 147.149.132.93 .
    Is there any issue regarding usage of Ajax in ALUI portal?
    Why the Ajax takes the server path from the portal login URL and not from the remote server configured for the portlet ? ?:|
    HELP !!!!!!!!!!!!!!!
    Regards,
    Prashant

    I m also facing same problem. I resolve the problem by simply giving >complete servlet address in ajax call.There are 2 issue with this:
    1) AJAX call will bypass portal, so it makes calls unsafe + you can not use portal functionality anymore. Plus some other issue like session expiration and so on.
    2) URL is hardcoded, so it's difficult to manage.
    All calls (include ajax) have to go through portal in portal environment. It means that AJAX url has to be gatewayed like any other url. There is no issue with ajax in portal. In G6 make sure that <inline> refresh checkbox (for WS) is unchecked.
    Here is example how to create AJAX URL on the fly by using Javascript. Let's say we have 2 files in root folder of <RemoteProjectName> web application:portlet.jsp file and ajaxExample.jsp.
    Code in portlet.jsp may looks like
    <script>
    var Url = "<pt:url xmlns:pt='http://www.plumtree.com/xmlschemas/ptui/' pt:href='ajaxExample.jsp'/>";
    </script>
    Here is what you can get as result of this transformation (based on data provided in first post):
    http://147.149.132.93:7001/portal/server.pt/gateway/PTARGS_0_0_XXX_XXX_X_XX/http%3B/147.149.132.102%3B/RemoteProjectName/ajaxExample.jsp
    where XXX - are numbers specific to particular portal environment.
    Edited by Bryazgin at 12/21/2007 7:43 AM

  • JSF 2.0 AJAX, calling method from commandButton

    I am trying to make an ajax call to a method in a backing bean when I click on a command button. In reality the method will persist or update my entity, but in this sample it will just compare a user and password and set a boolean. In the sample I would like to have the commandButton call "doLogin". Or add a second second commandButton that just calls the method by its self. TIA
    This is the form
            <h:form>
                <h:panelGroup id="edit2" >
                    <h:inputText id="editInput" value="#{StringHolder.str}" />
                    <br/>
                    <h:inputSecret id="inputPasswd" value="#{StringHolder.password}" />
                    <br/>
                    <h:outputText id="editOutput" value="#{StringHolder.str}" /><br/>
                    <h:selectBooleanCheckbox id="inOrNot" value="#{StringHolder.loggedIn}"/><br/>
                    <h:commandButton value="Submit" id="submit">
                        <f:ajax execute="editInput inputPasswd" render="editOutput inOrNot"/>
                    </h:commandButton><br/>
                </h:panelGroup>
            </h:form>This is the backing bean:
    @ManagedBean(name="StringHolder")
    @SessionScoped
    public class StringHolder {
        private String str;
        private String password;
        private boolean loggedIn;
        /** Creates a new instance of StringHolder */
        public StringHolder() {
         * @return the str
        public String getStr() {
            return str;
         * @param str the str to set
        public void setStr(String str) {
            this.str = str;
         * @return the password
        public String getPassword() {
            return password;
         * @param password the password to set
        public void setPassword(String password) {
            this.password = password;
         * @return the loggedIn
        public boolean isLoggedIn() {
            return loggedIn;
        public void doLogin() {
            if(str.equals("user") && password.equals("password")){
                loggedIn = true;
            } else {
                loggedIn = false;
    }

    Ok, I figured it out.
                    <h:commandButton value="Submit" id="submit" actionListener="#{StringHolder.doLogin}">
                        <f:ajax execute="editInput inputPasswd" render="editOutput inOrNot"/>
                    </h:commandButton><br/>

  • 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

Maybe you are looking for