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);
    }

Similar Messages

  • Can we can doGet/doPost method in jsp explicitly

    Hi All Experts,
    I want to know whether i can call doGet/doPost method
    explicitly in JSP? Because when JSP is converted to servlet
    it automatically generates _jspSevice method only.
    Thanx in Advance
    Pradipto

    I don't know of a compile-time check for that type of need, but, at runtime, you could use:
    if (!(request.getMethod().equals("POST"))
      throw new UnsupportedHTTPMethodException("Only HTTP POST requests supported");however, it's almost always better to submit a form to a servlet rather then a JSP, so you may want to rethink your design. Typically, you want nothing other then display logic in a JSP with validation, navigation control and more in a servlet, but, to each his/her own, I suppose. Take care.

  • Database connection not closed in Destroy()  method of servlet

    Hi,
    I have a problem with my deployed web application. At first, I thought Glassfish was messing up on me, and after checking the log I could see plenty of null pointer exceptions being thrown at lines in my code where I generate prepared statements from my connection object. I have been initialising my connection in the Init() method of all my classes, and equally, I've been closing it in Destroy(). I can only imagine that destroy() isn't being called - since the log clearly shows "connection success" messages but not "connection closed" messages. I am connecting to the servlets via a J2ME app on my mobile phone. Does connecting in this way somehow not invoke the destroy method when the servlets work is complete? Am I going to need to move all my connection initilisation and closing into the necessary doGet/doPost methods of each of my servlets?
    Chris

    You shouldn't be keeping the connection that long open. It's a bad design. It will timeout sooner or later and your complete application will crash. Always acquire and close the connection in the shortest possible scope, preferably just in the same method block where you process the query and/or results. If you want to improve performance while connecting, consider using a connection pool.
    Back to the actual problem: a servlet is created only once during application's lifetime and not during every request as you appears to think.
    You may find this tutorial useful to read on about using the DAO pattern in JSP/Servlet.
    [http://balusc.blogspot.com/2008/07/dao-tutorial-use-in-jspservlet.html]

  • Ned help  from java developer init() doGet(),doPost()

    Where do we create Databse connection in servlet in all the init() doGet(),doPost() method and why
    Appericite your help

    Here are the steps at high level to follow to obtain database connection in your web app -
    Configure connection pool(s) and data sources for the container on which your app is going to be deployed.
    Specify the names of the datasources to be used in the deployment descriptor of your app.
    Look up the datasource using JNDI APIs and get a connection from it.

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

  • Servlet Methods - doGet, doPost

    Hi,
    I understoot that GET request -> doGet(), POST request-> doPost() methods are overrids by the HttpServlets....
    do we need to use both methods in the Servlets class..?
    For example, I am sending POST request into the Servlets class... so i can override only doPost()  method to handle the client inputs

    There they are just for?
    Just read the HttpServlet API [1] documentation. It shall be clear. If you don't understand the HTTP spec [2] either, I highly reommend you to read that too.
    [1] http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServlet.html
    [2] http://www.w3.org/Protocols/rfc2616/rfc2616.html

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

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

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

  • Who calls doget() method of servlet

    hello all,
    i have typical customized webserver.
    the problem i have with that is when i configure it with IP address and when i send a request through browser using HOST NAME ,its not recognizing.
    the same happens vice versa
    that is : set up host name in the http server, and when try a request through IP Address using a web browser.
    can any body clear me who calls the doGet() method of servlet. if it is USER AGENT of web browser, is there any operation executes between
    USER AGENT - DoGet() method of servlet?
    regards
    R
    Message was edited by:
    LoveOpensource

    The servlet is on the server, the browser is on the client, so, do it think it possible (unless the browser is written in Java and does it's browsing with RMI, which is patently absurd) that the browser call doGet()?
    It is rather obvious, that the browser sends an HTTP request to the Application Container (or a web server such as apache which then uses some module to communicate with the Application Container, but the end effect is the same), and that Application Container calls the doGet() method.
    Edit: And man am I slow and "wordy".

  • Calling a method of servlet

    How to call a method of servlets like we do in struts like "get.do?method=getData". I know servlets are called defacult method either dopost or doget are called but can i call any other in the servlet and if yes how can i do that?

    May be your servlet is not able to lookup the EJB. You can use some print statements and see whether lookup ok or not.
    Just a guess.
    Plese get back, if any queries.
    Thanks,
    Rakesh.

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

  • Serialization of DOM Tree+calling POST method in servlet

    Hi all,
    I am trying to serialize a DOM tree and send it from an applet to a servlet..I am having difficulty in calling the post method of the servlet..can anyone please tell me how the POST method in the servlet is called from the applet...I am using the code as seen on the forum for calling the POST method as below:
    URL url = new URL("http://localhost:8080/3awebapp/updateservlet");
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.setUseCaches(false);
    con.setRequestProperty("Content-Type","application/octet-stream");
    System.out.println("Connected");
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    System.out.println("do output called");
    con.setDoInput(true);
    System.out.println("do Input called");
    ObjectOutputStream objout = new ObjectOutputStream(con.getOutputStream());
    yet the post method in the servlet does not seem to be called....
    another problem I had was trying to serialize a DOM document and send it to the servlet. I am using the following code to write the DOM document on an output stream..would this work:
    OutputFormat format = new OutputFormat(document);
    XMLSerializer serializer = new XMLSerializer( objout, format );
    System.out.println("XML Serializer Started");
    DOMSerializer newSerializer=serializer.asDOMSerializer();
    newSerializer.serialize( document );
    objout.flush();
    objout.close();
    ...since the doPost method of the servlet is not being called I do not whether the above code would be sent to the servlet..
    Any advice on the above two matters would be highly appreciated..
    Fenil

    perhaps my piece of code may help You - relevant parts marked //<--,
    but I have a problem when reading my object - which is a serialized DomTree :
    Variant 1 : sending XML-data as string will arrive as should be, but parser says org.xml.sax.SAXParseException (missing root-element)
    Variant 2 : readObject says java.io.OptionalDataException, but the DomTree will be parsed and displayed
    -- snipp --
    import java.io.InputStream;
    import org.w3c.dom.Document;
    import java.net.*;
    import com.oreilly.servlet.HttpMessage; //<--
    import java.util.*;
    import java.io.ObjectInputStream;
    myApplet :
    try {
         URL url = new URL(getCodeBase(),"../../xml/FetchDocument");
         HttpMessage msg = new HttpMessage(url);
         Properties props = new Properties();
         props.put("InputFeldName","FeldWert");
         InputStream in = msg.sendGetMessage(props);
    //<-- alt : sendPostMessage
         ObjectInputStream result = new ObjectInputStream(in);
         try {
         Object obj = result.readObject();
    myServlet :
    public void doGet(HttpServletRequest req,HttpServletResponse res)
         throws ServletException, IOException {
    TreeCreator currentTree = new TreeCreator();
    ObjectOutputStream out = new ObjectOutputStream(res.getOutputStream());
    -- variant 1 :
    out.writeObject(currentTree.skillOutputString());
    out.flush();
    out.close();
    -- variant 2 :          
    OutputFormat( TreeCreator.cdi ); //Serialize DOM
    OutputFormat format = new OutputFormat( currentTree.getCDI() ); format.setEncoding("ISO-8859-1");
    XMLSerializer serial = new XMLSerializer( out, format );
    serial.asDOMSerializer(); // As a DOM Serializer
    serial.serialize( currentTree.getCDI().getDocumentElement() );
    serial.endDocument();
    out.flush();
    out.close();

  • Hi, what is default method in servlets?

    hi,
    i am not mentioned any method in my servlet program,
    so what is the default method either get or post?
    jp

    Hi
    If you what to provide the same stuff for both
    POST/GET HTTP request you can use the service method:
    public void service(ServletRequest req,
    ServletResponse res)
    throws ServletException,java.io.IOException /Tobiaswhen reading 'More Servlets And Java Server Pages' you are discouraged to use service(), unless you want to do some of the preprocessing yourself. (sorry, I don't exactly, what is done before doGet()/doPost() are called...)

  • Methods in Servlets

    I want to seperate my html display output from my programs logic. In an application I would just make a method to do this. I have had a problem doing this with my servlet. I get the error is:
    BP_Test.java:32: missing method body, or declare abstract
         private void displayDetails ( HttpServletResponse resp,
    I have defined the method as follows:
         private void displayDetails ( HttpServletResponse resp,
                                                      int empNo );
              resp.setContentType ( "text/html" );
              PrintWriter out = resp.getWriter ();
              out.println ( "<HTML>\n<HEAD>" );
    I call the method as follows within a doPost method:
    displayDetails ( response, employeeNo );
    If any one could give me any help I would be very grateful.
    Bronek

    private void displayDetails ( HttpServletResponse resp,int empNo );Right here you have a semi-colon after the method declaration, so it's not seeing the body of the method below. Removing the semicolon should fix it.
    David Black
              resp.setContentType ( "text/html" );
              PrintWriter out = resp.getWriter ();
              out.println ( "<HTML>\n<HEAD>" );

Maybe you are looking for

  • OSB: send dateTime do Java Callout method

    Hi, I have a method in Java that receives a parameter of type java.util.Date and I want to invoke that method in an OSB Java Callout Activity. I receive in the OSB 11g service input an element of type xs:dateTime and I want to send it to the Java met

  • Automated batch

    Hi all, How the batch is generated automatically In Good receipt? In PO we are not entering the batch. Plz suggest. Arati.

  • Elements 6 and iPhoto

    I am trying to open a file(photo) in Elements 6 straight from iPhoto. Every time I try to access an event it hangs up, when I go look in a folder and select an image they disapear, again I have to force quit to get out. Is there an issue between iPho

  • Why not work [timeSelectorListener]  at [dvt:graph] (version 11g)

    I am practicing ADF Data Visualization sample written by Katarina Obradovic-Sarkic. http://www.oracle.com/technology/products/jdev/11/how-tos/dvt_how_tos/adf_dvt_graph_howto.html I cant' show the TimeSelector in the Graph. [ richGraphTimeSelector.jsp

  • Select XMLElement - want some whitespace or newlines!

    Hi - I'm using XML SQL psuedo functions to make an XML document. It's making valid XML, but it's hideous to read. The SQL select is actually a select ... into in a PL/SQL function. Is there any way to force some newlines or spaces after the end tags,