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

Similar Messages

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

  • 'Error: 500 SC_INTERNAL_SERVER_ERROR' after init() and before doGet() method in servlet.

    Hi to you all,
    I have been working with ias6.0 sp2 on Unix.
    I have a simple web application with servlets and packaged auxiliary classes. Deployment seems all good. But when I try to call my first servlet with URL, I get this message on the navigator : "Error: 500 SC_INTERNAL_SERVER_ERROR
    null ".
    In the log file, I have that :
    "error: Exception: SERVLET-execution_failed: Error in executing servlet myServlet: java.lang.NullPointerException [...]
    at com.netscape.server.servlet.servletrunner.ServletInfo.checkAuthorization (Unknown source)
    error: APPLOGIC-caught_exception: Caught Exception:
    java.lang.NullPointerException
    at com.netscape.server.servlet.servletrunner.ServletInfo.popPrincipalFromTLD (Unknown source )
    My application works well with iws. So, what's up ?
    The init() method is executed, but not the doGet() one.
    Well, hear you soon !
    Paul-Emile

    Hi,
    Although it is difficult to point out the place where the error exactly occurs, I can suggest the reasons. The possible place for error to occur normally lies in the database connectivity. When the HttpServlet is not able to communicate with the database or encountered errors while communicating with the database. Please let me know if this helps.
    Regards
    Raj

  • 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();

  • DoGet() method is being called every 3inutes repetitively in servlet

    HI,
    There are 2 managed servers in one unix box.
    i have one war application deployed in cluster level. This war application will search the logs and will give particular content as a result.
    The Jsp page will send the request and it is able to get the correct results if the operation completes within 3 minutes. if there are so many logs, it is giving unreliable results as war application is sending the request again and again in the interval of 3 mins.
    Request parameters are getting by servlet, and this servlet will create the unix shellscript in background and it will execute in a box.
    0-3 mins 1st .sh creating and executing..
    3-6 mins 2nd .sh creats and starts the execution, once the 1 one is completed...
    its becomes infinite loop...
    after some time Browser is going to diagnostic error state..
    i did debugging there i can see doGet method of servlet is being called for every 3 minutes..
    to avoid this i tried to give some parameters in weblogic.xml file...but its not working..
    please fine below weblogic.xml file
    ====================================
    <?xml version='1.0' encoding='UTF-8'?>
    <weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.2/weblogic-web-app.xsd">
    <session-descriptor>
    </session-descriptor>
    <jsp-descriptor>
    <page-check-seconds>-1</page-check-seconds>
    <debug>true</debug>
    </jsp-descriptor>
    <container-descriptor>
    <resource-reload-check-secs>-1</resource-reload-check-secs>
    <servlet-reload-check-secs>-1</servlet-reload-check-secs>
    <prefer-web-inf-classes>true</prefer-web-inf-classes>
    </container-descriptor>
    <logging>
    <log-filename>/wls_domains/b2borap2/application_MT/logs/messagetracker.log</log-filename>
    </logging>
    </weblogic-web-app>
    =======================================================
    and web.xml file is
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <listener>
    <listener-class>
    com.tm.messagetracker.listeners.MTrackerSession
    </listener-class>
    </listener>
    <servlet>
    <servlet-name>Controller</servlet-name>
    <servlet-class>com.tm.messagetracker.Controller</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>Controller</servlet-name>
    <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <session-config>
    <session-timeout>30</session-timeout>
    </session-config>
    <mime-mapping>
    <extension>txt</extension>
    <mime-type>text/plain</mime-type>
    </mime-mapping>
    <mime-mapping>
    <extension>html</extension>
    <mime-type>text/html</mime-type>
    </mime-mapping>
    <mime-mapping>
    <extension>htm</extension>
    <mime-type>text/html</mime-type>
    </mime-mapping>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
    =========================================
    please find the servlet code..
    public class Controller extends HttpServlet
    public void init()
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
         System.out.println("Iam at doGet");
    res.setContentType("text/html");
    HttpSession session = req.getSession (false);
    if (session==null) {
         // We Send a Redirect
         res.sendRedirect("./../pages/login.jsp");
    //HttpSession session = req.getSession(true);
    boolean loginTravelled = new Boolean((String)session.getAttribute("loginTravelled")).booleanValue();
    UserVerification uv = new UserVerification();
    MTUtils mTUtils = new MTUtils();
    Properties systemProps = SerializeProperties.doLoad();
    int noOFrecordsPerPage = 10;
    if (loginTravelled)
         System.out.println("loginTravelled value :"+loginTravelled);
    String pageId = req.getParameter("pageId");
    String actionId = req.getParameter("actionId");
    if (actionId.equals("logout"))
    session.removeAttribute("CompleteSearchRecords");
    session.removeAttribute("DisplaySearchRecords");
    session.invalidate();
    System.gc();
    res.sendRedirect("./../pages/login.jsp");
    else if (pageId.equals("faq"))
    if (actionId.equals("homepage"))
    System.gc();
    res.sendRedirect("./../pages/login.jsp");
    else if (actionId.equals("download"))
    String fileName = req.getParameter("fileName");
    String originalFileName = req.getParameter("originalFileName");
    doDownload(req, res, fileName, originalFileName);
    else if (pageId.equals("login"))
    if (actionId.equals("downloads"))
    List downloadListRecords = null;
    try
    downloadListRecords = DownloadableRecords.getDownloadableRecords(new File(systemProps.getProperty("faq")));
    catch (Exception e)
    e.printStackTrace();
    session.setAttribute("DownloadListRecords", downloadListRecords);
    res.sendRedirect("./../pages/downloads.jsp");
    else if (actionId.equals("userlogin"))
    String userId = req.getParameter("uname").trim();
    String password = req.getParameter("passwd").trim();
    if ((userId != null) && (userId.length() > 0) && (password != null) && (password.length() > 0))
    if ((userId.equals("superadmin")) && (password.equals("superadmin")))
    res.sendRedirect("./../pages/admin.jsp");
    String userAuthMsg = UserVerification.verifyUser(userId, password);
    if (userAuthMsg.equals("adminuser"))
    res.sendRedirect("./../pages/admin.jsp");
    else if (userAuthMsg.equals("guestuser"))
    res.sendRedirect("./../pages/search.jsp");
    else if (userAuthMsg.equals("wrongpassword"))
    res.sendRedirect("./../pages/login.jsp?userAuthDispMsg=Sorry wrong password");
    else if (userAuthMsg.equals("unauthorizeduser"))
    res.sendRedirect("./../pages/login.jsp?userAuthDispMsg=User is not Authorized ");
    else if ((userAuthMsg.equals("adminpropsNotFound")) || (userAuthMsg.equals("guestpropsNotFound")))
    res.sendRedirect("./../pages/error.jsp?userAuthDispMsg=user configurations not found , Please contact admin");
    else
    res.sendRedirect("./../pages/login.jsp?userAuthDispMsg=UserName or password cannot be null");
    else if (pageId.equals("adminPage"))
    if (actionId.equals("adduser"))
    CommonProperties adminProps = MTrackerProperties.getAdminProps();
    CommonProperties guestProps = MTrackerProperties.getGuestProps();
    String userId = req.getParameter("adduname").trim();
    String password = req.getParameter("passwd").trim();
    String userAuthMsg = uv.verifyUser(userId);
    if (userAuthMsg.equals("adminuser"))
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=Admin user with name exists");
    else if (userAuthMsg.equals("guestuser"))
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=Guest user with name exists");
    else
    String userType = req.getParameter("usertype").trim();
    if (userType.equals("admin"))
    adminProps.addProperty(userId, password);
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=User " + userId + " added successfully");
    else
    guestProps.addProperty(userId, password);
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=User " + userId + " added successfully");
    else if (actionId.equals("deleteuser"))
    CommonProperties adminProps = MTrackerProperties.getAdminProps();
    CommonProperties guestProps = MTrackerProperties.getGuestProps();
    String userId = req.getParameter("deluname").trim();
    String userAuthMsg = uv.verifyUser(userId);
    if (userAuthMsg.equals("adminuser"))
    adminProps.deleteProperty(userId);
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=Admin user " + userId + " deleted");
    else if (userAuthMsg.equals("guestuser"))
    guestProps.deleteProperty(userId);
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=Guest user " + userId + " deleted");
    else
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=User " + userId + " does not exists ");
    else if (actionId.equals("updatescript"))
    String perlScriptLoc = req.getParameter("perlloc").trim();
    SerializeProperties.doSave(perlScriptLoc);
    try
    Thread.sleep(2500L);
    catch (InterruptedException e) {
    e.printStackTrace();
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=Perl script location updated with -> " + perlScriptLoc);
    else if (actionId.equals("updatepropertyfile"))
    String propfileLoc = req.getParameter("proploc").trim();
    SerializeProperties.doSave(propfileLoc);
    try
    Thread.sleep(2500L);
    catch (InterruptedException e) {
    e.printStackTrace();
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=Property file location updated with -> " + propfileLoc);
    else if (actionId.equals("searchLink"))
    res.sendRedirect("./../pages/search.jsp");
    if (actionId.equals("cleanup"))
    String resultsDir = systemProps.getProperty("results");
    mTUtils.deleteFiles(new File(resultsDir), 24);
    res.sendRedirect("./../pages/admin.jsp?userAuthDispMsg=Cleanup Done !!!");
    else if (pageId.equals("searchPage"))
         System.out.println("Start searching process Here");
         if (actionId.equals("search"))
         System.out.println("Started searching process");
    String tboxValue = req.getParameter("tbox");
    String tareaValue = req.getParameter("tarea");
    String SearchString = "";
    String auditEnable = req.getParameter("audit");
    String errorEnable = req.getParameter("error");
    String debugEnable = req.getParameter("debug");
    String srchStartDate = req.getParameter("srchstartDate");
    String srchEndDate = req.getParameter("srchendDate");
    String srchInZipFile = "";
    if (req.getParameter("srchInZipFile") != null) {
    srchInZipFile = req.getParameter("srchInZipFile");
    String mode = req.getParameter("inputmode");
    try
    if (req.getParameter("recordsPerPage") != null)
    noOFrecordsPerPage = new Integer(req.getParameter("recordsPerPage")).intValue();
    catch (Exception e)
    res.sendRedirect("./../pages/error.jsp?userAuthDispMsg=recordsPerPage should be a number");
    if (mode.equals("single"))
    SearchString = tboxValue;
    else
    SearchString = tareaValue;
    String inputDir = systemProps.getProperty("inputs");
    String resultsDir = systemProps.getProperty("results");
    String inputFileName = new Integer(mTUtils.getRandom()).toString();
    File inputParams = new File(inputDir + "/" + inputFileName + ".properties");
    File inputTxt = new File(inputDir + "/" + inputFileName + ".txt");
    synchronized (inputParams) {
         System.out.println("inputParams"+inputParams);
    synchronized (inputTxt)
         System.out.println("inputtxt"+inputTxt);
    boolean saved = false;
    CommonProperties singleSerProps = new CommonProperties(inputParams);
    Properties searchProps = new Properties();
    searchProps.setProperty("search_from_date", srchStartDate);
    searchProps.setProperty("search_to_date", srchEndDate);
    searchProps.setProperty("force_zip_search", srchInZipFile);
    if ((SearchProperties.saveSingeSearchProps(singleSerProps, searchProps)) && (SearchProperties.saveSearchFile(inputTxt, SearchString)))
    if (mTUtils.genarateScript(auditEnable, debugEnable, errorEnable, srchInZipFile, inputFileName))
    if (mTUtils.runScript("sh", inputFileName))
    List tRecords = null;
    TrackingLogReader treader = new TrackingLogReader();
    try
    tRecords = treader.getRecords(new File(resultsDir), inputFileName);
    catch (Exception e)
    e.printStackTrace();
    if (tRecords == null)
    tRecords = new ArrayList();
    tRecords.add("No Records Found");
    String backEnb = "";
    String nextEnb = "";
    int fromRec = 0;
    int toRec = 0;
    if (tRecords.size() > noOFrecordsPerPage)
    toRec = noOFrecordsPerPage;
    backEnb = "false";
    nextEnb = "true";
    else
    toRec = tRecords.size();
    backEnb = "false";
    nextEnb = "false";
    List subList = tRecords.subList(fromRec, toRec);
    session.setAttribute("CompleteSearchRecords", tRecords);
    session.setAttribute("DisplaySearchRecords", subList);
    session.setAttribute("fromRec", new Integer(fromRec));
    session.setAttribute("toRec", new Integer(toRec));
    session.setAttribute("nextEnb", nextEnb);
    session.setAttribute("backEnb", backEnb);
    session.setAttribute("recsPerPage", new Integer(noOFrecordsPerPage));
    res.sendRedirect("./../pages/SearchResults.jsp");
    else {
    res.sendRedirect("./../pages/error.jsp?userAuthDispMsg=Problem in calling PERL system , Please contact admin");
    else
    res.sendRedirect("./../pages/error.jsp?userAuthDispMsg=Script not generated , Please contact admin");
    else
    res.sendRedirect("./../pages/error.jsp?userAuthDispMsg=Search input directory not found, Please contact admin ");
    //inputParams.delete();
    //inputTxt.delete();
    else if (pageId.equals("searchresults"))
    noOFrecordsPerPage = ((Integer)session.getAttribute("recsPerPage")).intValue();
    if (actionId.equals("newSearch"))
    session.removeAttribute("CompleteSearchRecords");
    session.removeAttribute("DisplaySearchRecords");
    session.removeAttribute("fromRec");
    session.removeAttribute("toRec");
    session.removeAttribute("recsPerPage");
    System.gc();
    res.sendRedirect("./../pages/search.jsp");
    else if (actionId.equals("first"))
    List completeRecords = (List)session.getAttribute("CompleteSearchRecords");
    int fromRec = 0;
    int toRec = 0;
    String backEnb = "";
    String nextEnb = "";
    if (completeRecords.size() > noOFrecordsPerPage)
    toRec = noOFrecordsPerPage;
    backEnb = "false";
    nextEnb = "true";
    else
    toRec = completeRecords.size();
    backEnb = "false";
    nextEnb = "false";
    List subList = completeRecords.subList(fromRec, toRec);
    session.setAttribute("CompleteSearchRecords", completeRecords);
    session.setAttribute("DisplaySearchRecords", subList);
    session.setAttribute("fromRec", new Integer(fromRec));
    session.setAttribute("toRec", new Integer(toRec));
    session.setAttribute("nextEnb", nextEnb);
    session.setAttribute("backEnb", backEnb);
    session.setAttribute("recsPerPage", new Integer(noOFrecordsPerPage));
    res.sendRedirect("./../pages/SearchResults.jsp");
    else if (actionId.equals("last"))
    List completeRecords = (List)session.getAttribute("CompleteSearchRecords");
    int fromRec = 0;
    int toRec = completeRecords.size();
    String backEnb = "";
    String nextEnb = "";
    if (noOFrecordsPerPage > completeRecords.size())
    fromRec = 0;
    backEnb = "false";
    nextEnb = "false";
    else
    fromRec = completeRecords.size() - noOFrecordsPerPage;
    backEnb = "true";
    nextEnb = "false";
    List subList = completeRecords.subList(fromRec, toRec);
    session.setAttribute("CompleteSearchRecords", completeRecords);
    session.setAttribute("DisplaySearchRecords", subList);
    session.setAttribute("fromRec", new Integer(fromRec));
    session.setAttribute("toRec", new Integer(toRec));
    session.setAttribute("nextEnb", nextEnb);
    session.setAttribute("backEnb", backEnb);
    session.setAttribute("recsPerPage", new Integer(noOFrecordsPerPage));
    res.sendRedirect("./../pages/SearchResults.jsp");
    else if (actionId.equals("back"))
    List completeRecords = (List)session.getAttribute("CompleteSearchRecords");
    int fromRec = ((Integer)session.getAttribute("fromRec")).intValue();
    int toRec = ((Integer)session.getAttribute("toRec")).intValue();
    toRec = fromRec;
    if (fromRec - noOFrecordsPerPage > 0)
    session.setAttribute("backEnb", "true");
    fromRec -= noOFrecordsPerPage;
    else
    fromRec = 0;
    session.setAttribute("backEnb", "false");
    session.setAttribute("nextEnb", "true");
    session.setAttribute("fromRec", new Integer(fromRec));
    session.setAttribute("toRec", new Integer(toRec));
    List subList = completeRecords.subList(fromRec, toRec);
    session.setAttribute("DisplaySearchRecords", subList);
    res.sendRedirect("./../pages/SearchResults.jsp");
    else if (actionId.equals("next"))
    List completeRecords = (List)session.getAttribute("CompleteSearchRecords");
    int fromRec = ((Integer)session.getAttribute("fromRec")).intValue();
    int toRec = ((Integer)session.getAttribute("toRec")).intValue();
    fromRec = toRec;
    if (toRec + noOFrecordsPerPage <= completeRecords.size())
    session.setAttribute("nextEnb", "true");
    toRec += noOFrecordsPerPage;
    else
    toRec = completeRecords.size();
    session.setAttribute("nextEnb", "false");
    session.setAttribute("backEnb", "true");
    session.setAttribute("fromRec", new Integer(fromRec));
    session.setAttribute("toRec", new Integer(toRec));
    List subList = completeRecords.subList(fromRec, toRec);
    session.setAttribute("DisplaySearchRecords", subList);
    res.sendRedirect("./../pages/SearchResults.jsp");
    else if (actionId.equals("download"))
    String fileName = req.getParameter("fileName");
    String originalFileName = req.getParameter("originalFileName");
    doDownload(req, res, fileName, originalFileName);
    else
    res.sendRedirect("./../pages/login.jsp?userAuthDispMsg=Invalid USER");
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    doGet(req, res);
    private void doDownload(HttpServletRequest req, HttpServletResponse resp, String filename, String original_filename)
    throws IOException
    File f = new File(filename);
    int length = 0;
    ServletOutputStream op = resp.getOutputStream();
    ServletContext context = getServletConfig().getServletContext();
    String mimetype = context.getMimeType(filename);
    resp.setContentType(mimetype != null ? mimetype : "application/octet-stream");
    resp.setContentLength((int)f.length());
    resp.setHeader("Content-Disposition", "attachment; filename=\"" + original_filename + "\"");
    byte[] bbuf = new byte[10240];
    DataInputStream in = new DataInputStream(new FileInputStream(f));
    while ((in != null) && ((length = in.read(bbuf)) != -1))
    op.write(bbuf, 0, length);
    in.close();
    op.flush();
    op.close();
    =========================
    anyone please help me on above......Thanks in advance..

    Hi jleech,
    Thanks for the reply. But deleting all the temporary internet files as also the history files does not seem to have an effect. the doFilter is being called only at the second request. or did i miss anything??
    Please help. unable to complete the assignment because of this.
    Thank You,
    Phani Kanuri

  • 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

  • Telling which class called your method

    Does anybody know a way you can tell which class is calling your method? I mean:
    class A {
    public static void main(String args[]) {
    new A.doIt();
    void doIt() {
    B b = new B();
    b.callMe();
    class B {
    public void callMe() {
    String whoDidIt;
    whoDidIt=[stuff i'm asking for];
    System.out.println("I was called from an instance of class " + whoDidIt);
    How can I get that code to print "I was called from an instance of class A"???
    Lots of thanks in advance

    Pass the calling object to callMe as a parameter, egB b = new B();
    b.callMe(this);callMe becomes:
    public void callMe(Object caller)
       System.out.println("I was called from an instance of class " + caller.getClass());
    }Of course, there is nothing to stop anyone who calls the method passing a different object and confusing callMe.

  • Problem calling servlet from doget method of another servlet

    hi,
    Iam trying to post an html form written in the doGet() method
    of a servlet to pass this information to another servlet's doPost() method. Iam giving the following URL:
    "<FORM ACTION=http://localhost:8080/examples/servlet/UpdateProcessServlet" +
    "METHOD=POST>"
    But its not happening,the error says that "the page cannot be found" The servlet is not getting called at all. would someboy please help me in this regard.
    Thanks

    #1 Iam calling servlet 2 from here
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    session=request.getSession(false);
    out.println
    (ServletUtilities.DOCTYPE +
    "<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN>"+
    "<HTML>" +
    "<BODY>" +
    "<P CLASS=LARGER>" +
    "<FORM ACTION=http://localhost:8080/examples/servlet/UpdateProcessServlet METHOD=POST>"
    "<INPUT TYPE=SUBMIT NAME=submitButton Value=submit>" +
    "</BODY> " +
    "</HTML>" );
    #2 This should get called and print me "Iam in doPost method
    public void doPost(HttpServletRequest request,HttpServletResponse response)
    throws ServletException,IOException
    url = "jdbc:odbc:Resume";
    System.out.println("Iam in doPost method");
    response.setContentType("text/html");
    out = response.getWriter();
    out.println("This is the last servlet for this project:");
    bool=false;
    check=false;
    Thank...:)

  • Why doGet() method wil be called default in servlet

    hi
    my first question is
    1.why doGet() method wil be called up first instead of doPost() method in servlet. .
    2. How to identify the browser disables the cookies.
    please help me to this questions.
    Thank u in advance.

    hi
    my first question is
    why doGet() method wil be called up first instead of
    doPost() method in servlet.This is not correct. doGet or doPost getting called depending on the request method of the HTTP request. If the request method is GET then doGet will get called, if the request method is POST then doPost will get called.
    By the way there are other request methods. If a request arrives with one of those request methods the corresponding doXXX method wil get called.
    2. How to identify the browser disables the
    cookies. There is no direct method. What you can do is set a cookie and then see if it is sent back with the next request from the same browser session.

  • Calling a method from another servlet? very beginner

    I am going to try to explain what I want to do so just be patient please.
    I want to call a method in a seperate servlet to connect and release my connection pool - How do I do this?
    This is what I have been trying... help
    dbPOOL.class
    package DATABASE;
    import javax.naming.*;
    import javax.sql.*;
    import java.sql.*;
    import java.util.*;
    public class dbPOOL {
      Connection con;
      private boolean conFree = true;
      private String dbName = "java:comp/env/jdbc/connectDB";
      public dbPOOL() throws Exception {
           try  {              
                    InitialContext ic = new InitialContext();
                    DataSource ds = (DataSource) ic.lookup(dbName);
                    con =  ds.getConnection();    
         } catch (Exception ex) { throw new Exception("Couldn't open connection to database: " + ex.getMessage());
      public void remove () {
             try {
                 con.close();
            } catch (SQLException ex) { System.out.println(ex.getMessage());}
      protected synchronized Connection getConnection() {
             while (conFree == false) {
                     try {
                             wait();
                     } catch (InterruptedException e) {
                  conFree = false;
                  notify();
                  return con;
        protected synchronized void releaseConnection() {
            while (conFree == true) {
                     try {
                        wait();
                     } catch (InterruptedException e) {
                  conFree = true;
                  notify();
    }and my worker servlet connTest
    package DATABASE;
    import javax.naming.*;
    import javax.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class connTest extends HttpServlet {  
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, SQLException, IOException {
             try {
                    String selectStatement = "select * " + "from mt.Evendale_Web_Groups";
                    getConnection();
                    PreparedStatement prepStmt = con.prepareStatement(selectStatement);
                    ResultSet rs = prepStmt.executeQuery();
                    while (rs.next()) {
                       groupList gl = new groupList(rs.getString(1), rs.getString(2), rs.getString(3));
                    prepStmt.close();
            } catch (SQLException ex) { throw Exception(ex.getMessage());}
                releaseConnection();
    }When I try to compile the connTest servlet - I keep getting cannot find symbols errors on the methods. How do I fix this?

    Which errors exactly?
    Try something like this:
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    dbPOOL db = null;     
    try {               
    String selectStatement = "select * " + "from mt.Evendale_Web_Groups";
    db = new dbPOOL();        
    Connection con = db.getConnection();               
    PreparedStatement prepStmt = con.prepareStatement(selectStatement);               
    ResultSet rs = prepStmt.executeQuery();               
    while (rs.next()) {                                    
       // process your rs                      
    prepStmt.close();           
    } catch (Exception ex) {
    } finally {
        if (db != null)
             db.releaseConnection();             
    }Simply change the package name to something else. But don't forget to import your dbPOOL class since it is now located in a diff package. Also be aware of coding standards when naming your classes and packages.

  • Call doGet in the Init of a servlet?

    Hello
    Please could you show through the code. I think there is something wrong with the init. If I run the servlet, it don't show a thing. It only displays: Site can't not be shown.
    The doGet and also the dopost is not executed. Must I call in the doPost in the init(). And when yes how?
    Thanks a lot!
    Sandra Frei
    import java.sql.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.Properties;
    public class update42 extends HttpServlet {
         Connection con = null;
         public void init() {//throws ServletException {
              String url = "jdbc:DBF:/sys:copal/copal_data/data/gesch/data/stamm";      
              try {
                   //Register the JDBC driver
                   Class.forName("zyh.sql.dbf.DBFDriver");//.newInstance();
                   con = DriverManager.getConnection(url, "fre","sandy66");                    
              catch( Exception e ) {
                   e.printStackTrace();
              }//end catch
         }//end init()
         public void doGet(HttpServletRequest req, HttpServletResponse res)
              throws ServletException, IOException {
              res.setContentType("text/html");
              PrintWriter out = res.getWriter();
              out.print("in do get");
              //connecting to the Database
              Statement stmt = null;
              ResultSet rs = null;
              PreparedStatement ps = null;
                   try
                   stmt = con.createStatement();
                   catch (SQLException e) {e.getNextException();}                              
                   // displaying records
                   try
                   rs = stmt.executeQuery("SELECT Random, Nsa, Bzng, Bzn2, Tart, Meeh, Fstat, Nzn FROM part");
                   catch (SQLException e) {e.getNextException();}                              
                   try
                   while(rs.next()) {
                        out.print("<form action=\"");
                        out.print( req.getRequestURI() );
                        out.print("\" method=\"post\">");
                        out.print("<input type=\"text\""); //hidden
                        out.print(" name=\"Random\" size=\"15\" value=\"");//without 15
                        out.print( rs.getObject(1).toString() );
                        out.print("\">");
                        out.print("<input type=\"text\"");
                        out.print(" name=\"Nsa\" size=\"15\" value=\"");
                        out.print( rs.getObject(2).toString() );
                        out.print("\">");
                        out.print("<input type=\"text\"");
                        out.print(" name=\"Bzng\" size=\"25\" value=\"");
                        out.print( rs.getObject(3).toString() );
                        out.print("\">");
                        out.print("<input type=\"text\"");
                        out.print(" name=\"Bzn2\" size=\"25\" value=\"");
                        out.print( rs.getObject(4).toString() );
                        out.print("\">");
                        out.print("<input type=\"text\"");
                        out.print(" name=\"Tart\" size=\"6\" value=\"");
                        out.print( rs.getObject(5).toString() );
                        out.print("\">");
                        out.print("<input type=\"text\"");
                        out.print(" name=\"Meeh\" size=\"6\" value=\"");
                        out.print( rs.getObject(6).toString() );
                        out.print("\">");
                        out.print("<input type=\"text\"");
                        out.print(" name=\"Fstat\" size=\"6\" value=\"");
                        out.print( rs.getObject(7).toString() );
                        out.print("\">");
                        out.print("<input type=\"text\"");
                        out.print(" name=\"Nzn\" size=\"15\" value=\"");
                        out.print( rs.getObject(8).toString() );
                        out.print("\">");
                        out.print(" <input type=\"submit\"");
                        out.print(" value=\" \">");
                        out.print(" Update<br>");
                        out.print("</form>");
                   catch (SQLException e) {e.getNextException();}                              
                   try
                        if(rs != null)
                             rs.close();
                        if(stmt != null)
                             stmt.close();
                   catch (SQLException e) {
                        e.printStackTrace();
         out.print("</pre></code>");
         out.print("<p\"><a href=\"");
         out.print( req.getRequestURI() );
         out.print("\">Back</a></p>");
         out.print("</body></html>");
         out.close();
         public void doPost(HttpServletRequest req, HttpServletResponse res)
              throws ServletException, IOException {
              res.setContentType("text/html");
              PrintWriter out = res.getWriter();
              out.print("<html><body>");
              out.print("<code><pre>");
              out.print("<table border=1>");
         out.print("<tr>");
              out.print("<td><font color=green>Artikelnr</font></td>");
              out.print("<td><font color=green>Bezeichnung</font></td>");
              out.print("<td><font color=green>Zusatzbezeichnung</font></td>");
              out.print("<td><font color=green>Art</font></td>");
              out.print("<td><font color=green>ME</font></td>");
              out.print("<td><font color=green>Stat</font></td>");
              out.print("<td><font color=green>Spezifikation</font></td>");
         out.print("</tr>");
              // receiving parameters
              String Bzn2 = req.getParameter("Bzn2").trim();
              String Meeh= req.getParameter("Meeh").trim();
              String Pk = req.getParameter("Random").trim();
              boolean proceed = false;
              Statement stmt = null;
              Statement stmt1 = null;
              ResultSet rs = null;
              try {
                   String sql;
              sql = "UPDATE part SET Bzn2 = " + "'" + Bzn2 + "'" + " WHERE Random LIKE " + "'" + Pk + "'";
                   stmt1 = con.createStatement();               
                   out.print(sql);
                   out.print(Bzn2 + Meeh + Pk);
                   stmt1.executeUpdate(sql);
              // displaying records
                   stmt = con.createStatement();               
                   rs = stmt.executeQuery("SELECT * FROM part");
                   while(rs.next())
                        out.print("<tr>");
                        out.print("<td>"+ rs.getObject(1).toString()+ "</td>");
                        out.print("<td>"+ rs.getObject(2).toString()+ "</td>");
                        out.print("<td>"+ rs.getObject(3).toString()+ "</td>");
                        out.print("<td>"+ rs.getObject(4).toString()+ "</td>");
                        out.print("<td>"+ rs.getObject(5).toString()+ "</td>");
                        out.print("<td>"+ rs.getObject(6).toString()+ "</td>");
                        out.print("<td>"+ rs.getObject(7).toString()+ "</td>");
                        out.print("</tr>");
                   out.print("</table>");
              catch (Exception e)     
                   out.print(e.getMessage());
                   e.printStackTrace();
                   try
                        if(rs != null)
                             rs.close();
                        if(stmt != null)
                             stmt.close();
                        if(stmt1 != null)
                             stmt1.close();
                   catch (SQLException e) {e.getNextException();}
              out.print("</pre></code>");
              out.print("<p\"><a href=\"");
              out.print( req.getRequestURI() );
              out.print("\">Back</a></p>");
              out.print("</body></html>");
              out.close();
         public void destroy() {
              try {
                   //Close the connection to the database
                   con.close();
              } catch( Exception e ) {
                   e.printStackTrace();
    }

    It won't get shown unless you make a call to the servlet from (e.g.) a web browser referencing it. And no - don't call doPost() or doGet() from the init() method. You might be lucky, and it might work, but it's inherently unsafe. Servlet engines will not normally call these methods until the servlet is properly initialised.
    And BTW, there is no guarantee that init() will be called until the first call to the servlet, unless you specify load on startup to the servlet engine.
    Your best bet is simply to type the URL of your servlet into your web browser. That will call doGet(). To call doPost(), you'll have to write a little HTML page with a form with method="post" and action=the name of your servlet.
    Robin

  • DoGet method is called 2 times when a switch-case statement is used

    Hello all,
    I have a servlet that, when run from browser, runs the doGet method 2 times.
    I have a switch case statement within the servlet and when I comment out this servlet, it runs 1 time as expected.
    Here is the code:
    public class RSSServlet extends HttpServlet {
        /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
         * @param request servlet request
         * @param response servlet response
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            System.out.println("CALLED SERVLET");
            response.setContentType("text/xml;charset=UTF-8");
            PrintWriter out      = response.getWriter();
            DBQueriesRSS queries = new DBQueriesRSS();
            String queryType     = request.getParameter("queryType");
            String strCount      = request.getParameter("count");
            int count            = (strCount != null && !strCount.equalsIgnoreCase("null") && strCount.length() > 0) ?
                Integer.parseInt(strCount) : 25;
             if(queryType != null && !queryType.equalsIgnoreCase("null") && queryType.length() > 0) {
                System.out.println("IN IF STATEMENT");
                switch(Integer.parseInt(queryType)) {
                    case 1 : out.println(queries.getDefault(count));System.out.println("1");       break;
                    case 11: out.println(queries.getDefault(count));System.out.println("11");       break;
                    case 21: out.println(queries.getTopDaily(count));System.out.println("21");      break;
                    case 22: out.println(queries.getTopWeekly(count));System.out.println("22");     break;
                    case 23: out.println(queries.getTopMonthly(count));System.out.println("23");    break;
                    case 24: out.println(queries.getTopYearly(count));System.out.println("24");     break;
                    case 31: out.println(queries.getTopNDailyBW(count));System.out.println("31");   break;
                    case 32: out.println(queries.getTopNWeeklyBW(count));System.out.println("32");  break;
                    case 33: out.println(queries.getTopNMonthlyBW(count));System.out.println("33"); break;
                    case 34: out.println(queries.getTopNYearlyBW(count));System.out.println("34");  break;
                    default: out.println(queries.getTopWeekly(25));System.out.println("default");    break;
                System.out.println("OUT OF SWITCH");
            System.out.println("OUT OF IF");
            out.close();
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /** Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
           processRequest(request, response);
        /** Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
        // </editor-fold>
    } The results from running this servlet are:
    http://localhost/proxy/RSSServlet??queryType=34&count=66
    CALLED SERVLET
    IN IF STATEMENT
    34
    OUT OF SWITCH
    OUT OF IF
    CALLED SERVLET
    IN IF STATEMENT
    34
    OUT OF SWITCH
    OUT OF IFAnyone see anything obvious?
    TIA!

    in your case you want 'count' to be a class attribute rather than a local variable. But yes, incrementing it each time that the method is called will serve your purpose.

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

  • Invoking servlet's doGet() method on startup

    Hi Friends,
    Is there any way of invoking the servlets doGet method on server start -up.
    I am using Tomcat 4.1.18.
    I know that we can Invoke the servlet at stat-up i.e. it will invoke init() method osf servlet.But what if I want to invoke the doGet method on start - up?
    Regards
    Abhay

    The doGet will require an Request and Response object. It would be easier to remove what ever logic in the doGet you need to execute to seperate methods that can be called from both the init and doGet methods.

Maybe you are looking for