Why do we use init() method instead of constructor to initialize a servlet?

Why do we use init() method instead of constructor to initialize a servlet?

I suspect the reasons are partly historical. A servlet is loaded dynamically, by class name and, once you've loaded the Class, it's easier to to a newInstance, using the default construtor than it is to search for a particular matching constructor and invoke it.

Similar Messages

  • Why we are using init() in servlet

    why we are using init() in servlet
    Instead of doing in init() we can do that things in Constructor

    Hi
    In order ti be clear. Do you remeber the applet lfe cycle ?. An applet run inside a browser and a servelts runs inside a servlet container, so is the servelt container who instatiate a servlet, init and destroy, and while servlet is alive calls doService inside a thread.
    The mechanism to fill some parameters or other task is by writing the init(ServletConfig) method inherited from GenericServlet.
    To clear parameters or other clearing stuff you can use the destroy method, inherited from GenericServlet
    Hope this helps

  • Why do we use ejbCreate() method? what does it returns?

    why do we use ejbCreate() method? what does it returns?

    People think its easier to get answers handed tothem
    instead of looking...I do my best to disabuse them of that notion.I've given up on that idea, too much hard work.
    Instead I've just written off the entire current generation of schoolkids as useless, good only for (at most) menial labour.

  • Why not to use static methods - with example

    Hi Everyone,
    I'd like to continue the below thread about "why not to use static methods"
    Why not to use static methods
    with a concrete example.
    In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
         public static void wait(int millis){
              r.delay(millis);
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
    Thanks for any comments in advance,
    lemonboston

    maheshguruswamy wrote:
    lemonboston wrote:
    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
    Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
    To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
    If you use a Singleton (and and interface), you can do something like this:
    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
    There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
    And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class.

  • Static factory methods, instead of constructor

    Hi All,
    why we use static factory methods, instead of constructor.
    Apart from Singleton class , what is use of static factory methods ?
    Thanks in Advance,
    Rishi

    One reason for using factories is that they simplify creating instances of immutable classes that might otherwise have messy constructors with lots of arguments.

  • Why there are two init methods?

    I copied this code from netbeans for a JApplet.. and it has two init methods
    One is public void init() that calls another initComponents() method.
    And the initComponents() method has all the components defined in it, and it is private.
    I replaced private with public and changed initComponents to init, and then deleted all the init method, it worked that way.
    But why there two methods when you can put every thing in single init() method?
    The init() method has this code in it:
    public void init() {
            try {
                java.awt.EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        initComponents();
            } catch (Exception ex) {
                ex.printStackTrace();
        }

    BDLH:
    WWJD? Probably code in Ruby, but I digress. No, he would define an abstract base for that boilerplate code:
    import java.awt.*;
    import java.lang.reflect.*;
    import javax.swing.*;
    public abstract class AbstractApplet extends JApplet {
         public void init() {
              try {
                   EventQueue.invokeAndWait(new Runnable() {
                        public void run() {
                             initComponents();
              } catch (InterruptedException ex) {
                   ex.printStackTrace();
              } catch (InvocationTargetException ex) {
                   ex.printStackTrace();
         protected abstract void initComponents();
         //ditto: start, stop, distroy
    }

  • Using @Init methods

    hi,
    I'm converting an app to EJB3. In the original code we defined home interfaces with specific create methods for example create(String name) for our session beans. Now that we use EJB3 we have removed the home interface but still want to construct (or initialise) the session beans according to different sets of parameters. I have read about the @Init annotation which appears to provide this function but how do I call the correct @Init function from the client without a home interface??
    Thanks
    Stephen

    Hi Stephen,
    For clients coded to the EJB 3.0 client view you can just define a business method that takes the
    initialization parameters.
    // 2.x
    Foo foo = FooHome.create(1, "bar");
    // 3.0
    Foo foo = (Foo) ic.lookup("FooEJB");
    foo.setState(1, "bar");
    In the cases where information is required to initialize the SFSB instance one could argue
    that the 3.0 approach is a bit more error-prone since there's no guarantee the client will
    call the developer-designated initialization method. However, the overall simplicity
    gained by eliminating the entire Home/LocalHome interface was seen as far outweighing
    that issue.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Why not to use static methods in interfaces?

    why?

    Because static methods are always attached to a particular class -- not an object. So object polymorphism (which is what interfaces are good for) won't help. Now, what you can do is say that subclasses must implement a method that looks an awful lot like a static method, in that it doesn't depend on object state.
    This bugged me, and it still bugs me a little bit in that I have to instantiate an object of a type in order to call these pseudo-static methods. When the pseudo-static methods tell the user how to initialize the object, you get a bit of a chicken-and-egg problem.

  • Why init() instead of constructor

    why we are using init method instead of constructor to initialise a servlet? pls any bosy tell me

    Before a servlet can be loaded, the servlet engine must first locate its class.Once loaded, the servlet engine instantiates an instance of that servlet class. An instantiated servlet must be initialised before it is ready to receive client requests.The Servlet API provides the init() callback method for a servlet to place all its initialisation logic. Once a servlet has been instantiated the init() is invoked by the servlet engine to initialise the servlet for the first time only.

  • Need clarification - Rreg Servlets init method and construction

    Hi,
    My friends asks me 'Is init method of servlet is necessary? Can't we do whatever we want to do in Init method, in the constructor of the servlet? Why is init method is necessary?'
    Thanks in advance,
    Guhan

    byte[] tripleDesKeyData = key.getBytes();
    Instead of getting Bytes directly from that Hex string now i am getting in the following way......
    byte[] tripleDesKeyData = Encryption.tempHexStringToByteArray(key);
    public static byte[] tempHexStringToByteArray(String hexString){
         byte[] bytes = new byte[hexString.length() / 2];
         for (int i = 0; i < bytes.length; i++) {
              bytes[i] = (byte) Integer.parseInt(hexString.substring(2*i, 2*i+2), 16);
         return bytes;
    And using that key to decrypt....as of now its working fine now
    Why i am posting this is for others to use further....

  • The Init() method of abstract pagebean always it excute, and i lost data.

    Hi,
    I have applicaction to buid in NetBean 6.1 and JDK 1.6 using Visual Web Java Server Pages. This application to present a view that have a 2 calendar component, 1 dropdownlist, button component and table component.
    The table component show rows where calendar1.date > date1 and calendar2.date < date2 and estado(DropDownList)= status1
    In the init() method of abstractpagebean i set de initial calendar's date that follow
    java.util.Calendar dateAntes = GregorianCalendar.getInstance();
    java.util.Calendar date = GregorianCalendar.getInstance();
    dateAntes.add(java.util.Calendar.MONTH, -1);
    GregorianCalendar gc = new GregorianCalendar(2000, 11, 20);
    //tablePhaseListener = getSessionBean1().getTablePhaseListener();
    calendar1.setSelectedDate(dateAntes.getTime());
    calendar2.setSelectedDate(date.getTime());
    With this initial dates dates i show the table row thw follow
    String command = "SELECT ALL codreqgmc, fechareq,cliente.nomclie,estado.Descripcion as Estado, " +
    "requerimiento.codtecnico, requerimiento.rutclie, requerimiento.codestado " +
    "FROM requerimiento,cliente,estado " +
    "WHERE requerimiento.rutclie=cliente.rutclie and requerimiento.codestado=estado.codestado and fechareq>=" + "'" + formatoFecha.format(calendar1.getSelectedDate()) + "'" +
    "AND fechareq<=" + "'" + formatoFecha.format(calendar2.getSelectedDate()) + "'";
    try {
    getSessionBean1().getRequerimientoRowSet().setCommand(command);
    getSessionBean1().getRequerimientoRowSet().getCommand();
    getSessionBean1().getRequerimientoDataProvider().refresh();
    } catch (Exception e) {
    error("No puede levantar comando");
    log("Cannot switch to person " +
    estados.getSelected().toString(), e);
    The DropDownList implement the ProcessValueChange Event with AutoSubmit On Change properties. At Change choise of DropDown List Component it trigger a event that and execute estados_processValueChange method that to show a table rows accord to the new filter (include the new calendar date if necessary that follow:
    String command = "SELECT ALL codreqgmc, fechareq,cliente.nomclie,estado.Descripcion as Estado, " +
    "requerimiento.codtecnico, requerimiento.rutclie, requerimiento.codestado " +
    "FROM requerimiento,cliente,estado " +
    "WHERE requerimiento.rutclie=cliente.rutclie and requerimiento.codestado=estado.codestado and fechareq>=" + "'" + formatoFecha.format(calendar1.getSelectedDate()) + "'" +
    "AND fechareq<=" + "'" + formatoFecha.format(calendar2.getSelectedDate()) + "'";
    try {
    getSessionBean1().getRequerimientoRowSet().setCommand(command + " AND requerimiento.codestado =" + "'" + (String) estados.getSelected() + "'");
    getSessionBean1().getRequerimientoRowSet().getCommand();
    getSessionBean1().getRequerimientoDataProvider().refresh();
    } catch (Exception e) {
    error("No puede levantar comando");
    log("Cannot switch to person " +
    estados.getSelected().toString(), e);
    The Table component have a column of checkbox type for select a particular(s) row(s). With a Button it to choose all the rows that has been to set checkbox, in the session bean to save this selected rows and link to another page that show the details about seletec rows.
    The Problem
    Every time that i press the button, after to the select the rows, for another page showme detail, this page is empty because it execute the init method before the button_action, to re initialize and erase the user selection and lost it
    I try with another component that trigger event, por exmaple dropdownlist, and it the same, even to press the pagin in teh table it execute init meth, re-initialize and erase all.
    Result prove
    1.- I execute the application for first time:
              Execute      Init()
    2.- I Chage choos en the DropDownList
              Execute      Init() and
              after           estado_processValueChange()
    3.- I change choos again in the DropDownList
              Execute      Init() and
              after           estado_processValueChange()
    4.- I press pagin button in table
              Execute      Init()
    5.- I press button detail, for detail
         Execute      Init() ----> I reinitialize and lost the user select.
         after          Butoon_action
    How ia can to preven that every time it execute init(),
    Why alway it execute init method?, the init methd() is for initialize application and not RE INTIALIZED
    Why is the relation INIT(); PREPROCESS(), PRERENDER(), PROCESSVALUECHANGE, BUTTON_ACTION. What it execute first, what secodn?
    I need execute init method only one , at first time
    I hope i undertandme, i not native english.
    Thank for advance

    Anupama,
    Do you mean init or wdDoInit? You cannot call the later as well as you cannot call any WD-framework methods that start with "wd" prefix.
    By the way, wdDoInit in component controller (do not confuse with custom controller or interface controller) is called before any other method in any controller. So I hardly believe that it is not called when your view become available.
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

  • Init method in Weblogic 5.1 gives  problem

              I have used init method in 4.5
              the same method gives problem in 5.1
              C:\weblogic\myserver\classfiles\jsp_servlet\_addcontract.java:89: The method void init(javax.servlet.ServletConfig) declared in class jsp_servlet._addcontract cannot override the final method of the same signature declared in class weblogic.servlet.jsp.JspBase. Final methods cannot be overridden.
              probably occurred due to an error in /addContract.jsp line 11:
              

    Use jspInit method.
              harish <[email protected]> wrote:
              > I have used init method in 4.5
              > the same method gives problem in 5.1
              > C:\weblogic\myserver\classfiles\jsp_servlet\_addcontract.java:89: The method void init(javax.servlet.ServletConfig) declared in class jsp_servlet._addcontract cannot override the final method of the same signature declared in class weblogic.servlet.jsp.JspBase. Final methods cannot be overridden.
              > probably occurred due to an error in /addContract.jsp line 11:
              Dimitri
              

  • Hi, why do we use the break and continue structure?

    Hi, I was wondering why do we use the break and continue structure in some program such as:
    for ( int i = 1; i <= 10; i++ ) {
    if ( i == 5 )
    break;
    So, now why do we use those codes, instead of achiving the same results by not using the if structure.
    I am new in java so I can be totaly wrong that is why my question come to you guys.
    I will appriciate if you let me understand more.

    I may not completely understand your question, but - imagine the following scenario:
    // Looking for some value in a long, unsorted list
    Object target = null;
    int index = -1;
    for (int i = 0; i < list.size(); i++) {
        Object curObject = list.get(i);
        if (curObject.equals(source)) {
            target = source;
            index = i;
    if (target != null){
        System.out.println("Found it at " + index);
    }You will always run through the entire long list, even if the thing you are looking for is the first thing in the list. By inserting a break statement as:
    // Looking for some value in a long, unsorted list
    Object target = null;
    int index = -1;
    for (int i = 0; i < list.size(); i++) {
        Object curObject = list.get(i);
        if (curObject.equals(source)) {
            target = source;
            index = i;
            break;
    if (target != null){
        System.out.println("Found it at " + index);
    }You can skip whatever's left in the list.
    As for continue, yes, I suppose you could use a big if, but that can get burdensome - you end up with code like:
    for (int i = 0; i < list.size(); i++) {
        Object curObject = list.get(i);
        // you want to do the rest only if some condition holds
        if (someCondition) {
            // do some stuff -
            // And you end up with lots of code
            // all in this if statement thing
            // which is ok, I suppose
            // but harder to read, in my opinion, than the
            // alternative
    }instead of
    for (int i = 0; i < list.size(); i++) {
        Object curObject = list.get(i);
        // you want to do the rest only if some condition holds
        if (!someCondition) {
            continue;
        // do some stuff -
        // And you end up with lots of code
        // all outside of any if statement thing
        // which is easier to read, in my opinion, than the
        // alternative
    }Hope that helped
    Lee

  • A simple ALV report using classes & methods ...

    i want a  simple ALV report using classes & methods ...
    my requirement : i have to use classes & methods instead  of calling a function module to display in grid or list format.
               plz send me with explanation ASAP...it's very urgent..
               Thanks in advance .

    Hi
    Please refer
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/e8a1d690-0201-0010-b7ad-d9719a415907
    U can use methods for vreating ALVs.
    There is a method named set_table_for_first_display in OOP Concepts.
    Use this Object Oriented Approach for ALV Creation
    Calling the method set_table_for_first_display
    CALL METHOD cust_alv->set_table_for_first_display
    EXPORTING
    is_layout = gst_layout
    CHANGING
    it_outtab = gt_list
    it_fieldcatalog = gt_fcat
    EXCEPTIONS
    invalid_parameter_combination = 1
    program_error = 2
    too_many_lines = 3
    OTHERS = 4
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    Object Creation and all
    Creation of Object for Container
    CREATE OBJECT cust_container
    EXPORTING
    container_name = 'ALV_CONTAINER'
    EXCEPTIONS
    cntl_error = 1
    cntl_system_error = 2
    create_error = 3
    lifetime_error = 4
    lifetime_dynpro_dynpro_link = 5
    others = 6
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    Creation of Object for ALV Grid
    CREATE OBJECT cust_alv
    EXPORTING
    i_parent = cust_container
    EXCEPTIONS
    error_cntl_create = 1
    error_cntl_init = 2
    error_cntl_link = 3
    error_dp_create = 4
    others = 5
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    Layout settings
    gst_layout-zebra ='X'.
    gst_layout-cwidth_opt = 'X'.
    CALL FUNCTION 'LVC_FIELDCATALOG_MERGE'
    EXPORTING
    I_BUFFER_ACTIVE =
    I_STRUCTURE_NAME = 'ZCS_INACTV_CUST'
    I_CLIENT_NEVER_DISPLAY = 'X'
    I_BYPASSING_BUFFER =
    CHANGING
    ct_fieldcat = gt_fcat
    EXCEPTIONS
    INCONSISTENT_INTERFACE = 1
    PROGRAM_ERROR = 2
    OTHERS = 3
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    Calling the method set_table_for_first_display
    CALL METHOD cust_alv->set_table_for_first_display
    EXPORTING
    is_layout = gst_layout
    CHANGING
    it_outtab = gt_list
    it_fieldcatalog = gt_fcat
    EXCEPTIONS
    invalid_parameter_combination = 1
    program_error = 2
    too_many_lines = 3
    OTHERS = 4
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    For object oriented concepts refer this link https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/b6cae890-0201-0010-ef8b-f970a9c41d47
    Reaward if helpful

  • Using Accessor Method from Within Considered Best Practice?

    I was wondering what is considered best practice in the AS3 world regarding this topic.
    In C++ and .NET world, as well as PHP I would consider using accessor methods, instead of directly accessing the class property, bad practice due to unnecessary overhead.
    What are your thoughts in this?

    Getters and setters and bindable vars can be public, protected or private.  Which one you choose follows standard object-oriented practices.
    is just like a macro that defines a particular get/set pair.  I would only use it on vars.  Using it on a getter simply wraps the getter in another get/set pair which is wasteful.  The Flex Framework rarely uses .  Instead, we typically define get/set pairs with metadata so we can control what event fires and when.  It also saves SWF size because the compiler doesn't have to generate a long and ugly name to avoid name collisions.
    Alex Harui
    Flex SDK Developer
    Adobe Systems Inc.
    Blog: http://blogs.adobe.com/aharui

Maybe you are looking for

  • Spontaneous Error Code 201003 for PCI DAQ Setup

    In lab we have been using a BNC-2120 connector block plugged into a PCI-6033E.  The arrangement seemed to be functioning fine for preliminary testing and a first round of experimenting, though during that round we couldn't seem to get a signal from o

  • Why i need all that b***s*** for installing oracle db?

    As all you know to install for instance oracle 11g on redhat, oel, centos, fedora, etc... oracle recommends to install more than 600MB of garbage in the OS... For instance if we have a minimal redhat install we would need to install more than 580 pac

  • Issue with Attachment download from Mail?

    I am having an issue with an attachment. I opened the attachment from an email account on my iPad2 and the screen has just gone black. Mail will not let me out of trying to view the attachment. I tap on the screen and nothing happens. It has frozen m

  • Check box column trouble

    Hi ! I am new with java server faces. What i am trying to do now is adding a check box column to a rich extended data table, i did this adding a new column with a h:selectBooleanCheckbox inside of it. The trouble is that i could not syncronize my che

  • Abnormal increase of used size in oracle home directory

    Hi all, I have a production database Oracle 10g R2 (10.2.0.1.0) on HP-UX 11.23 and the /oracle directory is having 74 GB size. when i check the size of the /oracle mountpoint today it is showing 45 % used whereas it is 33 % yesterday eveining. the ch