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.

Similar Messages

  • 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.

  • Is it possible to use doGet() and doPost method in one jsp

    i am having a jsp form which will perform upload as well as download.There is a seperate servlet for download and upload.For downloading i use doGet method and doPost for the upload.how can i change the method dynamically for the above cases.

    Hi,
    in your jsp, if you call:
    request.getMethod();
    it should the string "GET" or "POST" depending on the HTTP method used, so you could do something like
    <%
    String httpMethod = request.getMethod();
    if ( "GET".equals(httpMethod) ) {
    // code to handle get requests
    else if ( "POST".equals(httpMethod) ) {
    // code to handle post requests
    %>
    I probably would of done it in a servlet(override doGet and doPost), or 2 seperate jsps
    Hope this helps
    Dominic

  • Difference Between doGet() and doPost

    Hi Everyone !!!
    I'm very new to servlets.I dont know what is the difference between doGet() and doPost() Method.
    Can anyone explain me .
    Can any give me details and differences between these two
    thanks in advance

    As you mention Why developer will use GET, if POST have all the advantages. Please look into, it may clear you doubts
    GET
    the GET type request is normally used for simple HTML page requests. The types of events that generate this type of request are clicking on a hyperlink, changing the address directly by typing in the address textbox on a browser or application that has HTML functionality, and submitting an HTML form where the method header is set to get as in method=get. Also, a GET request is triggered when selecting a favorite from the Favorites list and using JavaScript to change location.href. Usually the browser is configured to send a GET request even if no method is set explicitly by the HTML.
    The benefits of the GET method are
    1. It retrieves information such as a simple HTML page or the results of a database query.
    2. It supports query strings (name-value pairs appended to URL). Servers usually limit query strings to about      
         1024 characters.
    3. It allows bookmarks.
    POST
    This occurs when a browser or application submits an HTML form with the method attribute set to post as in method=post.
    The benefits of the POST method are
    1. It sends information to the server such as form fields, large text bodies, and key-value pairs.
    2. It hides form data because it isn't passed as a query string, but in the message body.
    3. It sends unlimited length data as part of its HTTP request body.
    4. It disallows bookmarks.
    Conclusion, always prefer to use GET, except mentioned in the following reason:
    1. If data is sensitive
    2. It is greater than 1024 characters
    3. If your application don't need bookmarks
    As because GET is more faster than POST.
    Both are used to send the request to the server, if you analyze than you may make the differnces like
    In the case of GET means send the request to get the simple HTML page from server whereas, in the case of POST means send the request to post the data to server.
    By Ausaf Ahmad
    Message was edited by:
    Genius_Brainware

  • How does SingleThreadModel handles doget and dopost?

    Hi,
    I have a requirement to synchronize the DB transactions but my servlet has doGet and doPost methods instead of service method.
    public class EMEATPRates extends HttpServlet implements SingleThreadModel{
    doGet(){
    synchronized(){
    ---Gets the data from DB and displayes on a page
    doPost(){
    synchronized(){
    ----saves the changes to the DB
    I need to get a lock when an user requests for page(doGet()) and release the lock only after he saves it(doPost).
    Does SingleThreadModel handles this?

    HTTP GET requests submit any form parameters within the URL of the request itself. HTTP POST requests submit any form parameters within the HTTP message body. Let's say you have two forms for a logon screen:
    userid, password
    HTTP GET: http://localhost:8080/LoginServlet?userid=foo&password=bar
    [http headers]
    [http body (empty)]
    HTTP POST: http://localhost:8080/LoginServlet
    [http headers]
    userid=foo&password=bar
    Clearly, for something like a logon screen, you would want to POST (no need to see the user's password in a URL if someone walks by). Otherwise, the implementation is up to you. I personally like cleaner-looking URL's, so I usually POST.
    - Saish

  • DoGet() and service() method differences in servlets

    can you give the differences between doGet() and service() methods in servlets. where to use doGet() and where to use service()
    thanks

    service() is called whenever the Servlet gets a HTTP request. Per default it calls the correct do<METHOD>() method.
    So doGet() is only called when you get a GET request via HTTP. For POST (for example) doPost() will be called instead.

  • 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~

  • How to Submit doGet and doPost request using javascript ?

    Hi,
    My requirement is:
    Need to submit form to two different methods doGet and doPost.
    doGet will authenticate the request by asking to enter username and password.
    After successful authentication we need to call doPost to submit the data of form.
    I tried using Get(url); and Post(url,data,type); methods of FormCalc but i am not able to retrive the attribute and its value using Post.
    my FormCalc script is
    Get("https://server:port/servlet"); //I am able to call doGet method successfully
    Post("https://server:port/servler","user=abcd&password=123456"); //I am able to call doPost method but I am not able to retrive the attribute user and password in doPost method.
    i tried request.getAttribute("user"); and also i tried request.getParameter("user");
    both are coming as null. How to submit form data to doPost method of servlet.
    Also I would like to know is there any javascript for the same.

    Why do you want to use javascript..? Why not action listener..? You can check whether its an empty string by checking
    if(str != null && !str.equals("")) {..}
    where str is the variable for inputText value.
    If this is not helpful, do provide more details on which version of JDev you are using and what are you trying (your usecase).
    regards,
    ~Krithika

  • The Differrence between doget and dopost

    doget and dopost are urally used in the same class, but the function which afford seem the same. Except that doget resposes get, dopost responses post, what are the other or real difference between them?
    Can E-Mail:[email protected]

    difrent is between send param option in HTTP protocol
    if you use GET method param send in URL You can see http://something?param=1&param2=1
    if you use POST method param send in body You can't see param in URL
    if you want use doGet for both method (GET,POST) you have to write
    public void doPost(...){
    doGet(...);
    public void doGet(...){
    your code
    Siplo

  • DoGet(,) and doPost(,)

    doGet(request,response) throws Exception
    doPost(request,repsonse);
    when it is use full,when i have seen one project in it is like that what is that
    what it mean exactly please.

    Here doGet() will always get invoked by default . You cannot invoke a doPost() if you have not done expilicity .Here in your case you are invoking a doGet and then in turn doPost.
    doGet is called in response to an HTTP GET request. This happens when users click on a link, or enter a URL into the browser's address bar. It also happens with some HTML FORMs (those with METHOD="GET" specified in the FORM tag).
    doPost is called in response to an HTTP POST request. This happens with some HTML FORMs (those with METHOD="POST" specified in the FORM tag).
    Both methods are called by the default (superclass) implementation of service in the HttpServlet base class. You should override one or both to perform your servlet's actions. You probably shouldn't override service().
    A GET request is a request to get a resource from the server. This is the case of a browser requesting a web page. It is also possible to specify parameters in the request, but the length of the parameters on the whole is limited. This is the case of a form in a web page declared this way in html: <form method="GET"> or <form>.
    A POST request is a request to post (to send) form data to a resource on the server. This is the case of of a form in a web page declared this way in html: <form method="POST">. In this case the size of the parameters can be much greater

  • About DoGet() and DoPost()

    {color:#0000ff}Hi Guys,
    I have one doubt in my mind,
    That is,
    In an HTTP Based servlets We are going to Override doGet() or doPost() depend on the request come from the user,
    if it is a POST data then we are going to Override doPost (), or if it is a GET data then we are going to implement(),
    *{color:#ff0000}But how can the servlet or we knows that the data is POST data or GET data...{color}*
    Can anybody clarify this please
    Thank q so much in advence.{color}

    1) Assume all requests are GET (all <a href ...> links and direct URL access requests are GET)
    2) POST occurs when the CLIENT submits a form whose method is POST
    ex: <form action="servlet" method="post">
    3) Sometimes, direct URL connections are established as POST requests as well
    The server knows because the client is required to define the request METHOD when making a request via a header attribute. The Servlet container reads the attribute, calls the proper doXXX method, and gives you access to the method via request.getMethod()

  • Query on doGet() and doPost()

    Can i synchronized doGet(), or doPost().
    If yes how ,please give some suggestion on this
    Thank u

    Thanks ,
    iam ok for ur answer.but my doubt is
    I have only either doPost() or doGet() method in my servlet program can i make that method as synchronized without implemnting the SingleThreadModel concept.
    I Think u r clear about my doubt ..if u know answer for this please help me.
    Thank u

  • Whats the use of doget and dopost

    hi
    whats the use of doget and dopoast when same work can be done by sevice alone?
    Message was edited by:
    pooja_k_online

    Try looking at the Tomcat implementation of HttpServlet.service() method. I have pasted it below, if you look at the service() method all it does is to check for the method and call the appropriate method. It is not recommended to override the service method. It is a good practice to only override the getXXX() methods.
    protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    String method = req.getMethod();
    if(method.equals("GET"))
    long lastModified = getLastModified(req);
    if(lastModified == -1L)
    doGet(req, resp);
    } else
    long ifModifiedSince = req.getDateHeader("If-Modified-Since");
    if(ifModifiedSince < (lastModified / 1000L) * 1000L)
    maybeSetLastModified(resp, lastModified);
    doGet(req, resp);
    } else
    resp.setStatus(304);
    } else
    if(method.equals("HEAD"))
    long lastModified = getLastModified(req);
    maybeSetLastModified(resp, lastModified);
    doHead(req, resp);
    } else
    if(method.equals("POST"))
    doPost(req, resp);
    else
    if(method.equals("PUT"))
    doPut(req, resp);
    else
    if(method.equals("DELETE"))
    doDelete(req, resp);
    else
    if(method.equals("OPTIONS"))
    doOptions(req, resp);
    else
    if(method.equals("TRACE"))
    doTrace(req, resp);
    } else
    String errMsg = lStrings.getString("http.method_not_implemented");
    Object errArgs[] = new Object[1];
    errArgs[0] = method;
    errMsg = MessageFormat.format(errMsg, errArgs);
    resp.sendError(501, errMsg);
    }

  • Using doGet and doPost in a jsp

    Hi, I have not clear about which method is called in a jsp page, well, I think it's _jspService, but I would like to know how to instruct my jsp to execute doPost or doGet depending on the method used by the calling form. Should I call request.getMethod() first? But request in a Jsp is a ServletRequest, not a HttpServletRequest. Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Actually, it is a HttpServletRequest. You can use request.getMethod() in your JSP page.

  • Java Socket bind() and connect() method

    Hi,
    I'm running a windows xp machine and have set it up (using the raspppoe protocol) to make simultaneous dial-up connections to the internet. Each of these dial-up connections then has its own IP address.
    When I create a new Socket, bind it to one of these IP addresses and invoke the connect() method (to a remote host), the socket times out. Only when i bind it to the most recent dial-up connection that has been established, the socket connects.
    I'm welcome for any ideas :)
    thanks

    If you'll excuse the lengthy post it has alot of code and outputs :)
    Ok Wingate really doesnt have much to do with the program, let me get back to the point and then post the code I have.
    Goal of the application:
    To use multiple simultaneous dial-up interfaces connected to the internet by binding each of them (using Socket class .bind() method) to its associated Socket object.
    Method:
    I use the RASPPPOE protocol for Windows XP to allow these multiple simultaneous ADSL dial-up connections. Each of these dial-up instances gets assigned an IP address. I use the NetworkInterface class to retrieve these interfaces/IP addresses and then run a loop to bind each Socket to its associated interface.
    The code I am pasting here is over-simplified and is just to illustrate what it is i'm trying to do.
    Firstly, this is a cut & paste of the tutorial from the Java website on how to list the Network interfaces on an operating system and the associated output:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import static java.lang.System.out;
    public class ListNIFs
        public static void main(String args[]) throws SocketException
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();       
            for (NetworkInterface netint : Collections.list(nets))
                displayInterfaceInformation(netint);       
        static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
            out.printf("Display name: %s\n", netint.getDisplayName());
            out.printf("Name: %s\n", netint.getName());
            Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();       
            for (InetAddress inetAddress : Collections.list(inetAddresses))
                out.printf("InetAddress: %s\n", inetAddress); 
            out.printf("Up? %s\n", netint.isUp());
            out.printf("Loopback? %s\n", netint.isLoopback());
            out.printf("PointToPoint? %s\n", netint.isPointToPoint());
            out.printf("Supports multicast? %s\n", netint.supportsMulticast());
            out.printf("Virtual? %s\n", netint.isVirtual());
            out.printf("Hardware address: %s\n", Arrays.toString(netint.getHardwareAddress()));
            out.printf("MTU: %s\n", netint.getMTU());       
            out.printf("\n");
    }For which the output is:
    Display name: MS TCP Loopback interface
    Name: lo
    InetAddress: /127.0.0.1
    Up? true
    Loopback? true
    PointToPoint? false
    Supports multicast? true
    Virtual? false
    Hardware address: null
    MTU: 1520
    Display name: Intel(R) PRO/Wireless 3945ABG Network Connection - Packet Scheduler Miniport
    Name: eth0
    InetAddress: /192.168.1.10
    Up? true
    Loopback? false
    PointToPoint? false
    Supports multicast? true
    Virtual? false
    Hardware address: [0, 25, -46, 93, -13, 86]
    MTU: 1500
    Display name: WAN (PPP/SLIP) Interface
    Name: ppp0
    InetAddress: /196.209.42.125
    Up? true
    Loopback? false
    PointToPoint? true
    Supports multicast? true
    Virtual? false
    Hardware address: null
    MTU: 1492
    Display name: WAN (PPP/SLIP) Interface
    Name: ppp1
    InetAddress: /196.209.248.25
    Up? true
    Loopback? false
    PointToPoint? true
    Supports multicast? true
    Virtual? false
    Hardware address: null
    MTU: 1492
    Display name: WAN (PPP/SLIP) Interface
    Name: ppp2
    InetAddress: /196.209.249.4
    Up? true
    Loopback? false
    PointToPoint? true
    Supports multicast? true
    Virtual? false
    Hardware address: null
    MTU: 1492The part to take notice of is the three WAN (PPP/SLIP) Interfaces named ppp0, ppp1 and ppp2. They are simultaneous dial-up connections to the internet, each with a unique IP. I will now attempt to use one of these interfaces to establish a connection to www.google.com on port 80 (purely for illustration).
    In the code printed below, I simply hard coded the above listed IP address of the interface for simplification:
    import java.net.*;
    import java.io.*;
    public class SockBind {
         private Socket connection;     
         private void start() throws IOException
              while (true)
                   try {
                        connection = new Socket();
                        connection.bind(new InetSocketAddress("196.209.42.125", 12345));
                        connection.connect(new InetSocketAddress("www.google.com", 80));
                        connection.close();
                   } catch (SocketException e) {
                        System.err.println(e.getMessage());
         public static void main(String args[])
              try {
                   SockBind s = new SockBind();
                   s.start();
                   System.out.println("Program terminated.");
              } catch (IOException e) {
                   e.printStackTrace();
                   System.exit(1);
    }Once the program reaches the connection.connect() method, it pauses a while until it throws a SocketException with a "timed out" message. I have already tested the dial-up connection (using a wingate, which is irrelevant) just to confirm that the connection is in working order.
    EJP if you have any suggestions I will welcome it, many thanks :)

Maybe you are looking for