Followers

Friday, 29 June 2012


FaQs

Q: ServerSocket or DatagramSocket? What is better to use in my applications?

Answer: Both of them are good. It depends on task you do.  DatagramSocket is designed for UDP and ServerSocket for TCP.  TCP is more reliable in terms that it ensures delivery, UDP not.
But UDP packets are much smaller and have no such big headers like TCP packets have.
If it is smaller then there is more probability that it arrives faster. UDP used mostly in areas where you do no mind about retransmission. You just do not need this, because information become obsolete. Sound, for example. It is better to make small pause or repeat last packet than to
play some piece that was send first but received second.  It is up to you to take decision. If you do not mind that can lose small piece of data - use UDP. Otherwise use TCP.

Q: I read this statement: "The main thread must be the last thread to finish execution. When the main thread stops, the program terminates." Is it true?

Answer: Absolutely wrong!  The correct one: When you start a program, JVM creates one thread to run your program. The JVM creates one user thread for running a program.  This thread is called main thread.  The main method of the class is called from the main thread. If program spawns new threads from the main thread it does stop until last thread id died.  Even if the main thread dies program keep running.

Q: What is asynchronous architecture?

Answer: In asynchronous architecture a program does not wait for return immediately. The program continues to do another staff and does not care when it will happen.  Simple example: modeless dialog. You can do something else and return later to that dialog, change something and press "Apply" button.  Synchronous example: modal dialog call, the procedure call it will
not continue until the model dialog returns.  For example, when you try to delete files you will be asked: "Are you sure that you want to delete file(s)?" You can not continue until you press
"Yes", "No" or "Cancel".

Q: Why C++ is not platform independent?

Answer: C++ compiles to binary code (.obj, .exe, .dll, a.out etc.). Binary code (Machine code, 0's and 1's) are machine dependent.  Java compiles to byte code which is independent of any machine.  It need to be interpreted to binary code by JVM, and executed by the machine.

Q: I have heard that String concatenation operator "+" affects performance of program if it used much. Is it true?

Answer: Yes, it affects your program performance if you do a lot of "+" operations with strings:
A new StringBuffer must be created, then two arguments are added to it with append(), and the final result must be converted back with a toString().  Your time and space is wasted...
In case if you are appending more than one String, try to use a StringBuffer directly.

Code example: I want to show you one funny thing! The code is shown below is simplest that you can imagine and does very unusual thing!
 It is slightly bigger than "Hello World!" program but does much more. It lists all files in the current directory if you run it like this:
 java test * (of course after compilation) in DOS/CMD prompt on Windows or in any shell in UNIX.

The program shows all files both in Unix and Windows. If you do: java test. * On UNIX it also shows all hidden files.

class test{
public static void main(String args[]){
 for (int i = 0;i < args.length; i++) {
 System.out.println("File " + i + ":" + args[i]);
          }
      if (args.length<=0) {
 System.out.println("No files!");
}
     }
     }

You can ask how can we get this list without any file handling functionality in the code? Indeed looks mysterious...
But in reality everything is very simple. When you type "*" (wildcard) OS (DOS, Windows, UNIX), not Java (!!!) sends the list of files in the current directory to your program as a list of parameters. And you see this list...

Q: When can I use System.exit() in servlets?

Answer: Never! Depends on server you run on...
Security exceptions on good server or full shut down for simpler one

Q: I was writing and testing some servlet program. Now I decided to remove it from our web server. But it is still there causing confusion to another developers I am working with. How can I unload my servlet explicitly?

Answer: It depends on server you use. Often you can unregister your servlet somehow. Easier way to make your servlet empty (remove all code), compile it and copy class file to server. Many servers reload automatically a new class if they see it was changed. You will still have your servlet on the server but it will do nothing and nobody will complain...

Q: By default an application has no security manager and Java runtime environment does not create automatically a security manager for my program. How then applet where I am not creating any security manager already prevented from many operations?

Answer: It is true - Java by default let you do whatever you want and then it is your responsibility to restrict something. In case with applets a little bit different story - applet viewers and browser have THEIR OWN security manager, not from JRE. That's why even if you did not define any security manager in the code of your applet, during the start up time browser/viewers will use their own security manager. This manager is built in into their application (browser, viewer), not your Java applet.

Q: I the see method getClass() in java.lang.Object. Do we need it? I know all my classes.

Answer: Exactly. If you know - you do not need it. But if you do not know then it helps you. For example if you get some object and would like to instantiate it: Object createNewInstOf(Object obj) { return obj.getClass().newInstance(); }


Q: I know that Java file should have the same name as public class in the file..   But what are rules for files that have no public classes?

Answer: No rules are defined for such case! It is up to you how to name it. Please check my example:


// ******   ABCDEFG.java   file  *******************
          class G {
             public static void main(String[] args) {
                System.out.println("This is class G!");
             }
          }
          class Z {
             public static void main(String[] args) {
                System.out.println("This is another class Z!");
             }
          }
          class AB {}
          class CD {}
          class EF {}
After compilation you will get AB, CD, EF, G and Z classes.  You can run G and Z (they have main method), but not AB, CD, EF.
Try it: java G  or  java Z

Q: I am currently working on a program for generating a landscape from a bitmap.  I use lots of 4-Point-QuadArrays next to each other and set the vertexes z-positions according to values from a grayscale bitmap.  It looks pretty OK but is very memory intensive (at 150X150 QuadQrrays i get a memory exc.).

Answer: You might want to try the utilities that I've written and are part of the j3d.org code  repository. Instead of a QuadArray per pixel, I just generate one large array for the entire image.
You control the size of the quads by the size of the image :)

It also sounds like you are doing some automatic terrain generation, so you might want to have a look at the fractal terrain generator that is also part of the package. Here's the pages:


and Javadoc


Q: I am planning on making a MRU(Most Recently Used) list and allowing the user to configure some primitive directory settings, like where to look for images, other data, etc.  I have a class fairly well worked out in my brain to accomplish these goals.  It's not rocket science.  It does, however require that a file be written to store the information, and the application needs to be able to discern from whence the information should be read when started.  In C++, I have stripped the directory from which the application was run (from argv[0]) and saved my "ApplicationSettings.cfg" file in that  directory.  Any thoughts as to how to accomplish this?

Answer: Check the API documentation for JDK1.4 beta:
===========================
public abstract class Preferences extends Object

A node in a hierarchical collection of preference data. This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store.  Typical implementations include flat files, OS-specific
registries, directory servers and SQL databases.  The user of this class needn't be concerned with details of the backing store.
============================

Note the bit about 'needn't be concerned with details'.  The ugly problem of where to put such preference data has been abstracted away from the developer, which makes life much easier.  The Preferences API is part of JDK 1.4, which is available in beta form now, with a production release in the near future.

Q: I am writing a Java Applet program which pop up a Window, However, there is a Warning:Java Applet..." message appears at the bottom of the windows.  Do you know how can I remove this, or Can I rewrite the wording, for example, write company info instead of the "Waring:Java Applet ....."?

Answer: The rule for writing secure application is to use encapsulation.  Always make variables PRIVATE.  One of Sun's programmers, whose name I do not mention here, did not follow that
idea.

He wrote the class Window like this:

public class Window extends Container{
     String warningString;
     ......
     private FocusManager focusMgr;
     private static int nameCounter = 0;
     .....
}

What you do is like this:

Write:

package java.awt;
public class SetWarning {
     public static void setWarning(Window w){
        w.warningString = "";    /*disable warning string*/
     }
}

Compile this file and then put the class SetWarning.class inside the subdirectory java\awt somewhere onto the classpath, and you suddenly have gain access to the internal of the java.awt package.  Include whatever need be in your final product.

Q: Can I access a private variable of one Object from another Object?

Answer: Yes, if this object of the same class. You can access private field from static method of the class through an instance of the same class.
Check one example below:

public class Example {
         private int privateVar;
         Example(int a) {
           privateVar = a;
           System.out.println("private privateVar = " + privateVar);
         }
         public static void main(String[] args) {
           Example ex = new Example(5);
           System.out.println(ex.privateVar);
         }
       }
Q: I understand multi-threading as "parallel instances of execution" and I have a query in this regard. The following is a code and its output. I would like to how will you describe "what exactly is the join() method doing?".

Answer:  join() is a left over from UNIX days of doing process synchronization (via the infamous fork/spawn mechanism). join() makes the current thread (the one where you call T.join()) wait
until the thread that it is called on (namely T) dies (or is interrupted).  This is useful in the case where, for example, your main thread had to do additional work AFTER the other threads were finished doing theirs. join guarantees that the only way that the call to join will return is if the target thread is dead.

There's a good book on java multithreading that you might want to read "Java Threads" by Scott Oaks & Henry Wong.

Q: I run some code in my program like this:

Runtime rt = Runtime.getRuntime();
rt.exec("C:/StartMyApp.bat");

I get very strange behavior: sometime it starts from first time, sometime I need to call it a few times and often  it does not start at all after I run it once..

Answer: You need to modify your code since you execute your bat file in the MSDOS shell (Win95/98) or command line shell"cmd.exe" (NT).  You should use exec(String[] cmdarray) not exec(String cmd) method...

Q: I have a question between C and Java Language. In C, I want to call a Java Library, as Java calls C library in Java.  In Java, I can call a C function and execute an application program by using JNI Mechanism.  But can I call a library of Java Class in C ?

Answer: Not easily. But you can execute a Java program from C.  If you really need to call Java from C, write a Java program that does what you want and "call" it.

Q: Why Servlets are better than CGI scripts?

Answer: Generally, every new client's request to CGI script starting a new process. With servlet web server starts just a new thread that is much cheaper in terms of time for starting up, memory and CPU consumption.  JVM uses just one process.  This answer is right for "standard" CGI. Now appear new modules for Perl that uses the same approach as servlet does. Anyway, writing large programs on Java is much easier than on Perl, atleast for me.  Java has also very rich API.

Q: I can't find the API documentation on any classes in the sun.* packages. Where is it?

Answer: The short answer is that SUN provides documentation only for the public classes in java.*. SUN does not provide documentation for sun.* because those are the Sun-specific
implementation, and specifically not part of the Java technology API standard, and are therefore subject to change without notice.
In general, SUN doesn't provide javadoc documentation for sun.* classes in order to discourage developers from writing programs that use them. For further explanation, see the next question.  However, if you must have it, the documentation for sun.* is available separately, here: http://java.sun.com/communitysource/index.html For example, the doc comments for sun.net are in the source files located at:     /src/share/sun/sun/net/*.java  This source code release does not include javadoc-generated documentation. You would have to generate those docs yourself
using javadoc. source:


Q: My friend claim that garbage collectors do not collect int value since they are not created with new() method..  Is he right?

Answer: Programmers know about the importance of initialization, but often forget the importance of cleanup. After all, who needs to clean up an int? But with libraries, simply "letting go" of an object once you're done with it is not always safe. Of course, Java has the garbage collector to reclaim the memory of objects that are no longer used. Now consider a very unusual case.  Suppose your object allocates "special" memory without using new.  The garbage collector knows only how to release memory allocated with new, so it won't know how to release the bject's "special" memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Here's how it's supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object's memory. So if you choose to use finalize( ), it gives
you the ability to perform some important cleanup at the time of garbage collection.

Q: In my program where I use finalizers to help GC to free the memory faster... But it seems that it is difficult to know when it happens. I tried to find it and see that even on the same machine my program runs differently...

Answer: You are right! Garbage collection happens differently each time because it based not on definite schedule but quite complicate alghorithms that take into consideration many factors
such as CPU load, number of variables, memory size and so on.  Even developers of JVMs just guess when some process can start but not exactly. Since we have many JVMs, Java programmers, therefore, should avoid writing code for which program correctness depends upon the timely finalization of objects. For example, if a finalizer of an unreferenced object releases a resource that is needed again later by the program, the resource will not be made available until after the garbage collector has run the object finalizer. If the program needs the resource before the garbage collector has gotten around to finalizing the unreferenced object, the program is out of luck.

Q: I do not understand the difference between clone() and new().  Why shouldn't I just call new()?
Can apply new() to cloned object?

Answer: The difference is that clone() creates the object that possibly has changed fields (after start up) and this object is willing to be cloned by implementation Cloneable interface.  New() method can be applied without  objects "permission" and create a new instance with fields just initialized and not changed.  They will be changed later during runtime. Clone() "mirroring" this modified object.  That's why you NEVER should call new() on cloned object. You can destroy the clone...

Q: We need to authenticate a user on the local Linux system before he/she/it can log on to the application and begin taking over the world. Since the Linux system uses shadow passwords, we must have a method to retrieve the password and authenticate the user in the user shadow database. Once authenticated, this user can work with the application.  How it can be done in Java?

Answer: It can be done, it is already done!  Here if you are interested in interfacing C with Java in Linux (the JNI Solution):  

Advice: If you are C/C++ programmer be careful with shortcut assignment operator "+=" in Java when you work with Strings!

Why: The shortcut assignment operator += when used with Strings may confuse C and C++ programmers at first. Recall that a += b is equivalent to a = a + b. Let's look at two code samples written in C++ and the Java programming language:

//C++ code
string*  s1 = new string("hello");
string*  s2 = s1;
(*s1) += " world";
cout<<*s1<<endl<<*s2<<endl;
return  0;
//s1 = s2 = "hello world"

  //Java programming language code
String s1 = "hello";
String s2 = s1;
s1 += " world";
System.out.println(s1 + "\n" + s2);
//s1 = "hello world" and  s2 = "hello"


In the C++ example, the strings s1 and s2 print the same result because they both point to the same address. In the Java programming language, Strings can't be modified, so the + operator
must create a new String when "world" is appended to s1.

Q: What is difference between:
String My = "Test";
and
String My = new String ("My"); ?
Answer: Because the compiler automatically creates a new String object for every literal string it encounters, you can use a literal string to initialize a String.

String s = "Test";

The above construct is equivalent to, but more efficient than, this one, which ends up creating two Strings instead of one:

String s = new String("Test");

The compiler creates the first string when it encounters the literal string "Test", and the second one when it encounters new String.

Q: Why the String does not have a capacity method?

Answer:  The String class doesn't have a capacity method, because a string cannot be changed.

Q: Why can not I compile this simple example?

public class Test{
    int a;
    final static int fin;
    final int finint;
}

Answer: You can not compile it because you have to initialize final variables. It must be done explicitly.

Q: Can someone point me to some resources that explain how JSP and Servlets work together?
I am trying to develop a small project (to learn JSP and Servlets) that is similar to a banking transaction where I want to use JSP and Servlets.
I would ideally like to do something like this.

1. Get some input from the user in a HTML form.
2. Send this data to the database.
3. Get the reply from the database for user queries.
4. Print the results to the user.

It was suggested that I use JSP to display data and Servlets to interact with the browser. But I was not able to find a concrete example. Any help regarding this would be greatly appreciated.

Answer: Here is how this stuff works, generally:
1) The form (regular html) sends the request to a servlet that does all of the processing and stores the results in standard javabeans (not ejb) in the context that you want (either request
context or session context).
The things that the JSP is going to use need to be properties of the javabeans that are accessible with the normal getters and setters (i.e. street needs to be accessible by getStreet method
and city needs to be accessible with getCity method). You can create as many of these beans as you need to accomplish your purpose and store them in the context that makes sense for your
app.

2)  Get a request dispatcher from the ServletRequest using getRequestDispatcher("/") and call its forward method to transfer control to a JSP.  If you have been diligent in designing the beans, you will not need any java code inside the JSP to write your page back to the browser.  If the JSP has form stuff in it, you can send that form data off to another servlet and start the cycle over again.

This whole scheme has been enhanced for internationalization and other stuff with the Struts framework (http://jakarta.apache.com).  You will  be  able to accomplish your modest goals with the information above.

Q: Do I need to call Garbage Collector gc() explicitly? If not why then does exist this method?

Answer: Do not afraid, if you do not call gc() it will run anyway! You can be sure that GC-ing happens anyway... Why does SUN provide us such method? I see two reasons at least for having it: 
1. Time critical applications. If you know that in some moment it is safe to run GC call it. Probably it will run immediately. Not always.  Anyway it can provide better distribution of GC-ing in time increasing GC activity in "safe" time

2. Test applications. It can help you to be sure that your objects will be collected faster than usually.

Q: Does Garbage Collection hang my program for a while?

Answer: Well, of course it somehow "hungs" if you run your program on one CPU. Not in terms that it hungs until some GC-ing is over.  Usually well written GC runs in own thread, alongside to your Java program and not more time than any other thread.  Your program will not wait until some point is reached in GC but rather wait some amount of time which the GC-ing thread allowed to take.

Q: I write my first applet and it become very huge! It is an applet but looks like huge Java Application.  Could you point me what is most important for having a small applet?

Answer: 
1. Use compiler optimization: javac -O But check it the size anyway. Sometime it makes the code bigger.
2. Use jar files instead of class files.
3. Try to use inheritance as much as possible: than more code you can reuse than less new lines you have to add.
4. Try to use standard APIs. Often they are better optimized in size than some private exotic packages. Of course often they have better methods and so on but try to use efficiently what we have already!
5. Use short names.
6. Do not initialize big arrays because. They will be initialized and put directly into bytecode. You can do it later on the fly.

Q: Main disadvantage of Java GUI is that it is often slow. But I have seen also very fast working GUIs. Unfortunately the code is hidden and I do not know the technique for writing of fast Java
GUIs.

Answer: I can describe one of main technique you can use. It does not give you full solution, but will certainly speed up your GUI.  The main idea is to use "lazy" initialization. Instead of creating and initializing of all GUI components in constructors during start up time postpone it to later time until you really need. Let say, you have a lot of tab panels with many elements on each tab panel.  Your constructors should be "quite" empty and do not create and initialize those small elements until your tab panel is chosen.  You should have very small constructor for tab panel itself and additional lazy constructor for the rest. It should be called when user clicks on that particular tab.  This does not decrease the full time of initialization, but spreads it up. The user will not feel big delays during start up of your application. You should use these lazy constructors just before you are going to call any paint method.

Q: Could you give me simplest example how to do print in Java?  I will work out it myself :-)

Answer: Please compile and run it! It will draw empty rectangle (you see I save your inks!)

import java.awt.*;

public class print {

   public static void main(String args[])
   {
     Frame frm = new Frame("JavaFAQ_test");
     frm.pack();

     PrintJob printJob =
       frm.getToolkit().getPrintJob(frm, "print", null);

     if (printJob != null) {
       Graphics grphcs = printJob.getGraphics();

       grphcs.drawRect(50, 50, 150, 100);

       grphcs.dispose();

       printJob.end();
     }
     System.exit(0);
   }
}

Question: Please describe shortly J2ME and what is different comparing to J2SE and J2EE?

Answer: It will not be shortly :-) ...
J2ME is SUN's Java version for machines with limited amount of memory (RAM 128 KB)and  low performance (comparing to desktop versions such as PIII) processors.  The main difference from J2EE and J2SE is that it has a set of different profiles.

J2ME consist of three parts:
    1. Java virtual machines* that fit inside the range of consumer devices.
    2. APIs that are specialized for each type of device. 
    3. A profile, that is, a specification of the minimum set of APIs useful for a particular kind of 
        consumer device (set-top, screenphone, wireless, car, and digital assistant) and a   
        specification of the Java virtual machine functions required to support those APIs. Each
        profile is designed for specific hardware type - mobile phone, PDA, microwave oven and so
        on. Profile contains minimum libraries that are enough to support the particular device. The
        program is designed with profile for mobile phone does not contain many classes that must
        be used by oven oven, for example. Each profile uses JVM that uses some subset of JVM     
        from J2SE and J2EE. Usually the program that you write for J2SE or J2EE will not run on  
        J2ME JVM.

SUN already released two profiles:
1.     The Foundation Profile is a set of Java APIs which, together with the Connected Device 
Configuration (CDC), provides a J2ME application runtime environment targeted at next-generation, consumer electronic and embedded devices.
2.     The Mobile Information Device Profile (MIDP) is a set of Java[tm] APIs which, together with the Connected, Limited Device Configuration (CLDC), provides a complete J2ME application runtime environment targeted at mobile information devices, such as cellular phones and two-way pagers.

To be able to write a program with J2ME you must use profile's implementaion - configuration. Profiles define only specification.

SUN has two profiles now:
1.     Connected Device Configuration (CDC) and C virtual machine CDC is a Java Community  
Process effort that has standardized a portable, full-featured Java[tm] 2 virtual machine  building   block for next-generation, consumer electronic and embedded devices. CDC runs on top of the C Virtual Machine (CVM) that is provided as part of this release.
2.     Connected Limited Device Configuration (CLDC) and K virtual machine. CLDC Java 
Community Process effort that has standardized a portable, minimum-footprint Java building  block for small, resource-constrained devices. CLDC runs on top of Sun's K Virtual Machine (KVM) that is provided as part  of this release.

Also SUN provides developers with J2ME Wireless Toolkit The J2ME Wireless Toolkit is a set of tools that provides developers with the emulation environment, documentation and examples needed to develop CLDC/MIDP compliant applications.

Question: Can anybody tell me what an API is...

Answer: It stands for "Application Programming Interface" and is used to mean the collection of packages, classes, and methods that expose a proprietary implementation to an external user.
That's a pretty good definition, but I would qualify it a little bit.

"Proprietary" usually, in the vernacular, means "tied to a particular vendor's tools".

A lot of APIs are not tied to any particular vendor. One example is the C standard library. In that library, there is a common definition and syntax for a function to print to a file:

int printf(const char *format, ...);
and that function is considered to be part of the standard C API
and not tied to anything proprietary.

As well, any vendor can write a library and sell it, and it'll have its API, and that will be considered "proprietary."

An API can be either proprietary or non-proprietary.

Now, this is a Java group, and the standard Java API could be considered to be a proprietary Sun library. I'm aware that Sun considered and rejected the idea of giving ownership to all things
Java to the international standards committees.

But for our intents and purposes, we can call the standard Java library "non-proprietary", if only by virtue of the fact that we can get implementations of it from IBM and other sources.

Some might disagree with this, but that's okay, I don't feel strongly about it, and I'm not a software contract lawyer, thank goodness.

Question: I am quite new to JavaBeans and having some difficulty with making threads work with it.  I wrote a thread class and I want to use it in a visual builder (specifically VisualAge). I want to drop the class as a bean on the composition screen and then connect its output to other beans
and so on.  Only problem is I don't know how to start this thread

Answer: One way would be subclass the bean into a runnable subclass that also inherits from Runnable, like so:

MyBean <--extends-- RunnableMyBean ---implements--> Runnable

You could then call the run() method in the RunnableMyBean class by invoking RunnableMyBean.start().

Question: What are Thread Groups useful for? I do not see big reason to have them in Java API...

Answer: From the beginning Thread Groups were added for security reasons. Assumed, that not trusted code from third parties will run in dedicated Thread Group. Of course it can not affect the
rest of program. Those threads from external companies were not allowed to start, stop and suspend your threads. Then this model is changed and we have no such protection now.  Now the Thread Groups will let you a little bit easier manage your threads. You can manage many threads simultaneously rather than each separately. For example you can set maximum priority level, call suspend(), interrupt() on all threads in your group. Also giving good names will help you to easily track and debug your program.

Question: Could you give me an example how to generate TCP/IP packets? I need to write my first network program.

Answer: There is no need to write such program. Java hides this implementation from you. Just use java.net.Socket or java.net.ServerSocket class and use appropriate constructor.  Easy and fast!  If you want even faster, use the method setTcpNoDelay(true) :-)

Question: What is difference between Java Compiler and Java Interpreter?

Answer: Java compiler is a program that translates Java language code (you write program x.java) into the bytecode (x.class) for the Java Virtual Machine.  Another program that actually implements the Java Virtual Machine specification and runs bytecode is an interpreter program...


Question: Well, you say (see tip above) that compiler is a program that translates source code (x.java) into bytecode (x.class).  What is JIT compiler?  How can we have two compilers and where the JIT compiler takes my source code (if I already compiled it)?

Answer: The name "JIT compiler" is good enough to confuse people!  Indeed, what does it compile, if we have done the compilation after a program was checked and compiled by javac, for example?  JIT is a part of the JVM and what it does is an optimization of java bytecode to be able to run it much more efficiently on a current OS. Main difference from javac compiler is that JIT does it on the fly and taking into consideration much more things than javac.  Javac just compiles the code into bytecode and actual optimization happens during a run time in JVM with help of JIT.

Question: I read it on http://java.sun.com/docs/books/tutorial/java/javaOO/override.html:  "Also, a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. A subclass can HIDE a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass. "
My question: It looks like play with words: override, hide.. Why is it written HIDE?  If I can write a static method in subclass with the same signature it means that I override that method in superclass, I really changed that method here in subclass. Am I wrong?

Answer: Let's start from the very beginning - definition for overriding. It includes three main points that overridden method must:
* have the same name
* have the same signature
* have the same data type.

In your case the static method in subclass can have another data type.
Example:

************ Alex.java *************
package alex;
public class Alex {
     static String al(String name){
         return name;
     }
}
******************** EOF ***********
************ John.java *************
package alex;
public class John extends Alex {
     static int al(int name){
         return name;
     }
}
******************** EOF ***********
It compiles! You see that in Alex class the method "al" returns String and in John class - int.  It is hiding, not overriding.  Advice: try to avoid such situation when you hide methods in super class. Use different names instead and you will save a lot of time.

Question: Constructors are similar to methods... I know that they do not return any value. Could I say that they have void type (no return type)?

Answer: Not. Constructors are not methods and they are different because they:
* always have the same name as the  class name
* have no return type, even void!
* are not inherited and that's why (by the way) you can declare them final.
Question: I know that void method does not return any value. But I still write the code like this:

void nothing() {};
void nothing2() {return;};

Why can we still use "return" in the body of method?

Answer: To be able to exit method when it is necessary.  You can exit the method when you reach the end of method and do not need to use "return".  If due to some condition program must exit the method then you use "return".


Question: Protected members in Java and C++. What is difference?

Answer: C++ also has 3 levels of protection: private, protected and public.  They act pretty much the same way. There are no packages in C++ and that’s why protected members are accessible to subclasses only, not to whole package as in Java.

Question: I know that it is possible to create threads by two different ways. What is essential difference? What is better and when?

Answer: that's right! We can create a new thread by subclassing Thread:
public class MyBestThread extends Thread {...

Also we can do it by using Runnable interface. The difference is that by implementing Runnable we change just run() method keeping the possibility to subclass something more useful...
The difference between these two methods is really small and often makes no sense.




What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.
  • Model : The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

  • View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

  • Controller:The controller reacts to the user input. It creates and sets the model.

More about Model-View-Controller Architecture >>


2.What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.
3.What is Struts framework?
Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
4.What are the components of Struts?
Struts components can be categorize into Model, View and Controller:
  • Model: Components like business logic /business processes and data are the part of model.
  • View: HTML, JSP are the view components.
  • Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

5.What are the core classes of the Struts Framework?
Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.
  • JavaBeans components for managing application state and behavior.
  • Event-driven development (via listeners as in traditional GUI development).
  • Pages that represent MVC-style views; pages reference view roots via the JSF component tree.
6.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request.

7.What is role of ActionServlet?
ActionServlet performs the role of Controller:
  • Process user requests
  • Determine what the user is trying to achieve according to the request
  • Pull data from the model (if necessary) to be given to the appropriate view,
  • Select the proper view to respond to the user
  • Delegates most of this grunt work to Action classes
  • Is responsible for initialization and clean-up of resources

8.What is the ActionForm?
ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

9.What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().

10.Describe validate() and reset() methods ?
validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.
public void reset() {}

11.What is ActionMapping?
Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.

12.How is the Action Mapping specified ?
We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from <ActionMapping> configuration element of struts-config.xml file

<action-mappings>

 <action path="/submit"

        type="submit.SubmitAction"

         name="submitForm"

         input="/submit.jsp"

         scope="request"

         validate="true">

  <forward name="success" path="/success.jsp"/>

  <forward name="failure" path="/error.jsp"/>

 </action>

</action-mappings>

13.What is role of Action Class?
An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

14.In which method of Action class the business logic is executed ?
In the execute() method of Action class the business logic is executed.

public ActionForward execute( 

            ActionMapping mapping,

             ActionForm form,

             HttpServletRequest request,

             HttpServletResponse response)

          throws Exception ;

execute() method of Action class:
  • Perform the processing required to deal with this request
  • Update the server-side objects (Scope variables) that will be used to create the next page of the user interface
  • Return an appropriate ActionForward object

15.What design patterns are used in Struts?
Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.
  • Service to Worker
  • Dispatcher View
  • Composite View (Struts Tiles)
  • Front Controller
  • View Helper
  • Synchronizer Token
16.Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:

<servlet>

<servlet-name>action</servlet-name>       

  <servlet-class>

        org.apache.struts.action.ActionServlet

  </servlet-class>

<init-param>

  <param-name>config</param-name>

  <param-value>

     /WEB-INF/struts-config.xml,              

     /WEB-INF/struts-admin.xml,

     /WEB-INF/struts-config-forms.xml          

  </param-value>

</init-param>

.....

<servlet>
 

17.What is the directory structure of Struts application?
The directory structure of Struts application :

Struts Directory Structure

18.What is the difference between session scope and request scope when saving formbean ?
when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.
19.What are the important tags of struts-config.xml ?
The five important sections are:
struts-config.xml


20.What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:
  • ForwardAction
  • IncludeAction
  • DispatchAction
  • LookupDispatchAction
  • SwitchAction
21.What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

22.How to use DispatchAction?
To use the DispatchAction, follow these steps :
  • Create a class that extends DispatchAction (instead of Action)
  • In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
  • Do not override execute() method – Because DispatchAction class itself provides execute() method.
  • Add an entry to struts-config.xml

23.What is the use of ForwardAction?
The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.

24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

25.What is the difference between ForwardAction and IncludeAction?
The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.

26.What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

27.What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

28.What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

29.What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.

30.What if <action> element has <forward> declaration with same name as global forward?
In this case the global forward is not used. Instead the <action> element’s <forward> takes precendence.
16.Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:

<servlet>

<servlet-name>action</servlet-name>       

  <servlet-class>

        org.apache.struts.action.ActionServlet

  </servlet-class>

<init-param>

  <param-name>config</param-name>

  <param-value>

     /WEB-INF/struts-config.xml,              

     /WEB-INF/struts-admin.xml,

     /WEB-INF/struts-config-forms.xml          

  </param-value>

</init-param>

.....

<servlet>
 

17.What is the directory structure of Struts application?
The directory structure of Struts application :

Struts Directory Structure

18.What is the difference between session scope and request scope when saving formbean ?
when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.
19.What are the important tags of struts-config.xml ?
The five important sections are:
struts-config.xml


20.What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:
  • ForwardAction
  • IncludeAction
  • DispatchAction
  • LookupDispatchAction
  • SwitchAction
21.What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

22.How to use DispatchAction?
To use the DispatchAction, follow these steps :
  • Create a class that extends DispatchAction (instead of Action)
  • In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
  • Do not override execute() method – Because DispatchAction class itself provides execute() method.
  • Add an entry to struts-config.xml
23.What is the use of ForwardAction?
The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.

24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

25.What is the difference between ForwardAction and IncludeAction?
The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.

26.What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

27.What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

28.What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

29.What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.

30.What if <action> element has <forward> declaration with same name as global forward?
In this case the global forward is not used. Instead the <action> element’s <forward> takes precendence.
What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean.

32.What are the steps need to use DynaActionForm?
Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places:
  • In struts-config.xml: change your <form-bean> to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm
<form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >

    <form-property name="userName" type="java.lang.String"/>

    <form-property name="password" type="java.lang.String" />

</form-bean>

  • In your Action subclass that uses your form bean:
    • import org.apache.struts.action.DynaActionForm
    • downcast the ActionForm parameter in execute() to a DynaActionForm
    • access the form fields with get(field) rather than getField()

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessage;

import org.apache.struts.action.ActionMessages;





import org.apache.struts.action.DynaActionForm;



public class DynaActionFormExample extends Action {

 public ActionForward execute(ActionMapping mapping, ActionForm form,

   HttpServletRequest request, HttpServletResponse response)

            throws Exception {             

  DynaActionForm loginForm = (DynaActionForm) form;

                ActionMessages errors = new ActionMessages();        

        if (((String) loginForm.get("userName")).equals("")) {

            errors.add("userName", new ActionMessage(

                            "error.userName.required"));

        }

        if (((String) loginForm.get("password")).equals("")) {

            errors.add("password", new ActionMessage(

                            "error.password.required"));

        }

        ...........

33.How to display validation errors on jsp page?
<html:errors/> tag displays all the errors. <html:errors/> iterates over ActionErrors request attribute.

34.What are the various Struts tag libraries?
The various Struts tag libraries are:
  • HTML Tags
  • Bean Tags
  • Logic Tags
  • Template Tags
  • Nested Tags
  • Tiles Tags
35.What is the use of <logic:iterate>?
<logic:iterate> repeats the nested body content of this tag over a specified collection.

<table border=1>  

  <logic:iterate id="customer" name="customers"> 

    <tr> 

      <td><bean:write name="customer" property="firstName"/></td> 

      <td><bean:write name="customer" property="lastName"/></td> 

      <td><bean:write name="customer" property="address"/></td> 

   </tr> 

  </logic:iterate> 

</table> 

36.What are differences between <bean:message> and <bean:write>
<bean:message>: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.
<bean:message key="prompt.customer.firstname"/>
<bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body.
<bean:write name="customer" property="firstName"/>

37.How the exceptions are handled in struts?
Exceptions in Struts are handled in two ways:
  • Programmatic exception handling :
Explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs.
  • Declarative exception handling :You can either define <global-exceptions> handling tags in your struts-config.xml or define the exception handling tags within <action></action> tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.
<global-exceptions>

 <exception key="some.key"

            type="java.lang.NullPointerException"

            path="/WEB-INF/errors/null.jsp"/>

</global-exceptions>
or
<exception key="some.key" 

           type="package.SomeException" 

           path="/WEB-INF/somepage.jsp"/>
38.What is difference between ActionForm and DynaActionForm?
  • An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml
  • The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.
  • The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
  • ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
  • ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).
  • DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

39.How can we make message resources definitions file available to the Struts framework environment?
We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to struts-config.xml.
<message-resources parameter="com.login.struts.ApplicationResources"/>

40.What is the life cycle of ActionForm?
The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
  • Retrieve or Create Form Bean associated with Action
  • "Store" FormBean in appropriate scope (request or session)
  • Reset the properties of the FormBean
  • Populate the properties of the FormBean
  • Validate the properties of the FormBean
  • Pass FormBean to Action
Q 1. What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.
Model: The model contains the core of the application's functionality. The model enca psulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
Controller: The controller reacts to the user input. It creates and sets the model.
Q 2. What is a framework?
Framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.
Q 3. What is Struts framework?
Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application
of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.

Q 4. What is Jakarta Struts Framework?
Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
Q 5. What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server
 goes through the controller. Controller is responsible for handling all the requests.
Q 6. What is role of ActionServlet?
ActionServlet performs the role of Controller:
  • Process user requests
  • Determine what the user is trying to achieve according to the request
  • Pull data from the model (if necessary) to be given to the appropriate view,
  • Select the proper view to respond to the user
  • Delegates most of this grunt work to Action classes
  • Is responsible for initialization and clean-up of resources
Q 7.  What is Action Class?
Any java class which extends from org.apache.struts.action.Action is called Action class. The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to  Subclass and overwrite the execute()  method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model.   The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object..

Q 8. Write code of any Action Class?

package 
com.durgasoft;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class TestAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
 HttpServletRequest request,HttpServletResponse response) throws Exception 
   {
      return mapping.findForward("success");
   }
}
Q 9. What is ActionForm?
            Any java class which extends from org.apache.struts.action.ActionForm is called ActionForm. An ActionForm is also called JavaBean. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.
Q10. What is Struts Validator Framework?
Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. 
The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

   
Q11. How you will display validation fail errors on jsp page?

        
Following tag displays all the errors:
              <html:errors/>
  
Q12. What is RequestProcessor?
The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like
The ActionServlet Class
The RequestProcessor Class
The Action Class
The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application.
The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows.
      <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
       </servlet>
All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows.
<servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
<servlet-mapping>
          A request URI that matches this pattern will have the following form.
http://localhost:8080/mycontext/actionName.do
The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below.
<servlet-mapping>
   <servlet-name>action</servlet-name>
   <url-pattern>/do/*</url-pattern>
   <url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://localhost:8080/mycontext/do/action_Name The class
 org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed.
Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method.
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)    throws Exception 
      The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn?t already exist. The strut framework will create only a single instance of each Action class in your application.
       Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action. ActionMapping class. The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.
<action>
        path= "/somerequest"
        type="com.somepackage.someAction"
        scope="request"
        name="someForm"
        validate="true"
        input="somejsp.jsp"
    <forward name="Success" path="/action/xys" redirect="true"/>
    <forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
         Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache. struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file.
<action>
        path= "/somerequest"
        type="com.somepackage.someAction"
        scope="request"
        name="someForm"
        validate="true"
        input="somejsp.jsp"
    <forward name="Success" path="/action/xys" redirect="true"/>
    <forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
The action forward mappings also can be specified in a global section, independent of any specific action mapping.
<global-forwards>
    <forward name="Success" path="/action/somejsp.jsp" />
    <forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>


Q13. How you will handle exceptions in Struts?

In Struts you can handle the exceptions in two ways:
   a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within
<action>..</action> tag.

Example:
<exception
      key="database.error.duplicate"
      path="/UserExists.jsp"
      type="mybank.account.DuplicateUserException"/>
   b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.
Q14. What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:
ForwardAction, IncludeAction, DispatchAction, LookupDispatchAction, SwitchAction  
Q15. What is DispatchAction?
       The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.


Q16. How to use DispatchAction?
To use the DispatchAction, follow these steps :
  1. Create a class that extends DispatchAction (instead of Action)
  2. In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
  3. Do not override execute() method – Because DispatchAction class itself provides execute() method.
  4. Add an entry to struts-config.xml

Q17. What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

Q18. What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.
Q19. What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

Q20. What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.

Q21. What if <action> element has <forward> declaration with same name as global forward?

In this case the global forward is not used. Instead the <action> element’s <forward> takes precendence.
Q22. What is difference between ActionForm and DynaActionForm?
An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml.
The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.
The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.get Parameter( .. ).
  • DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.
Q23. What is the life cycle of ActionForm?
The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
  • Retrieve or Create Form Bean associated with Action
  • "Store" FormBean in appropriate scope (request or session)
  • Reset the properties of the FormBean
  • Populate the properties of the FormBean
  • Validate the properties of the FormBean
  • Pass FormBean to Action
Q24.What are the important tags of struts-config.xml ?
<struts-config>
  <!-- ========== Form Bean Definitions ============ -->

<form-beans>

<form-bean name="login" type=" LoginForm" />
  </form-beans>
  <!-- ========== Global Forward Definitions ========= -->
  <global-forwards>
  </global-forwards>
  <!-- ========== Action Mapping Definitions ======== -->
  <action-mappings>
    <action
        path="/login"
        type="LoginAction" >
        </action>
  </action-mappings>
<!-- ========== Properties Definitions ============ -->
<message-resources parameter="MessageResources" />
<!-- ========== Validator framework Definitions ============ --> 
<plug-in className="org.apache.struts.validator.ValidatorPlugIn"> 
    <set-property 
           property="pathnames" 
            value="/org/apache/struts/validator/validator-rules.xml, 
        /WEB-INF/validation.xml"/> 
   </plug-in> 
</struts-config>
Q25. What are the core classes of the Struts Framework?
A: Core classes of Struts Framework are ActionForm, Action, ActionMapping, Action Forward, ActionServlet etc.
Q26. What is action mappings?
         An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action.
Q27. Describe validate() and reset() methods ?
          validate () and reset() methods defined inActionForm class.
validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionMessage as ActionErrors. Following is the method signature for the validate() method.
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.
public void reset() {}
   
Q28. Give the Details of XML files used in Validator Framework?
The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.
Q29. How you will enable front-end validation based on the xml in validation.xml?
The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For  example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined