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.

Similar Messages

  • 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

  • Why the method can be called in this way?

    Hi all,
    The following is JAVA SWING TREE custom data models program. There are two files in the program: one is TestFrame.java, and the other is MyDataModel.java. I only posted the important part on the Forum.My question is how method getChild(...) in MyDataModel.java was called in the program? Why I couldn't see the statement like tree.getChild(..) in TestFrame.java? After adding PRINT statements, I know the method getChild(..) was called automatically when object tree was initialized , but I don't know why. Thank you in advance.
    ======
    TestFrame.java
    // Imports
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    class TestFrame extends JFrame
    // Instance attributes used in this example
    private JPanel topPanel;
    private JTree tree;
    private JScrollPane scrollPane;
    // Constructor of main frame
    public TestFrame()
    // Create a new tree control
    MyDataModel treeModel = new MyDataModel( root );
    tree = new JTree(treeModel);
    =========
    ==========
    MyDataModel.java
    import javax.swing.tree.*;
    class MyDataModel extends DefaultTreeModel
    private DefaultMutableTreeNode root;
    private String rootName = "";
    public MyDataModel( TreeNode root )
    super( root );
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)root;
    rootName = (String)parentNode.getUserObject();
    System.out.println("rootName is: "+rootName);
    public Object getChild( Object parent, int index )
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)parent;
    String parentName = (String)parentNode.getUserObject();
    System.out.println("parentName is: "+parentName);
    if( parentName.equals( rootName ) )
    return super.getChild( parent, index );
    else
    return new DefaultMutableTreeNode( cardArray[index] );
    }

    This is the first time I saw this usage. I understood it now, but I was afraid I missed some important concepts on "interface as parameter in the constructor". Therefore, I am wondering where I can find some online document about it in order to understand the usage clearly.
    For example, if there are a few method implementations of interface TreeModel in MyDataModel.java, which methods will it call after calling JTree constructor? all methods or only part of them?
    Thanks

  • Why listener methods are getting called twice ?

    Hi Group,
    I have a doubt, i need to know logic behind it.
    Lets consider, JComboBox,
    For an item state change of JComboBox,
    itemStateChanged method gets called twice.
    Its similar with valueChanged getting called twice
    on List Selection Event.
    Why does it call twice ? Is there any way, I can
    have invocation only once (except flagging mechanism)?
    with regards,
    vikram.

    http://java.sun.com/j2se/1.3/docs/api/java/awt/event/ItemListener.html
    tells the following:
    public void itemStateChanged(ItemEvent e)
    Invoked when an item has been selected or deselected. The code written for this method performs the operations that need to occur when an item is selected (or deselected).
    So the listener is notified for both items: losing and gaining selection.
    If you are only interested in listening to either selection or deselection event you can check which was the cause for the method call by examing the ItemEvent parameter i.e. item_event.getStateChange() == ItemEvent.DESELECTED or ItemEvent.SELECTED and then decide whether you are interested in the event at all.
    I don't know how to stop JComboBox from launching both select and deselected events.

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

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

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

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

  • How to know that a method has been called and returning value of a method

    Hi, everyone! I have two questions. One is about making judgment about whether a method has been called or not; another one is about how to return "String value+newline character+String value" with a return statement.
    Here are the two original problems that I tried to solve.
    Write a class definition of a class named 'Value' with the following:
    a boolean instance variable named 'modified', initialized to false
    an integer instance variable named 'val'
    a constructor accepting a single paramter whose value is assigned to the instance variable 'val'
    a method 'getVal' that returns the current value of the instance variable 'val'
    a method 'setVal' that accepts a single parameter, assigns its value to 'val', and sets the 'modified' instance variable to true, and
    a boolean method, 'wasModified' that returns true if setVal was ever called.
    And I wrote my code this way:
    public class Value
    boolean modified=false;
    int val;
    public Value(int x)
    {val=x;}
      public int getVal()
      {return val;}
       public void setVal(int y)
        val = y;
        modified = true;
         public boolean wasModified()
          if(val==y&&modified==true)
          return true;
    }I tried to let the "wasModified" method know that the "setVal" has been called by writing:
    if(val==y&&modified==true)
    or
    if(x.setVal(y))
    I supposed that only when the "setVal" is called, the "modified" variable will be true(it's false by default) and val=y, don't either of this two conditions can prove that the method "setVal" has been called?
    I also have some questions about the feedback I got
    class Value is public, should be declared in a file named Value.java
    public class Value
    cannot find symbol
    symbol  : variable y
    location: class Value
    if(val==y&&modified==true)
    *^*
    *2 errors*
    I gave the class a name Value, doesn't that mean the class has been declared in a file named Value.java*?
    I have declared the variable y, why the compiler cann't find it? is it because y has been out of scale?
    The other problem is:
    Write a class named  Book containing:
    Two instance variables named  title and  author of type String.
    A constructor that accepts two String parameters. The value of the first is used to initialize the value of  title and the value of the second is used to initialize  author .
    A method named  toString that accepts no parameters.  toString returns a String consisting of the value of  title , followed by a newline character, followed by the value of  author .
    And this is my response:
    public class Book
    String title;
    String author;
      public Book(String x, String y)
       { title=x; author=y; }
       public String toString()
       {return title;
        return author;
    }I want to know that is it ok to have two return statements in a single method? Because when I add the return author; to the method toString, the compiler returns a complain which says it's an unreachable statement.
    Thank you very much!

    Lets take this slow and easy. First of all, you need to learn how to format your code for readability. Read and take to heart
    {color:0000ff}http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html{color}
    Now as to your first exercise, most of it is OK but not this:   public boolean wasModified()
          if (val == y && modified == true)
                return true;
    y being a parmeter to the setValue method exists only within the scope of that method. And why would you want to test that anyways? If modified evaluates to true, that's all you need to know that the value has been modified. So you could have   public boolean wasModified()
          if (modified == true)
                return true;
       }But even that is unnecessarily verbose, as the if condition evaluates to true, and the same is returned. So in the final analysis, all you need is   public boolean wasModified()
          return modified;
       }And a public class has to be declared in a file named for the class, yes.
    As for your second assignment, NO you cannot "return" two variables fom a method. return means just that: when the return statement is encountered, control returns to the calling routine. That's why the compiler is complaining that the statement following the (first) return statement is unreachable.
    Do you know how to string Strings together? (it's called concatenation.) And how to represent a newline in a String literal?
    db

  • Can we call default.lgf in BADI logic

    Hello All,
    can we call default.lgf logic script to run in the BPC in the BADI ? If yes then can someone please let me know the relevant Method or Class etc.
    For e.g. we have a BADi logic that does a data push from Profit model to Main model based on some conditions. After all this processing in the BADi and writes to Main model, there is a requirement to run the default logic which is there in Profit Model. Which I want to handle in BADI itself after processing the earlier BADI.
    If you need more details please let me know.
    Many Thanks
    Krishna

    Hi Vadim,
    *START_BADI RUNLOGIC_PH
    QUERY = OFF
    WRITE = ON
    LOGIC = DEFAULT.LGF
    APPSET = UUG
    APP = MAIN
    DEBUG = OFF
    *END_BADI
    DEFAULT.LGF has 2 logic scripts calling.
    *account.lgf
    *balance.lgf
    This only executes the first LGF and ignores the second one. I executed each one at a time and all works fine but if I give both together it executes first one in the sequence and ignores the other. Any idea why it is doing like that ??
    Try 1)
    *START_BADI TRANSPROFITTOMAIN
    QUERY = OFF
    WRITE = OFF
    *END_BADI
    *START_BADI RUNLOGIC_PH
    QUERY = OFF
    WRITE = ON
    LOGIC = FLOW_BALANCE.LGF
    APPSET = <appset name>
    APP = MAIN
    DEBUG = OFF
    *END_BADI
    *START_BADI RUNLOGIC_PH
    QUERY = OFF
    WRITE = ON
    LOGIC = CALCACCOUNT.LGF
    APPSET = <appset name>
    APP = MAIN
    DEBUG = OFF
    *END_BADI
    it runs flow_balance.lgf and I can see the log for it..In the log it says the below
    SCRIPT RUNNING TIME IN TOTAL:109.42 s.
    LOG END TIME:2014-06-26 15:17:31
    Amount of time to run script:                                         110797.19 ms
    BADI EXECUTION TIME IN TOTAL :111233.64 ms.
    [WARNING!] NO MEMBER SPECIFIED FOR DIMENSION:DATASRC WILL QUERY ON ALL BASE MEMBERS.
    [WARNING!] NO MEMBER SPECIFIED FOR DIMENSION:INFLATION WILL QUERY ON ALL BASE MEMBERS.
    [WARNING!] NO MEMBER SPECIFIED FOR DIMENSION:INTORDER WILL QUERY ON ALL BASE MEMBERS.
    [WARNING!] NO MEMBER SPECIFIED FOR DIMENSION:PROFITCENTRE WILL QUERY ON ALL BASE MEMBERS.
    [WARNING!] NO MEMBER SPECIFIED FOR DIMENSION:PROFIT_ACCOUNT WILL QUERY ON ALL BASE MEMBERS.
    [WARNING!] NO MEMBER SPECIFIED FOR DIMENSION:TIME WILL QUERY ON ALL BASE MEMBERS.
    EXECUTION BADI:RUNLOGIC_PH
    QUERY: OFF
    WRITE: ON
    Parameter DIMENSION not specified. ALL values used.
    Dimension ACCOUNT not specified and doesn't exist in current context.
    Error in RUNLOGIC call.
    BADI EXECUTION TIME IN TOTAL :2.07 ms.
    SCRIPT RUNNING TIME IN TOTAL:132.65 s.
    Please advise.
    individually they both work fine..meaning Try 2 and Try 3 works fine.
    Try 2)
    *START_BADI TRANSPROFITTOMAIN
    QUERY = OFF
    WRITE = OFF
    *END_BADI
    *START_BADI RUNLOGIC_PH
    QUERY = OFF
    WRITE = ON
    LOGIC = CALCACCOUNT.LGF
    APPSET = <appset name>
    APP = MAIN
    DEBUG = OFF
    *END_BADI
    Try 3)
    *START_BADI TRANSPROFITTOMAIN
    QUERY = OFF
    WRITE = OFF
    *END_BADI
    *START_BADI RUNLOGIC_PH
    QUERY = OFF
    WRITE = ON
    LOGIC = FLOW_BALANCE.LGF
    APPSET = <appset name>
    APP = MAIN
    DEBUG = OFF
    *END_BADI
    Try 4) Default.lgf contains 2 include statements
    *include FLOW_BALANCE.LGF
    *include calcaccount.LGF
    In this case it executes only the fist lgf in the sequence and ignores the other. I cant see anything in the log for the 2nd LGF.
    *START_BADI TRANSPROFITTOMAIN
    QUERY = OFF
    WRITE = OFF
    *END_BADI
    *START_BADI RUNLOGIC_PH
    QUERY = OFF
    WRITE = ON
    LOGIC = Default.LGF
    APPSET = <appset name>
    APP = MAIN
    DEBUG = OFF
    *END_BADI
    Thanks
    Krishna

  • How to get only the last part of the URL in the doGet() method?

    In the doGet() method is there a way to check what URL it was called from ? For example the URL was: http://localhost:8080/myproject/jsp/randomPhrase.php (the php here is purely for misleading purposes - it's all Java really). in the doGet() method I would like to get the "randomPhrase" part of the URL only - to determine where to redirect the user. How can I do that?
    Thanks.

    Hello there,
    As it seems to me the part of the URL you're looking fo,r corresponds actually to the name of the servlet, so why don't you just call the getServletName method?

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

  • DoFilter() method is being called only at the second request

    Hi,
    I have implemented a simple Filter class
    Here is the code
    public class BasicFilter implements Filter
    FilterConfig config;
    public void init(FilterConfig config)
    System.out.println("Filter Initialised");
    this.config = config;
    public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws ServletException,
    IOException
    System.out.println("In The doFilter() method");
    ServletContext sc = config.getServletContext();
    sc.setAttribute("Hello","Hell");
    chain.doFilter(request,response);
    public void destroy()
    System.out.println("In the destroy method");
    and a simple servlet
    public class FilteredServlet extends HttpServlet
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<HTML>");
    out.println("<HEAD><TITLE>Filter Demo</TITLE></HEAD>");
    out.println("<BODY>");
    out.println(getServletContext().getAttribute("Hello"));
    out.println("</BODY>");
    out.println("</HTML>");
    Now when i start the server (Tomcat 4.0) i find that the filter's init() method is being called which is fine. But when i request the servlet (FilteredServlet) the doFilter() method is not called and only when i "refresh" it or call it a second time that the doFilter() method is actually called. What could be the reason for this.
    Help will be greatly appreciated.
    Thank You,
    Phani Kanuri

    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

  • Why do we need to call start() to execute a thread.

    hi,
    Why do we need to call thread.start() to execute a thread. why not just calling run().
    Vjoy

    hi,
    Why do we need to call thread.start() to execute a
    thread. why not just calling run().
    Because, start() does two things.
    - start a new thread of execution and then
    - call the run method....and calling run does NOT start a new thread of execution. It's just a plain old regular method.

  • What is the need for calling default constructor by JVM?

    What is the need for calling default constructor by JVM? why the JVM should intiializes default values to the data
    fields if the constructor is not there in our class?

    mahar wrote:
    What is the need for calling default constructor by JVM? Huh? The JVM does not need to call the default constructor. It needs to call a constructor.
    You decide which one by the way you use "new".
    why the JVM should initialize default values to the data fieldsHuh?
    ... if the constructor is not there in our class?Huh? The default constructor is always there. It may be private but it is still there.

Maybe you are looking for