Tuesday, September 6, 2011

response object in jsp

The response object denotes the HTTP Response data. The result or the information of a request is denoted with this object. The response object handles the output of the client. This contrasts with the request object. The class or the interface name of the response object is http.HttpServletResponse.



The response object is written: Javax.servlet.http.httpservletresponse.




The response object is generally used by cookies.



The response object is also used with HTTP Headers.



Methods of response Object:

There are numerous methods available for response object. Some of them are:




  • setContentType()
  • addCookie(Cookie cookie)
  • addHeader(String name, String value)
  • containsHeader(String name)
  • setHeader(String name, String value)
  • sendRedirect(String)
  • sendError(int status_code)

List below details the usage with syntax, example and explanation of each of these methods.



setContentType():

setContentType method of response object is used to set the MIME type and character encoding for the page.




General syntax of setContentType() of response object is as follows:






response.setContentType
();





For example:







response.setContentType
("text/html");





The above statement is used to set the content type as text/html dynamically.



addCookie(Cookie cookie):

addCookie method of response object is used to add the specified cookie to the response. The addcookie method is used to write a cookie to the response. If the user wants to add more than one cookie, then using this method by calling it as many times as the user wants will add cookies.



General syntax of addCookie() of response object is as follows:







response.addCookie
(Cookie cookie)





For example:







Cookie ckiePersonalizedMaxSearchResul

ts = new Cookie("MaxSearchResults", "50")

response.addCookie(ckiePersonalizedMaxSearchResults);




The above statement adds the specified cookie

ckiePersonalizedMaxSearchResults
to the response. This way, within the
same session or later visits the website could remember that the user prefers to
see a maximum of 50 results on a page while performing the search operation.



addHeader(String name, String value):

addHeader method of response object is used to write the header as a pair of name and value to the response. If the header is already present, then value is added to the existing header values.



General syntax of addHeader() of response object is as follows:







response.addHeader
(String name, String value)





Here the value of string is given as second parameter and this gets assigned to the header given in first parameter as string name.



For example:






response.addHeader
("Author", "Exforsys");




The output of above statement is as below:






Author:
Exforsys





containsHeader(String name):

containsHeader method of response object is used to check whether the response already includes the header given as parameter. If the named response header is set then it returns a true value. If the named response header is not set, the value is returned as false. Thus, the containsHeader method is used to test the presence of a header before setting its value. The return value from this method is a Boolean value of true or false.




General syntax of containsHeader() of response object is as follows:






response.containsHeader
(String name)





Return value of the above containsHeader method is a Boolean value true or false.




setHeader(String name, String value):

setHeader method of response object is used to create an HTTP Header with the name and value given as string. If the header is already present, then the original value is replaced by the current value given as parameter in this method.



General syntax of setHeader of response object is as follows:






response.setHeader
(String name, String value)





For example:







response.setHeader
("Content_Type","text/html");




The above statement would give output as






Content_Type: text/html





sendRedirect(String):

sendRedirect method of response object is used to send a redirect response to the client temporarily by making use of redirect location URL given in parameter. Thus the sendRedirect method of the response object enables one to forward a request to a new target. But one must note that if the JSP executing has already sent page content to the client, then the sendRedirect method of response object will not work and will fail.




General syntax of sendRedirect of response object is as follows:






response.sendRedirect
(String)





In the above the URL is given as string.



For example:






response.sendRedirect
("http://xxx.test.com/error.html");



Monday, September 5, 2011

jsp latest interview question

1
Q
What is the difference between JSP and Servlets ?

A
JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.



2
Q
What is difference between custom JSP tags and beans?

A
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag's behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library

JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags

Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences:

Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.



3
Q
What are the different ways for session tracking?

A
Cookies, URL rewriting, HttpSession, Hidden form fields



4
Q
What mechanisms are used by a Servlet Container to maintain session information?

A
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information



5
Q
Difference between GET and POST

A
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.

In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.



6
Q
What is session?

A
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server.



7
Q
What is servlet mapping?

A
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.



8
Q
What is servlet context ?

A
The servlet context is an object that contains a information about the Web application and container.  Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.



9
Q
What is a servlet ?

A
servlet is a java program that runs inside a web container.



10
Q
Can we use the constructor, instead of init(), to initialize servlet?

A
Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.



12
Q
How many JSP scripting elements are there and what are they?

A
There are three scripting language elements: declarations, scriptlets, expressions.



13
Q
How do I include static files within a JSP page?

A
Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. 



14
Q
How can I implement a thread-safe JSP page?

A
You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page.



15
Q
What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

A
In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in   resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.



16
Q
What are the lifecycle of JSP?

A
When presented with JSP page the JSP engine does the following 7 phases.
  • Page translation: -page is parsed, and a java file which is a servlet is created.
  • Page compilation: page is compiled into a class file
  • Page loading : This class file is loaded.
  • Create an instance :- Instance of servlet is created
  • jspInit() method is called
  • _jspService is called to handle service calls
  • _jspDestroy is called to destroy it when the servlet is not required.



17
Q
What are context initialization parameters?

A
Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application.



18
Q
What is a Expression?

A
Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.



19
Q
What is a Declaration?

A
It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet.



20
Q
What is a Scriptlet?

A
A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a .  Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet's service method.

Friday, September 2, 2011

struts-interview-questions for experienced


Q) What is Struts?

A) The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
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.
The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.



Q) What is Jakarta Struts Framework?

A) 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) What is ActionServlet?

A) 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) How you will make available any Message Resources Definitions file to the Struts Framework Environment?

A) T Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through < message-resources /> tag.
Example:
< message-resources parameter=\"MessageResources\" />.
Q) What is Action Class?
A) The Action Class is part of the Model and is a wrapper around the business logic. 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. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. 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) What is ActionForm?

A) An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. 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.

Q) What is Struts Validator Framework?

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

Q) Give the Details of XML files used in Validator Framework?

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

Q) How you will display validation fail errors on jsp page?
A) Following tag displays all the errors:
< html:errors/>
Q) How you will enable front-end validation based on the xml in validation.xml?
A) 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 in the validation.xml file. The < html:javascript> when added in the jsp file generates the client site validation script.
 
Q) How to get data from the velocity page in a action class?

A) We can get the values in the action classes by using data.getParameter(\"variable name defined in the velocity page\");
Q) Write code of any Action Class?
A) Here is the code of Action Class that returns the ActionForward object.
TestAction.java
package javajotter.net;
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;
public class TestAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}
Q) Why cant we overide create method in StatelessSessionBean?
A) From the EJB Spec : - A Session bean's home interface defines one or morecreate(...) methods. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method must be the enterprise Bean's remote interface type. The home interface of a stateless session bean must have one create method that takes no arguments.
Q) Is struts threadsafe?Give an example?
A) Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.
Q) Can we Serialize static variable?
A) Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular object's state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields. There are four basic things you must do when you are making a class serializable. They are:
1. Implement the Serializable interface.
2. Make sure that instance-level, locally defined state is serialized properly.
3. Make sure that superclass state is serialized properly.
4. Override equals( )and hashCode( ).
it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process .
Q) What are the disadvantages of Struts?
A) Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts:
a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts.
b) Harder to learn
Struts are harder to learn, benchmark and optimize.
 
Q) What is the difference between perform() and execute() methods?
A) Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.
Q) What are the various Struts tag libraries?
A) Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:
* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application
Q) How Struts relates to J2EE?
A) Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.
Q) What is Struts actions and action mappings?
A) A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward.
An action can perform tasks such as validating a user name and password.
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.
An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.
Q) What is Struts Flow?
A) Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html )
Q) What are the difference between < bean:message> and < bean:write> ?
A) < bean:message> : This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.

< bean:write> : This tag is used to output property values from a bean. < bean:write> is a commonly used tag which enables the programmers to easily present the data.
Q) What is LookupDispatchAction?
A) An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. (Ref. http://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.html).
Q) What are the components of Struts?
A) Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller.
Model: Components like business logic / business processes and data are the part of Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.
Q) What are the core classes of the Struts Framework?
A) Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc.
 
Q) What are Tag Libraries provided with Struts?
A)Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are:
a) Bean Tags: Bean Tags are used to access the beans and their properties.
b) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc..
c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets.
d) Nested Tags: Nested Tags helps to work with the nested context.
Q) What are difference between ActionErrors and ActionMessage?
A) ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property.Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message.

ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form).
Q) How you will handle exceptions in Struts?
A) 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.
Q) Can I setup Apache Struts to use multiple configuration files?
A) Yes Struts can use multiple configuration files. Here is the configuration example:
< servlet>
< servlet-name> banking< /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-authentication.xml,
/WEB-INF/struts-help.xml
< /param-value>
< /init-param>
< load-on-startup> 1< /load-on-startup>
< /servlet>




Q) What are the disadvantages of Struts?
A) Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts:
a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts.
b) Harder to learn
Struts are harder to learn, benchmark and optimize.
 
Q) What is the difference between perform() and execute() methods?
A) Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.
Q) What are the various Struts tag libraries?
A) Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:
* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application
Q) How Struts relates to J2EE?
A) Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.
Q) What is Struts actions and action mappings?
A) A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward.
An action can perform tasks such as validating a user name and password.
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.
An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.
Q) What is Struts Flow?
A) Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html )
Q) What are the difference between < bean:message> and < bean:write> ?
A) < bean:message> : This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.

< bean:write> : This tag is used to output property values from a bean. < bean:write> is a commonly used tag which enables the programmers to easily present the data.
Q) What is LookupDispatchAction?
A) An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. (Ref. http://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.html).
Q) What are the components of Struts?
A) Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller.
Model: Components like business logic / business processes and data are the part of Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.
Q) What are the core classes of the Struts Framework?
A) Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc.
 
Q) What are Tag Libraries provided with Struts?
A)Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are:
a) Bean Tags: Bean Tags are used to access the beans and their properties.
b) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc..
c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets.
d) Nested Tags: Nested Tags helps to work with the nested context.
Q) What are difference between ActionErrors and ActionMessage?
A) ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property.Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message.

ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form).
Q) How you will handle exceptions in Struts?
A) 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.
Q) Can I setup Apache Struts to use multiple configuration files?
A) Yes Struts can use multiple configuration files. Here is the configuration example:
< servlet>
< servlet-name> banking< /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-authentication.xml,
/WEB-INF/struts-help.xml
< /param-value>
< /init-param>
< load-on-startup> 1< /load-on-startup>
< /servlet>

Thursday, September 1, 2011

struts-interview-question-answer-question

Ques: 1 What is struts?
Ans:The Jakarta struts project, an open source project supported by the Apache software Foundation, is a server side java implementation of the modetl view controller (MVC) design pattern.

The struts framework designed to create Web application that easily separate the presentation layer and allow it to be abstracted from the transaction and data layers.
Ques: 2 

What are the various steps involved in the implementaion of struts?
Ans:The struts framwork models its server side implementation of the MVC using a combination of JSPs, custom JSP tags, and a Java Servlet. It involves the following steps :



* The incoming request is received by the ActionServlet, which acts as the controller, and the ActionServlet looks up the requested URI in an XML file.

* The ActionClass performs its logic on the Model components associated with the application.

* Once the Action has completed its processing, it returns control to the ActionServlet with a key that indicates the result of its processing. ActionServlet uses this key to determine where this result should be forwarded for presentation.

* The request is complete when the ActionServlet response by forwarding the request ot the view that was linked to the returned key, and this view presents the result of the Action.
Ques: 3 What is MVC design pattern?
Ans:MVC stands for Model-View-Controller. The MVC design pattern is originated from Smalltalk, consists of three components : a Model, a View, and a Controller.



MODEL : Represents the data objects. The Model is what is being manipulated and persented to the user. Model contains the business logic of the application.



VIEW : Serves as screen representation of the Model. It is the object that represents the current state of the objects.



CONTROLLER : Defines the way the user interface reacts to the user's input. The Controller component is the object that manipulates the Model, or data object.
Ques: 4 How will you install struts framework in your web application?
Ans:The follwing steps are involved to install struts framework in your web application :



* Uncompress the Struts Archive to your local disk.

* Create a new web Application say, MyStrutsApp inside the webapps directory under the tomcat directory.

* Copy all the jar files, extracted from the lib directory into the /webapps/MyStrutsApp/WEB-INF/lib directory.

* Create an empty web.xml file and copy it to the /webapps/MyStrutsApp/WEB-INF/ directory.

* Create an empty struts-config.xml file and copy it to the /webapps/MyStrutsApp/WEB-INF/ directory. The struts-config.xml file is the diployment descriptor for all Struts applicattion. It is the file that glues all of the MVCcomponents together.
Ques: 5 Describe the struts specific form tag?
Ans:Instead of using the standard HTML Form tag, like most HTML pages, the struts specific Form tag is : 





..........




This tag with its subordinate input tags, encapsulates Struts form processing. The Form tag attributes are :

* action : Represents the URL to which this form will be submitted. This is also used to find the appropriate ActionMapping in the Struts configuration file.

* name : Identifies the key that is used to lookup the appropriate ActionForm that will represent the submitted form data.

* type : Names the fully qualified classname of the form bean you want to use in this request.



To use the struts specific tag you have to use the taglib directive:

<%@ taglib uri="WEB-INF/struts-html.tld" prefix="html" %>
Ques: 6 What is ActionForm in the struts?
Ans:When an  is submitted, the Struts framework populates the matching data members of the ActionForm with the values entered in the  tag. The Struts framework does this by using JavaBean introspection. This is all done by the class specified in the type attribute of the  tag. This class will extends the org.apache.struts.action.ActionForm, as must all ActionForm objects with a get and set accessor that match its data members.
Ques: 7 What are the parameters used in the Action.execute() method in the Struts.
Ans:The following parameters are used in the Action.execute(...) method :

* ActionMapping : The ActionMapping class contains all of the deployment information for a particular Action object. This class is used to determine where the result of the class (that extends the Action class) will be sent once its processing is complete.

* ActionForm : Represents the form inputs cntaining the request parameters from the view referencing this Action bean.

* HttpServletRequest : Reference to the current Http request object.

* HttpServletResponse : Reference to the current Http response object.
Ques: 8 Which mathod is use to forward the result to the appropriate view in the Action class in Struts?
Ans:The findForward() method is use to forward the result to the appropriate view in the Action class. This method takes the paremeter name for the view file to which the result is being forwarded.
Ans:ActionMapping Class's findForward(String) method...

in ActionClass ActionMapping is Passed as Parameter so we do not need to create Seprate instance for that ......
Ques: 9 How will you tell the web application and container about your ActionServlet?
Ans:This can be accomplished by adding the following servlet definition to the web.xml file :





action

org.apache.struts.action.ActionServlet



config/WEB-INF/struts-config.xml


1




Once you told the container about the ActionServlet you need to tell it when it should be executed by adding element in web.xml file :





action

*.do




This mapping tells the web application that whenever a request is received with .do appended to the URL then the servlet named action should service the request.
Ques: 10 

What are the various struts controller components?
Ans:Four distinct Struts Controller components:

* The ActionServlet class

* The Action class

* Plugins

* RequestProcesser
Ques: 11 

What is ActionServlet class in the struts controller?
Ans:The org.apache.struts.action.ActionServlet is the backbone of all Struts application. It is the main controller component that handles the client request and determines which org.apache.struts.action.Action will process each received request. It serves as an Action factory - creating specific Action classes based on the user's request.
Ques: 12 What is the entry point to ActionServlet when a request comes in.
Ans:The two main entry point into the ActionServlet are the same as any other servelt : doGet() and doPost().

They call single method named process(). The struts specific behaviour begin with this mehtod.
Ques: 13 What is the process() method doing in the ActionServlet class?
Ans:The process() method gets the current RequestProcessor and invokes the RequestProcessor.process() method.The RequestProcessor.process() method is where the current request is actually serviced. This method retrieves from the struts-config.xml file, the  element that matches the path submitted on the request. It does this by matching the path passed in the  tag's action element to the  element with the same path value.
Ques: 14 Who calls the ActionForm.validate() method inside the ActionServlet.
Ans:The RequestProcessor.process() method calls the ActionForm.validate() method, which checks the validity of the of the submitted values.
Ques: 15 What is for Action.execute() method?
Ans:The execute method is where your application logic begins. It is the method that you need to override when defining your own Actions. The execute() method has two functions:

* It performs the user-defined business logic associated with your application.

* It tells the Framework where it should next route the request.



The Struts framework defines two execute() methods. The first execute() implementation is used when you are defining custom Actions that are not HTTP specific, i.e. anlogous to the javax.servlet.GenericServlet class. The second, HTTP specific, You need to override the Action.execute() method and is anlogous to the javax.servlet.HttpServlet class.

Its signature is:



public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpResponse response) throws IOException, ServletException{// some code here}
Ques: 16 

Describe the purpose of the Action class?
Ans:The org.apache.struts.action.Action class is a most common component of the Struts Controller. This class must be extended for each specialized Struts function in your application. The collection of these Action classes is what defines your web application.

To develop your own Action class, you must complete the following steps:

* Create a class that extends the org.apache.struts.action.Action class.

* Implement the appropriate execute() method and add your specific business logic.

* Compile the new Action and move it to the Web application's classpath, i.e. /WEB-INF/classes directory.

* Add an element to the application's struts-config.xml file describing the new Action.
Ques: 17 What are Struts Plugins?
Ans:Struts Plugins are modular extensions to the Struts COntroller. They are defined by the org.apache.struts.action.Plugin interface.  Struts Plugins are useful are useful when you are allocating resources or preparing connections to the databases or even JNDI resources.

This interface defines two lifecycle mathods: init() and desstroy().
Ques: 18 

What are the steps involved in Struts Plugins?
Ans:All Plugins must implement the two Plugin methods init() and destroy(). To develop your own Plugin You must complete the following steps:

* Create a class that implements the org.apache.struts.action.Plugin interface.

* Add a default empty contructor to the Plugin implementation. You must have a default constructor to ensure that the ActionServlet property creates your Plugin.

* Implement both the init() and destroy() methods and your implementation.

* Compare the new Plugin and move it into the web applocation's classpath.

* Add a element to the application's struts-config.xml file describing the new Plugin.
Ques: 19 What is RequestProcessor? How will you create your own RequestProcessor? 
Ans:The RequestProcessor is the class that you need to override when you want to customize the processing of the ActionServlet. It contains a predefined entry point that is invoked by the Struts controller with each request. The entry point is the processPreprocess() method.

Steps involved in creation your own RequestProcessor:

* Create a class that extends the org.apache.struts.action.RequestProcessor class.

* Add a default empty constructor to the RequestProcessor implementation.

* Implement your processPreprocess() method.
Ques: 20 

How will you configure the Plugin in your web application.
Ans:To deploy and configure your Plugin class, you must:

* Compile and move the Plugin class file into your application's WEB-INF/classes/ directory.

* Add a element to your struts-config.xml file. For example:



The element should be the last element in the struts-config.xml file.

* Restart the Web application.

Monday, August 29, 2011

Dispatch Class source code in struts Api org.apache.struts



    1   /*
    2    * $Id: DispatchAction.java 384089 2006-03-08 01:50:52Z niallp $
    3    *
    4    * Copyright 2001-2006 The Apache Software Foundation.
    5    *
    6    * Licensed under the Apache License, Version 2.0 (the "License");
    7    * you may not use this file except in compliance with the License.
    8    * You may obtain a copy of the License at
    9    *
   10    *      http://www.apache.org/licenses/LICENSE-2.0
   11    *
   12    * Unless required by applicable law or agreed to in writing, software
   13    * distributed under the License is distributed on an "AS IS" BASIS,
   14    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   15    * See the License for the specific language governing permissions and
   16    * limitations under the License.
   17    */
   18  
   19   package org.apache.struts.actions;
   20  
   21   import java.lang.reflect.InvocationTargetException;
   22   import java.lang.reflect.Method;
   23   import java.util.HashMap;
   24  
   25   import javax.servlet.ServletException;
   26   import javax.servlet.http.HttpServletRequest;
   27   import javax.servlet.http.HttpServletResponse;
   28  
   29   import org.apache.commons.logging.Log;
   30   import org.apache.commons.logging.LogFactory;
   31   import org.apache.struts.action.Action;
   32   import org.apache.struts.action.ActionForm;
   33   import org.apache.struts.action.ActionForward;
   34   import org.apache.struts.action.ActionMapping;
   35   import org.apache.struts.util.MessageResources;
   36  
   37   /**
   38    *
An abstract Action that dispatches to a public
   39    * method that is named by the request parameter whose name is specified
   40    * by the parameter property of the corresponding
   41    * ActionMapping.  This Action is useful for developers who prefer to
   42    * combine many similar actions into a single Action class, in order to
   43    * simplify their application design.

   44    *
   45    * To configure the use of this action in your
   46    * struts-config.xml file, create an entry like this:

   47    *
   48    *
   49    *   <action path="/saveSubscription"
   50    *           type="org.apache.struts.actions.DispatchAction"
   51    *           name="subscriptionForm"
   52    *          scope="request"
   53    *          input="/subscription.jsp"
   54    *      parameter="method"/>
   55    *

   56    *
   57    * which will use the value of the request parameter named "method"
   58    * to pick the appropriate "execute" method, which must have the same
   59    * signature (other than method name) of the standard Action.execute
   60    * method.  For example, you might have the following three methods in the
   61    * same action:

   62    *
       63    *
  • public ActionForward delete(ActionMapping mapping, ActionForm form,
       64    *     HttpServletRequest request, HttpServletResponse response)
       65    *     throws Exception


  •    66    *
  • public ActionForward insert(ActionMapping mapping, ActionForm form,
       67    *     HttpServletRequest request, HttpServletResponse response)
       68    *     throws Exception


  •    69    *
  • public ActionForward update(ActionMapping mapping, ActionForm form,
       70    *     HttpServletRequest request, HttpServletResponse response)
       71    *     throws Exception


  •    72    *

   73    * and call one of the methods with a URL like this:

   74    *
   75    *   http://localhost:8080/myapp/saveSubscription.do?method=update
   76    *

   77    *
   78    * NOTE - All of the other mapping characteristics of
   79    * this action must be shared by the various handlers.  This places some
   80    * constraints over what types of handlers may reasonably be packaged into
   81    * the same DispatchAction subclass.

   82    *
   83    * NOTE - If the value of the request parameter is empty,
   84    * a method named unspecified is called. The default action is
   85    * to throw an exception. If the request was cancelled (a html:cancel
   86    * button was pressed), the custom handler cancelled will be used instead.
   87    * You can also override the getMethodName method to override the action's
   88    * default handler selection.

   89    *
   90    * @version $Rev: 384089 $ $Date: 2006-03-08 01:50:52 +0000 (Wed, 08 Mar 2006) $
   91    */
   92   public abstract class DispatchAction extends Action {
   93  
   94  
   95       // ----------------------------------------------------- Instance Variables
   96  
   97  
   98       /**
   99        * The Class instance of this DispatchAction class.
  100        */
  101       protected Class clazz = this.getClass();
  102  
  103  
  104       /**
  105        * Commons Logging instance.
  106        */
  107       protected static Log log = LogFactory.getLog(DispatchAction.class);
  108  
  109  
  110       /**
  111        * The message resources for this package.
  112        */
  113       protected static MessageResources messages =
  114               MessageResources.getMessageResources
  115               ("org.apache.struts.actions.LocalStrings");
  116  
  117  
  118       /**
  119        * The set of Method objects we have introspected for this class,
  120        * keyed by method name.  This collection is populated as different
  121        * methods are called, so that introspection needs to occur only
  122        * once per method name.
  123        */
  124       protected HashMap methods = new HashMap();
  125  
  126  
  127       /**
  128        * The set of argument type classes for the reflected method call.  These
  129        * are the same for all calls, so calculate them only once.
  130        */
  131       protected Class[] types =
  132               {
  133                   ActionMapping.class,
  134                   ActionForm.class,
  135                   HttpServletRequest.class,
  136                   HttpServletResponse.class};
  137  
  138  
  139  
  140       // --------------------------------------------------------- Public Methods
  141  
  142  
  143       /**
  144        * Process the specified HTTP request, and create the corresponding HTTP
  145        * response (or forward to another web component that will create it).
  146        * Return an ActionForward instance describing where and how
  147        * control should be forwarded, or null if the response has
  148        * already been completed.
  149        *
  150        * @param mapping The ActionMapping used to select this instance
  151        * @param form The optional ActionForm bean for this request (if any)
  152        * @param request The HTTP request we are processing
  153        * @param response The HTTP response we are creating
  154        *
  155        * @exception Exception if an exception occurs
  156        */
  157       public ActionForward execute(ActionMapping mapping,
  158                                    ActionForm form,
  159                                    HttpServletRequest request,
  160                                    HttpServletResponse response)
  161               throws Exception {
  162           if (isCancelled(request)) {
  163               ActionForward af = cancelled(mapping, form, request, response);
  164               if (af != null) {
  165                   return af;
  166               }
  167           }
  168  
  169           // Get the parameter. This could be overridden in subclasses.
  170           String parameter = getParameter(mapping, form, request, response);
  171  
  172           // Get the method's name. This could be overridden in subclasses.
  173           String name = getMethodName(mapping, form, request, response, parameter);
  174  
  175  
  176       // Prevent recursive calls
  177       if ("execute".equals(name) || "perform".equals(name)){
  178           String message =
  179               messages.getMessage("dispatch.recursive", mapping.getPath());
  180  
  181           log.error(message);
  182           throw new ServletException(message);
  183       }
  184  
  185  
  186           // Invoke the named method, and return the result
  187           return dispatchMethod(mapping, form, request, response, name);
  188  
  189       }
  190  
  191  
  192  
  193      
  194       /**
  195        * Method which is dispatched to when there is no value for specified
  196        * request parameter included in the request.  Subclasses of
  197        * DispatchAction should override this method if they wish
  198        * to provide default behavior different than throwing a ServletException.
  199        */
  200       protected ActionForward unspecified(
  201               ActionMapping mapping,
  202               ActionForm form,
  203               HttpServletRequest request,
  204               HttpServletResponse response)
  205               throws Exception {
  206  
  207           String message =
  208                   messages.getMessage(
  209                           "dispatch.parameter",
  210                           mapping.getPath(),
  211                           mapping.getParameter());
  212  
  213           log.error(message);
  214  
  215           throw new ServletException(message);
  216       }
  217  
  218       /**
  219        * Method which is dispatched to when the request is a cancel button submit.
  220        * Subclasses of DispatchAction should override this method if
  221        * they wish to provide default behavior different than returning null.
  222        * @since Struts 1.2.0
  223        */
  224       protected ActionForward cancelled(ActionMapping mapping,
  225                                         ActionForm form,
  226                                         HttpServletRequest request,
  227                                         HttpServletResponse response)
  228               throws Exception {
  229  
  230           return null;
  231       }
  232  
  233       // ----------------------------------------------------- Protected Methods
  234  
  235  
  236       /**
  237        * Dispatch to the specified method.
  238        * @since Struts 1.1
  239        */
  240       protected ActionForward dispatchMethod(ActionMapping mapping,
  241                                              ActionForm form,
  242                                              HttpServletRequest request,
  243                                              HttpServletResponse response,
  244                                              String name) throws Exception {
  245  
  246           // Make sure we have a valid method name to call.
  247           // This may be null if the user hacks the query string.
  248           if (name == null) {
  249               return this.unspecified(mapping, form, request, response);
  250           }
  251  
  252           // Identify the method object to be dispatched to
  253           Method method = null;
  254           try {
  255               method = getMethod(name);
  256  
  257           } catch(NoSuchMethodException e) {
  258               String message =
  259                       messages.getMessage("dispatch.method", mapping.getPath(), name);
  260               log.error(message, e);
  261  
  262               String userMsg =
  263                   messages.getMessage("dispatch.method.user", mapping.getPath());
  264               throw new NoSuchMethodException(userMsg);
  265           }
  266  
  267           ActionForward forward = null;
  268           try {
  269               Object args[] = {mapping, form, request, response};
  270               forward = (ActionForward) method.invoke(this, args);
  271  
  272           } catch(ClassCastException e) {
  273               String message =
  274                       messages.getMessage("dispatch.return", mapping.getPath(), name);
  275               log.error(message, e);
  276               throw e;
  277  
  278           } catch(IllegalAccessException e) {
  279               String message =
  280                       messages.getMessage("dispatch.error", mapping.getPath(), name);
  281               log.error(message, e);
  282               throw e;
  283  
  284           } catch(InvocationTargetException e) {
  285               // Rethrow the target exception if possible so that the
  286               // exception handling machinery can deal with it
  287               Throwable t = e.getTargetException();
  288               if (t instanceof Exception) {
  289                   throw ((Exception) t);
  290               } else {
  291                   String message =
  292                           messages.getMessage("dispatch.error", mapping.getPath(), name);
  293                   log.error(message, e);
  294                   throw new ServletException(t);
  295               }
  296           }
  297  
  298           // Return the returned ActionForward instance
  299           return (forward);
  300       }
  301  
  302       /**
  303        * Returns the parameter value.

  304        *
  305        * @param mapping  The ActionMapping used to select this instance
  306        * @param form     The optional ActionForm bean for this request (if any)
  307        * @param request  The HTTP request we are processing
  308        * @param response The HTTP response we are creating
  309        * @return The ActionMapping parameter's value
  310        * @throws Exception if the parameter is missing.
  311        */
  312       protected String getParameter(ActionMapping mapping, ActionForm form,
  313           HttpServletRequest request, HttpServletResponse response)
  314           throws Exception {
  315  
  316           // Identify the request parameter containing the method name
  317           String parameter = mapping.getParameter();
  318  
  319           if (parameter == null) {
  320               String message =
  321                   messages.getMessage("dispatch.handler", mapping.getPath());
  322  
  323               log.error(message);
  324  
  325               throw new ServletException(message);
  326           }
  327  
  328  
  329           return parameter;
  330       }
  331  
  332       /**
  333        * Introspect the current class to identify a method of the specified
  334        * name that accepts the same parameter types as the execute
  335        * method does.
  336        *
  337        * @param name Name of the method to be introspected
  338        *
  339        * @exception NoSuchMethodException if no such method can be found
  340        */
  341       protected Method getMethod(String name)
  342               throws NoSuchMethodException {
  343  
  344           synchronized(methods) {
  345               Method method = (Method) methods.get(name);
  346               if (method == null) {
  347                   method = clazz.getMethod(name, types);
  348                   methods.put(name, method);
  349               }
  350               return (method);
  351           }
  352  
  353       }
  354  
  355       /**
  356        * Returns the method name, given a parameter's value.
  357        *
  358        * @param mapping The ActionMapping used to select this instance
  359        * @param form The optional ActionForm bean for this request (if any)
  360        * @param request The HTTP request we are processing
  361        * @param response The HTTP response we are creating
  362        * @param parameter The ActionMapping parameter's name
  363        *
  364        * @return The method's name.
  365        * @since Struts 1.2.0
  366        */
  367       protected String getMethodName(ActionMapping mapping,
  368                                      ActionForm form,
  369                                      HttpServletRequest request,
  370                                      HttpServletResponse response,
  371                                      String parameter)
  372               throws Exception {
  373  
  374           // Identify the method name to be dispatched to.
  375           // dispatchMethod() will call unspecified() if name is null
  376           return request.getParameter(parameter);
  377       }
  378  
  379   }