Wednesday, August 25, 2010

What is the difference between interface and abstract class?

* interface contains methods that must be abstract; abstract class may contain concrete methods.
* interface contains variables that must be static and final; abstract class may contain non-final and final variables.
* members in an interface are public by default, abstract class may contain non-public members.
* interface is used to "implements"; whereas abstract class is used to "extends".
* interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.
* interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces.
* interface is absolutely abstract; abstract class can be invoked if a main() exists.
* interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.
* If given a choice, use interface instead of abstract class.



if req more info please go through below URL


http://www.interview-questions-java.com/abstract-class-interface.htm

Monday, August 23, 2010

Mysql tutorials

http://www.tizag.com/mysqlTutorial/mysqljoins.php

Wednesday, August 11, 2010

SCJP mock test

http://www21.brinkster.com/infoway02/SCJP2.asp

Tuesday, August 10, 2010

best Jsp tutorial

http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html#8865


http://java.sun.com/products/jsp/tags/11/syntaxref11.fm9.html

http://www.jchq.net/mockexams/exam3.htm

http://www.jchq.net/mockexams/exam3.htm

Core java SCJP Mock test1

1 public class MyClass{
int x = 10;
static final int y= 5;

public void method (int z){
int a = 10;
final float b = 10;

class LocalClass {
int c = 3;

public void method (int d){
System.out.println (??); // -- 1
}
}

public static void main (String args[]){
new MyClass();
}
}
Which of the following variable names can be replaced ?? at line no marked as 1,without compiler error?
A x
B a
C b
D c



A , C and D

Local classes can access all the variables from
the enclosing classes. But it can access only the
final variables of the enclosing method or the method parameter.
The above constraint is applicable if the Local class
is declared inside the non-static context.
since, if the Local class is declared inside the static
context it can access only the static members of the enclosing class.





2 public class MyClass{
public static void main (String args[]){
String str = "Hello World";
System.out.print(str.indexOf('d'));
System.out.print(str.indexOf('h'));
System.out.print(str.indexOf('a'));
}
}
What will be the output?
A 10 -1 -1
B 9 -1 -1
C 10 0 -1
D 10 1 -1



A

IndexOf() returns the index within this string
of the first occurrence of the specified character.
IndexOf() method returns -1 if it cannot
find the specified character.
The search is case sensitive. So. it returns -1 for indexOf('a').






3 What is the range of values that can be stored in a short primitive variable?
A 0 - 656535
B -32768 to 32767
C -32768 to 32768
D -32767 to 32768



B

The short is a 16 bit signed integer. Its value ranges from -216 to 216-1





4 Which of the following lines will compile without warning or error.
A float f=1.3;
B int i=10;
C byte b=257;
D char c="a";



B

Always real values default o double.
So when compiler sees a value like 1.3 ,
it will treat it as double and will complain.
Choice C is incorrect because the byte value
ranges from -128 to +127. Here also the compiler
will show the same error message,' possible loss of precision'.
Choice D is incorrect because , we cannot assign a
String to a char, even though the length is one. ie,
anything comes inside " " is a string.





5
What will happen if you try to compile and run the following code ?
public class MyClass {
public static void main (String arguments[]) {
amethod( arguments) ;
}
public void amethod (String[] arguments) {
System.out.println (arguments) ;
System.out.println (arguments[1]) ;
}
}

A Error Can't make static reference to void amethod.
B Error Incorrect main method.
C amethod must be declared with String
D Compiles and executes fine.



A

We cannot call a non static method from a static context.





6 Which of the following will compile without error ?
A import java.util.*;
package mypack;
class MyClass {}
B package mypack;
import java.uril.*;
class MyClass{}
C /*This is a comment */
package MyPackage;
import java.awt.*;
class MyClass{}
D All of the above



B and C

The order of different statements and blocks
in a java program is as follows. package declaration first,
then imports, then class declaration.
if a package declaration exist, it =must be the first non
comment code in the file.





7 Float f= new Float( 1.0F );
String str = "value is " +f;
System.out.println( str );

What will be the output of executing the above code snippet?
A Compiler error invalid character in constructor

B Runtime exception invalid character in constructor.
C Compiles and prints 'value is 1.0'

D Compiles and prints 'value is 1'



C

Choice A and B is incorrect because we can use
'F' to specify the given number is float.





8 Which of the following are java keywords
?
A null
B const
C volatile
D true



B and C

Choices B and C are java keywords.
Choice A and D are not java keywords,
but they are treated as reserved words in java.





9 What will be printed out if this code is run
with the following command line : java myprog good morning
public class myprog {
public static void main (String argv[]) {
System.out.println(argv[2])
}
}
A myprog
B good
C morning
D Exception raised: java.lang.ArrayIndexOutOfBoundsException: 2



D

Unlike C++ , java command line arguments
does not include the java program name
in the argument list. So in our program
we actually passing only two arguments.
But when printing we are printing the third
argument (since array index always start at zero)
and as a result it will cause a RuntimeException.





10 What is the range of a byte
A 0 - 256
B -128 to 127
C -127 to 128
D -255 to 256



B

The size of a byte is 1 byte. So its range is from -28 to +28-1.







11 Which of the following are legal identifiers ?
A 1variable
B variable1
C $anothervar
D _anothervar
E %anothervar



B , C and D

A variable name should start with a letter, under score or a dollar sign.
A valid variable can contain letters and digits.





12 What will happen when you compile the following code
public class MyClass{
static int i;
public static void main (String argv[]) {
System.out.println(i) ;
}
}
A 0
B 1
C Compiler
Error variable 'i' may not have initialized.

D null



A

All the class level variables are automatically
initialized to a default value. Since 'i' is of type int, it is initialized to zero.





13 What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [] {1, 2, 3, 4};
System.out.println(abc[2]);
}
}
A ArrayIndexOutofBoudsException will be thrown.
B 2
C 3
D 4



C

Always array elements starts with index zero.
The element at index 2, ie, the e3lement at position 3 is 3 .
So the correct answer is C.





14 What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [5];
System.out.println(abc);
}
}
A Error array not initialized
B 5
C null
D Print some junk characters




D

It will print some junk characters to the output.
Here it will not give any compile time or runtime error
because we have declared and initialized the array properly.
Event if we are not assigning a value to the array, it will always initialized to its defaults.





15
What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [5];
System.out.println(abc[0]);
}
}

A Error array not initialized
B 5
C 0
D Print some junk characters



C

Here it will not give any compile time or runtime
error because we have declared and initialized the
array properly. Event if we are not assigning a value to the array,
it will always initialized to its defaults.
So the array will be initialized with values zero.





16 What will be the result of attempting to compile and run the following code ?
abstract class MineBase {
abstract void amethod() ;
static int i;
}

public class Mine extends MineBase {
public static void main( String argv[]) {
int[] ar=new int[5];
for (i=0;i < ar.length;i++)
System.out.println (ar[i]) ;
}
}
A A sequence of 5 0's will be printed
B Error: variable 'ar' may not have initialized .
C Error Mine must be declared abstract
D Error MineBase cannot be declared abstract.



C

If we are extending an abstract class,
we need to provide implementations for every abstract method.
If we are not able to provide the implementation
we have to declare our child class as abstract.
Otherwise the compiler will flag an error message.





17 What will be printed out if you attempt to compile and run the following code ?
int i=1;
switch (i) {
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
break;
case 2:
System.out.println("two") ;
break;
default:
System.out.println("default") ;
}
A one
B zero
C one default
D one two default



A

It is obvious. It printed the value corresponding for the case label 1.





18
What will be printed out if you attempt to compile and run the following code ?
int i=1;
switch (i) {
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
case 2:
System.out.println("two") ;
break;
}

A zero
B one
C one two
D Error no default specified.



C

Choice C is the correct because, since the value of i is one,
it will start executing the case 1.
But it will continue its execution till it finds a break
or till it reach the end of switch statement,
so the value one followed by two will be printed.
Choice D is incorrect because, the use of default in switch expression is optional.





19 What will be printed out if you attempt to compile and run the following code ?
int i=10;
switch (i) {
default:
System.out.println("Default");
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
case 2:
System.out.println("two") ;
break;
}
A default
B default zero
C Error , default cannot be the first statement in switch.
D default zero one two



B

Since there is no matching case labels,
it will start its execution in default,
and continue till the first break statement.
The order of case labels in switch statement does not matter.





20 Which of the following data types
can appear inside a switch statement as its label ?
A String
B char
C int
D byte



B , C and D

The valid types for the switch statement is byte, char, short and int.

Friday, August 6, 2010

Jsp interview questions

1.What are the advantages of JSP over Servlet?

JSP is a serverside technology to make content generation a simple appear.The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.


2.What is the life-cycle of JSP?

When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:

* Translation
* Compilation
* Loading the class
* Instantiating the class
* jspInit() invocation
* _jspService() invocation
* jspDestroy() invocation

More about JSP Life cycle


3.What is the jspInit() method?

The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.

4.What is the _jspService() method?

SThe _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.

5.What is the jspDestroy() method?

The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.

6.What JSP lifecycle methods can I override?

You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

7.How can I override the jspInit() and jspDestroy() methods within a JSP page?

The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:

<%!
public void jspInit() {
. . .
}
%>
<%!
public void jspDestroy() {
. . .
}
%>


8.What are implicit objects in JSP?

Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.The implicit objects available in JSP are as follows:

* request
* response
* pageContext
* session
* application
* out
* config
* page
* exception

The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

9.What are the different types of JSP tags?

The different types of JSP tags are as follows:
page directive
include directive
taglib directive

10.What are JSP directives?

* JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page
* They are used to set global values such as a class declaration, method implementation, output content type, etc.
* They do not produce any output to the client.
* Directives are always enclosed within <%@ ….. %> tag.
* Ex: page directive, include directive, etc.


11.What is page directive?

* A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
* Typically, the page directive is found at the top of almost all of our JSP pages.
* There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
* The syntax of the include directive is: <%@ page attribute="value">
* Example:<%@ include file="header.jsp" %>


12.What are the attributes of page directive?

There are thirteen attributes defined for a page directive of which the important attributes are as follows:

* import: It specifies the packages that are to be imported.
* session: It specifies whether a session data is available to the JSP page.
* contentType: It allows a user to set the content-type for a page.
* isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.


13.What is the include directive?

There are thirteen attributes defined for a page directive of which the important attributes are as follows:

* The include directive is used to statically insert the contents of a resource into the current JSP.
* This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
* The syntax of the include directive is as follows:
<%@ include file = "FileName" %>
* This directive has only one attribute called file that specifies the name of the file to be included.


14.What are the JSP standard actions?

* The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
* They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
* Ex: include, forward, useBean,etc. object


15.What are the standard actions available in JSP?

The standard actions available in JSP are as follows:

* : It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
* : It forwards a response from a servlet or a JSP page to another page.
* : It makes a JavaBean available to a page and instantiates the bean.
* : It sets the properties for a JavaBean.
* : It gets the value of a property from a JavaBean component and adds it to the response.
* : It is used in conjunction with ;, ; to add a parameter to a request. These parameters are provided using the name-value pairs.
* : It is used to include a Java applet or a JavaBean in the current JSP page.


16.What is the standard action?

The standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type.

17.What are the scopes available in ?

The scopes available in are as follows:

* page scope:: It specifies that the object will be available for the entire JSP page but not outside the page.
* request scope: It specifies that the object will be associated with a particular request and exist as long as the request exists.
* application scope: It specifies that the object will be available throughout the entire Web application but not outside the application.
* session scope: It specifies that the object will be available throughout the session with a particular client.


18.What is the standard action?

* The standard action forwards a response from a servlet or a JSP page to another page.
* The execution of the current page is stopped and control is transferred to the forwarded page.
* The syntax of the standard action is :

Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.

* If anything is written to the output stream that is not buffered before , an IllegalStateException will be thrown.

Note : Whenever we intend to use or in a page, buffering should be enabled. By default buffer is enabled.

19.What is the standard action?

The standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the standard action is as follows:

Here, targetPage is the page to be included in the current JSP.

20.What is the difference between include directive and include action?

Include directive Include action
The include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet. The include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.
The include directive is used to statically insert the contents of a resource into the current JSP. The include standard action enables the current JSP page to include a static or a dynamic resource at runtime.
Use the include directive if the file changes rarely. It’s the fastest mechanism. Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.


21.Differentiate between pageContext.include and jsp:include?

The standard action and the pageContext.include() method are both used to include resources at runtime. However, the pageContext.include() method always flushes the output of the current page before including the other components, whereas flushes the output of the current page only if the value of flush is explicitly set to true as follows:




22.What is the jsp:setProperty action?

You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:


...


In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:


...
property="someProperty" ... />


Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.



23.What is the jsp:getProperty action?

The action is used to access the properties of a bean that was set using the action. The container converts the property to a String as follows:

* If it is an object, it uses the toString() method to convert it to a String.
* If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
* The syntax of the method is:

Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the action before using the action.



24.What is the standard action?

The standard action is used with or to pass parameter names and values to the target resource. The syntax of the standard action is as follows:


25.What is the jsp:plugin action ?

This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.

26.What are scripting elements?

JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:

1. Expressions of the form <%= expression %> that are evaluated and inserted into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method,
3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.


27.What is a scriptlet?

A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service() method. Hence, methods and variables written in scriptlets are local to the service() method. A scriptlet is written between the <% and %> tags and is executed by the container at request processing time.


28.What are JSP declarations?

As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in the service() method when a JSP is translated to a servlet.

29.What is a JSP expression?

A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.

30.How is scripting disabled?

Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:


*.jsp
true

struts interview questions

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


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 configuration element of struts-config.xml file




path="/submit"
type="submit.SubmitAction"
name="submitForm"
input="/submit.jsp"
scope="request"
validate="true">
name="success" path="/success.jsp"/>
name="failure" path="/error.jsp"/>


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:




>action
servlet-name>

org.apache.struts.action.ActionServlet


config

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



.....



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

DispatchAction Example »

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 element has declaration with same name as global forward?

In this case the global forward is not used. Instead the element’s takes precendence.


31.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 to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm
 name="loginForm"type="org.apache.struts.action.DynaActionForm" >

name="userName" type="java.lang.String"/>
name="password" type="java.lang.String" />

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

tag displays all the 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 ?

repeats the nested body content of this tag over a specified collection.



id="customer" name="customers">






name="customer" property="firstName"/> name="customer" property="lastName"/> name="customer" property="address"/>


36.What are differences between and

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

key="prompt.customer.firstname"/>

: is used to retrieve and print the value of the bean property. has no body.

 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 handling tags in your struts-config.xml or define the exception handling tags within tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.


key="some.key"
type="java.lang.NullPointerException"
path="/WEB-INF/errors/null.jsp"/>

or

 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( .. ).

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.

 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






Monday, August 2, 2010

JDBC Driver Types

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

Type 1 JDBC Driver

JDBC-ODBC Bridge driver

The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.


Type 1: JDBC-ODBC Bridge

Advantage

The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available.

Disadvantages

1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

import java.sql.*;

public class AccessDAO {

private Connection con;
private Statement st;
private static final String url="jdbc:odbc:MyAccessDB";
private static final String className="sun.jdbc.odbc.JdbcOdbcDriver";
private static final String user="";
private static final String pass="";

AccessDAO()throws Exception {


Class.forName(className);
con = DriverManager.getConnection(url, user, pass);
st = con.createStatement();

//do whatever database processing is required
}
}


Type 2 JDBC Driver

Native-API/partly Java driver

The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.


Type 2: Native api/ Partly Java Driver

Advantage

The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.

Disadvantage

1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3 JDBC Driver

All Java/Net-protocol driver

Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.


Type 3: All Java/ Net-Protocol Driver

Advantage

1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantage

It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

Type 4 JDBC Driver

Native-protocol/all-Java driver

The Type 4 uses java networking libraries to communicate directly with the database server.


Type 4: Native-protocol/all-Java driver

Advantage

1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

Disadvantage

With type 4 drivers, the user needs a different driver for each database.




EX::http://www.cs.wright.edu/~schung/cs801/JDBC.pdf

in this pdf book we weill get some examples


JDBC Driver Types

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

Type 1 JDBC Driver

JDBC-ODBC Bridge driver

The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.


Type 1: JDBC-ODBC Bridge

Advantage

The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available.

Disadvantages

1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.


Type 2 JDBC Driver

Native-API/partly Java driver

The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.


Type 2: Native api/ Partly Java Driver

Advantage

The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.

Disadvantage

1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3 JDBC Driver

All Java/Net-protocol driver

Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.


Type 3: All Java/ Net-Protocol Driver

Advantage

1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantage

It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

Type 4 JDBC Driver

Native-protocol/all-Java driver

The Type 4 uses java networking libraries to communicate directly with the database server.


Type 4: Native-protocol/all-Java driver

Advantage

1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

Disadvantage

With type 4 drivers, the user needs a different driver for each database.

JDBC interview questions and answers

  1. What are the steps involved in establishing a JDBC connection? This action involves two steps: loading the JDBC driver and making the connection.
  2. How can you load the drivers?
    Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

    Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);

    Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line of code:

    Class.forName(”jdbc.DriverXYZ”);

  3. What will Class.forName do while loading drivers? It is used to create an instance of a driver and register it with the
    DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
  4. How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS.
    The following line of code illustrates the general idea:

    String url = “jdbc:odbc:Fred”;
    Connection con = DriverManager.getConnection(url, “Fernanda”, “J8?);

  5. How can you create JDBC statements and what are they?
    A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object

    Statement stmt = con.createStatement();

  6. How can you retrieve data from the ResultSet?
    JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

    ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);
    String s = rs.getString(”COF_NAME”);

    The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs.

  7. What are the different types of Statements?
    Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)
  8. How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a
    Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first.
    PreparedStatement updateSales =
    con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
  9. What does setAutoCommit do?
    When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:

    con.setAutoCommit(false);

    Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.

    con.setAutoCommit(false);
    PreparedStatement updateSales =
    con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
    updateSales.executeUpdate();
    PreparedStatement updateTotal =
    con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
    updateTotal.setInt(1, 50);
    updateTotal.setString(2, "Colombian");
    updateTotal.executeUpdate();
    con.commit();
    con.setAutoCommit(true);
  10. How do you call a stored procedure from JDBC?
    The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open
    Connection object. A CallableStatement object contains a call to a stored procedure.
     CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
    ResultSet rs = cs.executeQuery();
  11. How do I retrieve warnings?
    SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an
    application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a
    Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these
    classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object:
    SQLWarning warning = stmt.getWarnings();
    if (warning != null)
    {
    System.out.println("n---Warning---n");
    while (warning != null)
    {
    System.out.println("Message: " + warning.getMessage());
    System.out.println("SQLState: " + warning.getSQLState());
    System.out.print("Vendor error code: ");
    System.out.println(warning.getErrorCode());
    System.out.println("");
    warning = warning.getNextWarning();
    }
    }
  12. How can you move the cursor in scrollable result sets?
    One of the new features in the JDBC 2.0 API is the ability to move a result set’s cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.

    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet srs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);

    The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

  13. What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?
    You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:
    Statement stmt =
    con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet srs =
    stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
    srs.afterLast();
    while (srs.previous())
    {
    String name = srs.getString("COF_NAME");
    float price = srs.getFloat("PRICE");
    System.out.println(name + " " + price);
    }
  14. How to Make Updates to Updatable Result Sets?
    Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

15. Difference between statement and prepared statement


A Statement compiles (into a database internal format) and executes a
SQL command all at once from a String, with all values hard-coded. For
example:

Statement stmt = cxn.createStatement(); // no command yet

At the time of the query the String provides everything hard coded:

ResultSet rset = // define and execute command
stmt.executeQuery( "SELECT * FROM mytable WHERE id = '12354'" );

A PreparedStatement (note the letter case) pre-compiles a SQL command
from a String upon its creation. The String may have placeholder
parameters for some values, each marked by a question mark (?). By query
execution time the code must provide a value for each parameter. Thus:

PreparedStatement pstmt = // precompile command at creation
cxn.prepareStatement( "SELECT * FROM mytable WHERE id = ?" );

By the time of the query there must be a value set for the 'id' column:

pstmt.setString( 1, "12354" ); // set parameter 1, a String
ResultSet rset = // command already defined
pstmt.executeQuery();

A (non-Prepared) Statement is compiled at every execution. A
PreparedStatement is compiled once, then executed from that compiled
format even if there are dynamic parameters. (One certainly can make a
PreparedStatement with hard-coded values.) If a command will execute
multiple times, perhaps with different dynamic values, the
PreparedStatement will be much faster over time.

Also, a PreparedStatement is immune to certain SQL insertion exploits
that could compromise a database. (The Statement can be made immune,
but it requires conscious thought.


A Statement is a static SQL statement. It does not support SQL parameters.
A PreparedStatement is a more dynamic SQL statement. The SQL doesn't
change, but it supports SQL parameters so you can execute the same query
in different ways (different filters for example).

The Waterfall Software Life Cycle Model

http://www.cs.toronto.edu/~sme/CSC444F/slides/L04-Lifecycles.pdf