Sei sulla pagina 1di 56

Servlet Questions

1 . What is the servlet?


Servlet is a script, which resides and executes on server side, to create dynamic HTML. In
servlet programming we will use java language. A servlet can handle multiple requests
concurrently

2 . What is the architechture of servlet package?


Servlet Interface is the central abstraction. All servlets implements this Servlet
Interface either direclty or indirectly
( may implement or extend Servlet Interfaces sub classes or sub interfaces)

Servlet
|
Generic Servlet
|
HttpServlet ( Class ) — we will extend this class to handle GET / PUT HTTP requests
|
MyServlet
3 . What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle requests.
HttpServlet extends GenericServlet added new methods
doGet()
doPost()
doHead()
doPut()
doOptions()
doDelete()
doTrace() methods
Both these classes are abstract.
4 . What’s the difference between servlets and applets?
Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets
have no graphical user interface.

5 . What are the uses of Servlets?


A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets
can forward requests to other servers and servlets. Thus servlets can be used to balance load
among several servers.

6 . When doGET() method will going to execute?


When we specified method=’GET’ in HTML
Example : < form name=’SSS’ method=’GET’>

7 . When doPOST() method will going to execute?


When we specified method=’POST’ in HTML
< form name=’SSS’ method=’POST’ >
8 . What is the difference between Difference between doGet() and doPost()?
GET Method : Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).

POST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info on the browser.

9 . What is the servlet life cycle?


When first request came in for the servlet , Server will invoke init() method of the servlet.
There after if any user request the servlet program, Server will directly executes the service()
method. When Server want to remove the servlet from pool, then it will execute the destroy()
method
10 . Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.

11 . Which protocol will be used by browser and servlet to communicate ?


HTTP

12 . In how many ways we can track the sessions?


Method 1) By URL rewriting
Method 2) Using Session object

Getting Session form HttpServletRequest object


HttpSession session = request.getSession(true);

Get a Value from the session


session.getValue(session.getId());

Adding values to session


cart = new Cart();
session.putValue(session.getId(), cart);

At the end of the session, we can inactivate the session by using the following command
session.invalidate();

Method 3) Using cookies

Method 4) Using hidden fields


13 . How Can You invoke other web resources (or other servlet / jsp ) ?
Servelt can invoke other Web resources in two ways: indirect and direct.
Indirect Way : Servlet will return the resultant HTML to the browser which will point to
another Servlet (Web resource)

Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself,
by using RequestDispatcher object.

You can get this object using getRequestDispatcher(”URL”) method. You can get this object
from either a request or a Context.
Example :
RequestDispatcher dispatcher = request.getRequestDispatcher(”/jspsample.jsp”);
if (dispatcher != null)
dispatcher.forward(request, response);
}
14 . How Can you include other Resources in the Response?
Using include method of a RequestDispatcher object.

Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example,
setCookie) that affects the headers of the response.

Example : RequestDispatcher dispatcher =


getServletContext().getRequestDispatcher(”/banner”);
if (dispatcher != null)
dispatcher.include(request, response);
}

15 . What is the difference between the getRequestDispatcher(String path)


ServletRequest interface and ServletContext interface?
The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter
the path to the resource to be included or forwarded to, which can be relative to the request of
the calling servlet. If the path begins with a “/” it is interpreted as relative to the current
context root.

The getRequestDispatcher(String path) method of ServletContext interface cannot accepts


relative paths. All path must sart with a “/” and are interpreted as relative to curent context
root. If the resource is not available, or if the server has not implemented a
RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your
servlet should be prepared to deal with this condition.

16 . What is the use of ServletContext ?


Using ServletContext, We can access data from its environment. Servlet context is common to
all Servlets so all Servlets share the information through ServeltContext.

17 . Is there any way to generate PDF’S dynamically in servlets?


We need to use iText. A open source library for java. Please refer sourceforge site for sample
servlet examples.

18 . What is the difference between using getSession(true) and getSession(false)


methods?

getSession(true) - This method will check whether already a session is existing for the user.
If a session is existing, it will return that session object, Otherwise it will create new session
object and return taht object.
getSession(false) - This method will check existence of session. If session exists, then it
returns the reference of that session object, if not, this methods will return null.

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.

5.What are the core classes of the Struts Framework?


Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2
design.

JavaBeans components for managing application state and behavior.

Event-driven development (via listeners as in traditional GUI development).

Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

6.What is ActionServlet?

ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main
Controller component that handles client requests and determines which Action will process
each received request. It serves as an Action factory – creating specific Action classes based
on user’s request.

7.What is role of ActionServlet?

ActionServlet performs the role of Controller:

Process user requests

Determine what the user is trying to achieve according to the request

Pull data from the model (if necessary) to be given to the appropriate view,

Select the proper view to respond to the user

Delegates most of this grunt work to Action classes

Is responsible for initialization and clean-up of resources

8.What is the ActionForm?

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

9.What are the important methods of ActionForm?

The important methods of ActionForm are : validate() & reset().

10.Describe validate() and reset() methods ?

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

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)


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

public void reset() {}

11.What is ActionMapping?

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

12.How is the Action Mapping specified ?

We can specify the action mapping in the configuration file called struts-config.xml. Struts
framework creates ActionMapping object from <ActionMapping> configuration element of
struts-config.xml file

<action-mappings>
<action path=“/submit”
type=“submit.SubmitAction”
name=“submitForm”
input=“/submit.jsp”
scope=“request”
validate=“true”>
<forward name=“success” path=“/success.jsp”/>
<forward name=“failure” path=“/error.jsp”/>
</action>
</action-mappings>

13.What is role of Action Class?

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

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

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

public ActionForward execute(


ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;

execute() method of Action class:

<!--[if !supportLists]--><!--[endif]-->Perform the processing required to deal with


this request
<!--[if !supportLists]--><!--[endif]-->Update the server-side objects (Scope
variables) that will be used to create the next page of the user interface

<!--[if !supportLists]--><!--[endif]-->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.

<!--[if !supportLists]--><!--[endif]-->Service to Worker

<!--[if !supportLists]--><!--[endif]-->Dispatcher View

<!--[if !supportLists]--><!--[endif]-->Composite View (Struts Tiles)

<!--[if !supportLists]--><!--[endif]-->Front Controller

<!--[if !supportLists]--><!--[endif]-->View Helper

<!--[if !supportLists]--><!--[endif]-->Synchronizer Token

16.Can we have more than one struts-config.xml file for a single Struts application?

Yes, we can have more than one struts-config.xml for a single Struts application. They can be
configured as follows:

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
…..
<servlet>

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.

20.What are the different kinds of actions in Struts?


The different kinds of actions in Struts are:

<!--[if !supportLists]--><!--[endif]-->ForwardAction

<!--[if !supportLists]--><!--[endif]-->IncludeAction

<!--[if !supportLists]--><!--[endif]-->DispatchAction

<!--[if !supportLists]--><!--[endif]-->LookupDispatchAction

<!--[if !supportLists]--><!--[endif]-->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 :

<!--[if !supportLists]--><!--[endif]-->Create a class that extends DispatchAction


(instead of Action)

<!--[if !supportLists]--><!--[endif]-->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.

<!--[if !supportLists]--><!--[endif]-->Do not override execute() method – Because


DispatchAction class itself provides execute() method.

<!--[if !supportLists]--><!--[endif]-->Add an entry to struts-config.xml

23.What is the use of ForwardAction?

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

24.What is IncludeAction?

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

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

26.What is LookupDispatchAction?

The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the


resource bundle to get the key and then gets the method whose name is associated with the
key into the Resource Bundle.

27.What is the use of LookupDispatchAction?

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

<!--[if !vml]--><!--[endif]-->28.What is difference between LookupDispatchAction


and DispatchAction?

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

29.What is SwitchAction?

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

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

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

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:

<!--[if !supportLists]--><!--[endif]-->In struts-config.xml: change your <form-


bean> to be an org.apache.struts.action.DynaActionForm instead of some subclass of
ActionForm

<form-bean name=”loginForm“type=”org.apache.struts.action.DynaActionForm“ >


<form-property name=”userName” type=”java.lang.String“/>
<form-property name=”password” type=”java.lang.String” />
</form-bean>

<!--[if !supportLists]--><!--[endif]-->In your Action subclass that uses your form


bean:

<!--[if !supportLists]--><!--[endif]-->import
org.apache.struts.action.DynaActionForm

<!--[if !supportLists]--><!--[endif]-->downcast the ActionForm parameter in


execute() to a DynaActionForm

<!--[if !supportLists]--><!--[endif]-->access the form fields with get(field)


rather than getField()

import org.apache.struts.action.DynaActionForm;

public class DynaActionFormExample extends Action {


public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get(“userName”)).equals(“”)) {
errors.add(“userName”, new ActionMessage(
“error.userName.required”));
}
if (((String) loginForm.get(“password”)).equals(“”)) {
errors.add(“password”, new ActionMessage(
“error.password.required”));
}
………..

33.How to display validation errors on jsp page?

<html:errors/> tag displays all the errors. <html:errors/> iterates over ActionErrors request
attribute.

34.What are the various Struts tag libraries?

The various Struts tag libraries are:


<!--[if !supportLists]--><!--[endif]-->HTML Tags

<!--[if !supportLists]--><!--[endif]-->Bean Tags

<!--[if !supportLists]--><!--[endif]-->Logic Tags

<!--[if !supportLists]--><!--[endif]-->Template Tags

<!--[if !supportLists]--><!--[endif]-->Nested Tags

<!--[if !supportLists]--><!--[endif]-->Tiles Tags

35.What is the use of <logic:iterate>?

<logic:iterate> repeats the nested body content of this tag over a specified collection.

<table border=1>
<logic:iterate id=“customer“ name=“customers”>
<tr>
<td><bean:write name=“customer” property=“firstName”/></td>
<td><bean:write name=“customer” property=“lastName”/></td>
<td><bean:write name=“customer” property=“address”/></td>
</tr>
</logic:iterate>
</table>

36.What are differences between <bean:message> and <bean:write>

<bean:message>: is used to retrive keyed values from resource bundle. It also supports the
ability to include parameters that can be substituted for defined placeholders in the retrieved
string.

<bean:message key=“prompt.customer.firstname”/>

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

<bean:write name=“customer” property=“firstName”/>

37.How the exceptions are handled in struts?

Exceptions in Struts are handled in two ways:

<!--[if !supportLists]--><!--[endif]-->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.

<!--[if !supportLists]--><!--[endif]-->Declarative exception handling :You can


either define <global-exceptions> handling tags in your struts-config.xml or define the
exception handling tags within <action></action> tag. It works well when custom
page needed when error occurs. This approach applies only to exceptions thrown by
Actions.

<global-exceptions>
<exception key=“some.key”
type=“java.lang.NullPointerException”
path=”/WEB-INF/errors/null.jsp”/>
</global-exceptions>

or

<exception key=“some.key”
type=“package.SomeException”
path=“/WEB-INF/somepage.jsp”/>

38.What is difference between ActionForm and DynaActionForm?

<!--[if !supportLists]--><!--[endif]-->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

<!--[if !supportLists]--><!--[endif]-->The DynaActionForm bloats up the Struts


config file with the xml based definition. This gets annoying as the Struts Config file
grow larger.

<!--[if !supportLists]--><!--[endif]-->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.

<!--[if !supportLists]--><!--[endif]-->ActionForm can be cleanly organized in


packages as against the flat organization in the Struts Config file.

<!--[if !supportLists]--><!--[endif]-->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( .. ).

<!--[if !supportLists]--><!--[endif]-->DynaActionForm construction at runtime


requires a lot of Java Reflection (Introspection) machinery that can be avoided.

39.How can we make message resources definitions file available to the Struts
framework environment?

We can make message resources definitions file (properties file) available to Struts framework
environment by adding this file to struts-config.xml.

<message-resources parameter=“com.login.struts.ApplicationResources”/>

40.What is the life cycle of ActionForm?

The lifecycle of ActionForm invoked by the RequestProcessor is as follows:


<!--[if !supportLists]--><!--[endif]-->Retrieve or Create Form Bean associated with
Action

<!--[if !supportLists]--><!--[endif]-->“Store” FormBean in appropriate scope


(request or session)

<!--[if !supportLists]--><!--[endif]-->Reset the properties of the FormBean

<!--[if !supportLists]--><!--[endif]-->Populate the properties of the FormBean

<!--[if !supportLists]--><!--[endif]-->Validate the properties of the FormBean

<!--[if !supportLists]--><!--[endif]-->Pass FormBean to Action

<!--[if gte vml 1]> <![endif]--><!--[if !vml]--><!--[endif]-->

JSP Interview Questions


1 . What is JSP? Describe its concept
JSP is a technology that combines HTML/XML markup languages and elements of Java
programming Language to return dynamic content to the Web client, It is normally used to
handle Presentation logic of a web application, although it may have business logic.

2 . What are the lifecycle phases of a JSP?


JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP
engine does the following 7 phases.

1. Page translation: -page is parsed, and a java file which is a servlet is created.
2. Page compilation: page is compiled into a class file
3. Page loading : This class file is loaded.
4. Create an instance :- Instance of servlet is created
5. jspInit() method is called
6. _jspService is called to handle service calls
7. _jspDestroy is called to destroy it when the servlet is not required.

3 . What is a translation unit?

JSP page can include the contents of other HTML pages or other JSP files. This is done by
using the include directive. When the JSP engine is presented with such a JSP page it is
converted to one servlet class and this is called a translation unit, Things to remember in a
translation unit is that page directives affect the whole unit, one variable declaration cannot
occur in the same unit more than once, the standard action jsp:useBean cannot declare the
same bean twice in one unit.

4 . How is JSP used in the MVC model


JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays
the role of the view. The controller deals with calling the model and the business classes which
in turn get the data, this data is then presented to the JSP for rendering on to the client.

5 . What are context initialization parameters


Context initialization parameters are specified by the in the web.xml file, these are
initialization parameter for the whole application and not specific to any servlet or JSP.
6 . What is a output comment
A comment that is sent to the client in the viewable page source. The JSP engine handles an
output comment as un-interpreted HTML text, returning the comment in the HTML output sent
to the client. You can see the comment by viewing the page source from your Web browser.

7 . What is a Hidden Comment


A comment that documents the JSP page but is not sent to the client. The JSP engine ignores
a hidden comment, and does not process any code within hidden comment tags. A hidden
comment is not sent to the client, either in the displayed JSP page or the HTML page source.
The hidden comment is useful when you want to hide part of your JSP page.

8 . What is a Expression
Expressions are act as place holders for language expression, expression is evaluated each
time the page is accessed.

9 . What is a Declaration
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.

10 . What is a Scriptlet
A scriptlet can contain any number of language statements, variable or method declarations,
or expressions that are valid in the page scripting language. Within scriptlet tags, you can
declare variables or methods 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 <?
xml:namespace prefix = jsp />.
11 . What are the implicit objects
List them. Certain objects that are available for the use in JSP documents without being
declared first. These objects are parsed by the JSP engine and inserted into the generated
servlet. The implicit objects are:

1. request
2. response
3. pageContext
4. session
5. application
6. out
7. config
8. page
9. exception

12 . What’s the difference between forward and sendRedirect


When you invoke a forward request, the request is sent to another resource on the server,
without the client being informed that a different resource is going to process the request. This
process occurs completely with in the web container And then returns to the calling method.
When a sendRedirect method is invoked, it causes the web container to return to the browser
indicating that a new URL should be requested. Because the browser issues a completely new
request any object that are stored as request attributes before the redirect occurs will be lost.
This extra round trip a redirect is slower than forward.

13 . What are the different scope values for the


The different scope values for <?XML:NAMESPACE PREFIX = JSP />are:

1. page
2. request
3. session
4. application
14 . Why are JSP pages the preferred API for creating a web-based client program
Because no plug-ins or security policy files are needed on the client systems(applet does).
Also, JSP pages enable cleaner and more module application design because they provide a
way to separate applications programming from web page design. This means personnel
involved in web page design do not need to understand Java programming language syntax to
do their jobs.

15 . Is JSP technology extensible


Yes, it is. JSP technology is extensible through the development of custom actions, or tags,
which are encapsulated in tag libraries.

16 . What is difference between custom JSP tags and beans


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

17 . How can I implement a thread-safe JSP page? What are the advantages and
Disadvantages of using it?

You can make your JSPs thread-safe by having them implement the SingleThreadModel
interface. This is done by adding the directive <%@ page isThreadSafe=”false” %> within
your JSP page. With this, instead of a single instance of the servlet generated for your JSP
page loaded in memory, you will have N instances of the servlet loaded and initialized, with
the service method of each instance effectively synchronized. You can typically control the
number of instances (N) that are instantiated for all servlets implementing SingleThreadModel
through the admin screen for your JSP engine. More importantly, avoid using the tag for
variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned
above. Otherwise, all requests to that page will access those variables, causing a nasty race
condition. SingleThreadModel is not recommended for normal use. There are many pitfalls,
including the example above of not being able to use <%! %>. You should try really hard to
make them thread-safe the old fashioned way: by making them thread-safe

18 . How does JSP handle run-time exceptions


You can use the errorPage attribute of the page directive to have uncaught run-time
exceptions automatically forwarded to an error processing page. For example: <%@ page
errorPage=”error.jsp” %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during
request processing. Within error.jsp, if you indicate that it is an error-processing page, via the
directive: <%@ page isErrorPage=”true” %> Throwable object describing the exception may
be accessed within the error page via the exception implicit object. Note: You must always use
a relative URL as the value for the errorPage attribute.

19 . How do I prevent the output of my JSP or Servlet pages from being cached by the
browser
You will need to set the appropriate HTTP header attributes to prevent the dynamic content
output by the JSP page from being cached by the browser. Just execute the following scriptlet
at the beginning of your JSP pages to prevent them from being cached at the browser. You
need both the statements to take care of some of the older browser versions.
<%
response.setHeader(”Cache-Control”,”no-store”); //HTTP 1.1
response.setHeader(”Pragma”,”no-cache”); //HTTP 1.0
response.setDateHeader (”Expires”, 0); //prevents caching at the proxy server
%>

20 . How do I use comments within a JSP page


You can use JSP-style comments to selectively block out code while debugging or simply to
comment your scriptlets. JSP comments are not visible at the client. For example:
<%– the scriptlet is now commented out
<%
out.println(”Hello World”);
%>
–%>

You can also use HTML-style comments anywhere within your JSP page. These comments are
visible at the client. For example:

<!– (c) 2004 –>

Of course, you can also use comments supported by your JSP scripting language within your
scriptlets. For example, assuming Java is the scripting language, you can have:

<%
//some comment
/**
yet another comment
**/
%>

21 . Response has already been commited error. What does it mean


This error show only when you try to redirect a page after you already have written something
in your page. This happens because HTTP specification force the header to be set up before
the lay out of the page can be shown (to make sure of how it should be displayed, content-
type=”�text/html” or “text/xml” or “plain-text”� or “image/jpg”, etc.) When you try to send a
redirect status (Number is line_status_402), your HTTP server cannot send it right now if it
hasn’t finished to set up the header. If not starter to set up the header, there are no
problems, but if it’s already begin to set up the header, then your HTTP server expects these
headers to be finished setting up and it cannot be the case if the stream of the page is not
over.. In this last case it’s like you have a file started with some output (like testing your
variables.) Before you indicate that the file is over (and before the size of the page can be
setted up in the header), you try to send a redirect status. It s simply impossible due to the
specification of HTTP 1.0 and 1.1
22 . How do I use a scriptlet to initialize a newly instantiated bean
A jsp:useBean action may optionally have a body. If the body is specified, its contents will be
automatically invoked when the specified bean is instantiated. Typically, the body will contain
scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not
restricted to using those alone.
The following example shows the “today”� property of the Foo bean initialized to the current
date when it is instantiated. Note that here, we make use of a JSP expression within the
jsp:setProperty action.

value=”<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>”/ >


<%– scriptlets calling bean setter methods go here –%>”
23 . How can I enable session tracking for JSP pages if the browser has disabled cookies
We know that session tracking uses cookies by default to associate a session identifier with a
unique user. If the browser does not support cookies, or if cookies are disabled, you can still
enable session tracking using URL rewriting. URL rewriting essentially includes the session ID
within the link itself as a name/value pair. However, for this to be effective, you need to
append the session ID for each and every link that is part of your servlet response. Adding the
session ID to a link is greatly simplified by means of of a couple of methods:
response.encodeURL() associates a session ID with a given URL, and if you are using
redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.
Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported
by the browser; if so, the input URL is returned unchanged since the session ID will be
persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp
and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp
and place an object within this session. The user can then traverse to hello2.jsp by clicking on
the link present within the page.Within hello2.jsp, we simply extract the object that was
earlier placed in the session and display its contents. Notice that we invoke the encodeURL()
within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is
automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try
this example first with cookies enabled. Then disable cookie support, restart the brower, and
try again. Each time you should see the maintenance of the session across pages. Do note
that to get this example to work with cookies disabled at the browser, your JSP engine has to
support URL rewriting.
hello1.jsp
<%@ page session=”true” %>
<%
Integer num = new Integer(100);
session.putValue(”num”,num);
String url =response.encodeURL(”hello2.jsp”);
%>
hello2.jsp
<%@ page session=”true” %>
<%
Integer i= (Integer )session.getValue(”num”);
out.println(”Num value in session is “+i.intValue());

24 . How can I declare methods within my JSP page


You can declare methods for use within your JSP page as declarations. The methods can then
be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do
note that you do not have direct access to any of the JSP implicit objects like request,
response, session and so forth from within JSP methods. However, you should be able to pass
any of the implicit JSP variables as parameters to the methods you declare. For example:
<%!
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();

return req.getRemoteHost();
}
%>
<%
out.print(”Hi there, I see that you are coming in from “);
%>
<%= whereFrom(request) %>
Another Example
file1.jsp:
<%@page contentType=”text/html”%>
<%!
public void test(JspWriter writer) throws IOException{
writer.println(”Hello!”);
}
%>
file2.jsp
<%@include file=”file1.jsp”%>
<%test(out);% >

25 . Is there a way I can set the inactivity lease period on a per-session basis
Typically, a default inactivity lease period for all sessions is set within your JSP engine admin
screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API,
you can manage the inactivity lease period on a per-session basis. This is done by invoking
the HttpSession.setMaxInactiveInterval() method, right after the session has been created.
For example:
<%
session.setMaxInactiveInterval(300);
%>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in
seconds.

26 . How can I set a cookie and delete a cookie from within a JSP page
A cookie, mycookie, can be deleted using the following scriptlet:
<%
//creating a cookie
Cookie mycookie = new Cookie(”aName”,”aValue”);
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie(”mycookie”, null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath(”/”);
response.addCookie(killMyCookie);
%>

27 . How does a servlet communicate with a JSP page


The following code snippet shows how a servlet instantiates a bean and initializes it with FORM
data posted by a browser. The bean is then placed into the request, and the call is then
forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream
processing.
public void doPost (HttpServletRequest request, HttpServletResponse response) {
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter(”id”);
f.setName(request.getParameter(”name”));
f.setAddr(request.getParameter(”addr”));
f.setAge(request.getParameter(”age”));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute(”fBean”,f);
getServletConfig().getServletContext().getRequestDispatcher
(”/jsp/Bean1.jsp”).forward(request, response);
} catch (Exception ex) {
...
}
}
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default
request scope via the useBean action.

jsp:useBean id=”fBean” class=”govi.FormBean” scope=”request”


/ jsp:getProperty name=”fBean” property=”name”
/ jsp:getProperty name=”fBean” property=”addr”
/ jsp:getProperty name=”fBean” property=”age”
/ jsp:getProperty name=”fBean” property=”personalizationInfo” /

28 . How do I have the JSP-generated servlet subclass my own custom servlet class,
instead of the default
One should be very careful when having JSP pages extend custom servlet classes as opposed
to the default one generated by the JSP engine. In doing so, you may lose out on any
advanced optimization that may be provided by the JSP engine. In any case, your new
superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing
JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final
Additionally, your servlet superclass also needs to do the following:

The service() method has to invoke the _jspService() method

The init() method has to invoke the jspInit() method


The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:

<%@ page extends=”packageName.ServletName” %>

29 . How can I prevent the word “null” from appearing in my HTML input text fields
when I populate them with a resultset that has null values
You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? “” : s;
}
%>
then use it inside your JSP form, like
<input type=”text” name=”shoesize” value=”<%=blanknull(shoesize)% >” >

30 . How can I get to print the stacktrace for an exception occuring within my JSP page
By printing out the exceptionâ?Ts stack trace, you can usually diagonse a problem better
when debugging JSP pages. By looking at a stack trace, a programmer should be able to
discern which method threw the exception and which method called that method. However,
you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter.
You will have to use a PrintWriter object instead. The following snippet demonstrates how you
can print a stacktrace from within a JSP error page:
<%@ page isErrorPage=”true” %>
<%
out.println(” “);
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println(” “);
%>

31 . How do you pass an InitParameter to a JSP


The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can
use in their pages and are invoked in much the same manner as the init() and destory()
methods of a servlet. The example page below enumerates through all the parameters and
prints them to the console.
<%@ page import=”java.util.*” %>
<%!
ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+”=”+value);
}
}
%>

32 . How can my JSP page communicate with an EJB Session Bean


The following is a code snippet that demonstrates how a JSP page can interact with an EJB
session bean:
<%@ page import=”javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome,
foo.Account” %>
<%!
//declare a “global” reference to an instance of the home interface of the session bean
AccountHome accHome=null;
public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup(”java:comp/env/ejb/AccountEJB”);
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(…);
// etc etc…
%>

33 . Can we implement an interface in a JSP


No

34 . What is the difference between ServletContext and PageContext


ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request

35 . What is the difference in using request.getRequestDispatcher() and


context.getRequestDispatcher()
request.getRequestDispatcher(path): In order to create it we need to give the relative
path of the resource,
context.getRequestDispatcher(path): In order to create it we need to give the absolute
path of the resource.

36 . How to pass information from JSP to included JSP


Using <%jsp:param> tag.

37 . What is the difference between directive include and jsp include


<%@ include>: Used to include static resources during translation time. JSP include: Used to
include dynamic content or static content during runtime.

38 . What is the difference between RequestDispatcher and sendRedirect


RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.

39 . How do I mix JSP and SSI #include


If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.

But it’s a little trickier if you want the server to evaluate any JSP code that’s inside the
included file. If your data.inc file contains jsp code you will have to use
<%@ vinclude=”data.inc” %>
The is used for including non-JSP files.

Java Notes
Java is a programming language i.e. used to design the net based applications i.e. applications
that run securely over a network and work on wide range of platforms.

Java program is just nothing but a set of definitions of classes

Class is a model or prototype of an object i.e. required in the application.

Every class is defined with a set of attributes and a set of functions according to requirements
of the physical objects.

We can define the constructors in a class according to the application requirement to initialize
the values of the attributes for an object at the time of constructing the object.

We must specify the returning type for a method depending on the value of the method
returns, where as for a constructor we should not specify any returning type.

The name of a method can be given by the user as any name where as the name of the
constructor should exactly match with the name of the class.

main() is declared as public in order to allow the JVM to call the method being a non member
of the class.

In java variables of user defined data types are known as references. A reference is in the
background at pointer only. References are in fact restricted pointer.

According to the principles of OOP, all the objects that are created from the same class will
have same structure and behavior, but not the same state.

Whenever instance variable names and local variable names are the same always preference
is given for local variables. In such a case instance variables are not referred at all. As a result
object state can not be changed. To overcome this problem, we make use of keyword ‘this’.

Access Specifiers: An access specifier is a keyword in java. That is associated with the
members of class to specify their visibility or accessing mode.

AS Is visible Other class Child class Child class Other class


applied in same same same other other
class directory directory directory directory

private Y N N N N

default Y Y Y N N

protected Y Y Y Y N

public Y Y Y Y Y
To implement encapsulation in java, define a class and create the object.

To implement abstraction in java, define a class .declare some crucial BL methods as private.
Make some methods non private.

In OOP, objects communicate one another through message passing. From the code of one
class calling the code of another class is known as message passing.

Method overloading: Within the same class defining more than one method with the same
name is known as method overloading.

Main rule to implement overloading is that method signatures should be differ.

When method overloading is implemented in a class and if we create the object of that class,
that object becomes polymorphic.

Method overloading implements the concept of static polymorphism.

By implementing method overloading we make objects polymorphic. If the object is


polymorphic we achieve the extensibility of code and message passing becomes compact.

Inheritance: Creating new classes from the existing class for the sake of code reusability is
known as inheritance.

Sub class inherits all the variables and methods of super class irrespective of access specifiers.

Always our subject of interest will to create the objects of sub class to optimize the code
reusability.

Method overriding: Redefining the super class method in a sub class is known as method
overriding.

Method signatures should be same for super class method and sub class method. Return types
must be same.

Overriding method (sub class) should not be have lesser access privilege than that of
overridden method.

When overriding is implemented and method call is made on the sub class object always sub
class version only is executed.

Difference b/w static variable and instance variable:

Instance Variable Static variable

1 For each instance one separate For entire class only one copy is
copy is created created
2
Memory is allocated only when No relation when object existence
object is created. as soon as class is loaded into
environment, memory is created.

3 Objects own it. Objects do not own it but only


share it and manipulated.
4 Can’t be referred by the class Can be referred by both class
name. name and instance name.
Static method: is also known as a class method, if a method is declared a static, that method
can be called directly with the class name without the need of an object being created.

A static method can not access an instance variable. Similarly it can not call an instance
method, where as an instance method can access static variable and call static method also.

Abstract method: A method which has no body is known as on abstract method.

An abstract class cannot be instantiated only concrete class can be instantiated. Abstract class
concept is meaningful in the context of inheritance only.

An abstract class can act as data type i.e., its reference can be created even though its object
cannot be created.

An abstract method enforces method overriding i.e. if any class is inheriting from an abstract
class, it is the responsibility of that child class to override all the abstract methods of the super
class.

Binding: Associating method call with method definition is known as binding.

Categorization of polymorphism depends upon the type of binding involved.

Difference between overloading an overriding:

overloading overriding

1 Method signature should be Should be same.


2 different Methods return type must be
3 Return type has no same.
4 significance. It matters.
5 Access specifier has no It is mandatory.
significance It can participate in the
Inheritance is not mandatory implementation of dynamic
It implements static polymorphism
polymorphism

Final: If a method declared as a final, it is an indication to the child classes that its definition
is already finalized. Don’t try to redefine it. But can be inherited.

Abstract keyword enforces overriding of methods and final keyword prevents overriding.
Inheritance is not prevented in both cases.

Final class: Can not be sub classed i.e. inheritance is prevented.

Interface: Is a java language construct.

An interface differs from a class in the following ways….


1. It cannot be instantiated.
2. It can’t have concrete methods i.e. only contain abstract methods.
3. It can have only constants that too static.

Difference between an Abstract class and an Interface :

Abstract class Interface


1 Method implementations are Should not have
2 possible. Only constants
3 Not only constants other Implicitly public
4 variables possible It can support indirectly
5 Members are implicitly default. Provides standardization
Can not support multiple
inheritance
Provides generalization.

In java, one class cannot inherit from more than one class. But, one class can inherit from any
no. of interfaces besides inherit from single class.

Arrays in java: A collection of contiguous, homogeneous elements referred to a common


name.

Every array in java has property called length that gives the programmer its size.

Values supplied from the commandline to the main() during the program execution are known
as commandline arguments.

Constructors in inheritance:
Whenever sub class object is created, sub class constructor is called first but not executed.
From within the sub class constructor an implicit call is made to the super class
constructor(zero argument constructor only). If the constructor is found in super class, it will
be called.

As for calling is concerned it is for specialized to generalizes where as, it is reverse in


execution.

Compilation errors: are reported when the grammar(syntax) of the language is violated.
These are not all dangerous.

Execution time errors: are known as exceptions. During the program execution, if any
abnormal event occurs exception is fired.

Unchecked Exception: is that kind of exception which, even though you don’t deal within
your program does not become a syntactical error.

Checked Exception: must be handled in your program otherwise, it becomes a syntactical


error

If any abnormal event is generated with in the code of try block, JVM encapsulates that
abnormal event as appropriate exception object and throw it from the try block.

Try and catch are inseparable.

Finally: is a keyword used to create a block of statements. In this block we write that code
which need to be executed in both cases i.e. exception generating case and exception not
generated case.

Stream: A stream is an abstraction of an IO device (or) an IO resource.

A java program never ever need to directly deal with the IO devices. Instead, it deals with the
respective objects.

In multithreading n number of jobs are performed by a single process.


Thread: A single sequential flow of control is known as a thread.
A thread is an object in java. Right from its creation to destruction the series of life cycle
events are described by the following four states…..

1. New state: Thread t=new Thread();


2. Active state: we call start() method on the thread
3. Blocked state: join(), sleep(), wait()
4. Dead state: stop()

Synchronization:
Whenever 2 threads concurrently access a common resource, there is a possibility of data
integrity compromise.

Synchronization is a mechanism of allowing only one thread to access a resource when


multiple threads are competing for CPU cycles to action upon that shared resource.

Synchronization can be treated as a locking mechanism. As soon as one thread enters the
monitor, code is not locked. Instead, object(shared resource) is locked.

End user interacts with business applications throw graphical user interfaces of the application.

An applet is a small java program, it is stored in the server side, dynamically loaded to client
side along with web page and executed in the client side with in the confines of java enabled
browser.

Writing some special code along with the front end code to provide functionality for GUI
controls is the basic goal of event handling.

Defining a class in another class is known as nesting of class.

Inner class can access all the members of outer class including private members.

Difference between string and stringbuffer:


1. In principle both abstracts a sequence of characters, but the content of a
String can never be changed (it’s immutable) whereas a StringBuffer can(mutable).
2. string and stringbuffer both are the classes provided by jdk. Difference is
that object of string class is immutable and object of string buffer class is mutable moreover
stringbuffer is faster in concatenation.
3. Moreover in the case of StringBuffer no new object is created when you
use a string buffer….. But when you use string a new object is created and its access time is
slower when compared to string buffer..
4. If you encounter a lot of operations while performing string operations, try
to use Stringbuffer which is faster and easy to handle…use String objects to represent mostly
static strings….
5. Both String and StringBuffer are final classes.
6. For eg: to concate String s1=”ABC” and String s2=”DEF” we need another
string
String s3=s1+s2; which will have the value of “ABCDEF”; One cannot append it to s1. But
StringBuffer is mutable and one can change the contents of it. The same scenario in this case
can be s1.append(”DEF”); s1 becomes “ABCDEF”.

2-tier arch: In this model client is responsible for presentation logic and BL along with this it
should be intelligent to communicate with server. Server is responsible to maintain business
data and in some cases consists of some parts of logic like generating auto key….like server
can be database server.

Problems with this 2-tier arch:


1. PL && BL are combined this increases the complexity of client application.
2. BL is binded with PL this may lead to modify the BL whenever the PL is modified.
3. The resources required for the PL & BL has to be installed into the client environment.

3-tier arch: In this model client takes the responsibility for the PL and some logic which helps
to communicate with the middleware server. Middleware server is responsible to encapsulate
the BL and to interact with the backend server and includes NL i.e. intelligent to take the
request from the client and send response to the client.

As generic middleware servers has been introduced which are intelligent to make and resolves
HTTP format msg’s.

Servlet: is a standard specification used to develop web component in java.

Servlet Component: is a simple java class written following Servlet specification standards.

Servlet container is a 3rd party vendor application which provides all the low level services and
manages Servlet components.

Types of Servlet containers:


1. Standalone container, 2. In process Servlet container, 3. Out Process Container

Servlet API:
init(ServeltConfig)
service(ServletRequest, ServlerResponce)
destroy()
getServletConfig()
getServletInfo()

Servlet Lifecycle:
1. When container creates an instance of Servlet
After creating an instance of our Servlet class and before it is used to process the request container
creates ServletConfig type of instance for this Servlet.
Call init method on Servlet object and pass the ServletConfig type of object created.
2. When client makes a request
Locates the Servlet instance and create ServletRequest, ServlerResponce type of objects which
encapsulates request and response details.
Call service() method on Servlet object passing above ServletRequest, ServlerResponce type of
instances.
3. destroying
Container call destroy method on Servlet instance.

Request parameters: If we want to send some data from client to server and use it in the
server to process the request then we can submit this data in the form of name value pairs.
To get request parameter details in javax.servlet.ServletRequest we have given with following
methods
1. String getParameter(String)
2. String[] getParameterValues(String)
3. java.util.Enumeration getParameterNames()

Init Parameters: These are the Servlet instance level parameters where these parameters
are configured by the deployer at the time of deploying the application and are set into
ServletConfig type of object.

ServletConfig: is a standard abstraction through which Servlet instance can communicate


with the Servlet container to get some instance specific environmental details like Servlet
name & init parameters.
Is an interface which has to be implemented by the container provider.
Context Parameters: We have an additional requirement to maintain some data which is
common for the entire instance in the context and to meet this requirement context
parameters are introduced.

For one web application only one ServletContext type of object is created.

RequestDispacher: In a web component development we have a requirement to dispatch


the request from one component to the other.
We want one Servlet component intelligent to communicate(dispatch the request to) other
web components.

We have an option to get the other Servlet instance reference from the container using which
we can dispatch the request to other Servlet by just invoking service method on that instance.

Javax.servlet.RequestDispatcher is an interface with 2 methods


void include(ServletRequest, ServletResponce)
void forward(ServletRequest, ServletResponce)

To get a RequestDispatcher type of objects reference


RequestDispatcher getRequestDispatcher(String uri)

Using include or forward: Both of these options allows us to dispatch the request from our
Servlet to other component but forward has some restrictions like our Servlet(which is
forwarding the request) should not involve in generating the response content.

Using RD we can dispatch the request to only the component in the same context.

Attributes: we want to dispatch the request from one Servlet to other web component; we
may require making some data which is generated in the source Servlet to the destination
Servlet. To meet this requirement RequestAttributes option is given under Servlet
specification.

In javax.servlet.ServletRequest:
setAttribute(String, object)
getAttribute(String)
removeAttribute(String)

RequestAttributes are thread safe since scope of these attributes is request and as we know
that one request is completely processed by only one thread.

HTTP: is an appln layer protocol and it can not maintain client data and identify the client b/w
multiple requests.

HTTPServlet: is an abstract class but doesn’t consist of any abstract methods. It is sub type
of GenericServlet and doesn’t override init, destroy and other methods except it implements
service method which is an abstract method in Generic Servlet.
Additional methods in this class are
protected void service(-,-)throws ServletException, IOEception
protected void doGet(-,-)throws ServletException, IOEception
protected void doPost(-,-)throws ServletException, IOEception and all doXXX methods……
HTTPServletRequest: This type of object encapsulates all http specific request information.

Additional methods declared in this interface are


getHeader(String), String getMethod(), String getRequestURI()
String getContextPath(), String getServletPath()

HTTPServletResponce: is declared withal the method which can be used to set the http
specific response content and headers.
Some of additional methods declared in this interface are
setHeader(String, String), addCookie(), sendRedirect()

sendRedirect(): is one of the method in HTTPServletResponce. This method sets the location
header into the response. This is used to redirect the request from one resource to the other.

Difference b/w forward and sendRedirect:


1. With forward we can dispatch the request to the resource in the same context where as
with sendRedirect we can dispatch the request to the resource in the same context or other or
even resource in different server also.
2. forward instruction is executed in server side whereas sendRedirect instruction is executed
in client side.
3. redirect option provided under HTTP specification and hence it can be used only with HTTP
client whereas forward is protocol independent.

Session Tracking: For each request from client can have one connection, mean the
connection is destroyed for each completion of response from the server.

Session: A set of uninterrupted request and response b/w client && server where the data
with in this set of requests is known as session data.
Session tracking is concept which explains how to keep track of session data. This is required
to be managed in our appln by the container.

URLRewritting: In this case the data which has to required in the next request will be
appended to the url which has to be used by the client to make a next request

So that without clients knowledge this data will come from the client as a request parameters.

In an HTTPRequest GET, we can pass some small amount of data from client to server(i.e.
upto 256 char’s)and this data is appended to request uri and sent to the server where ‘?’ is
the separator b/w the request uri and this data.
Where each of the parameter in the query string is separated with ‘&’ char and the name and
value of the parameter is separated by ’=’ char.

This is not accepted for POST method request.

Problems with this approach:


1. since data is flowing in b/w client && server it increases n/w traffic.
2. it is less secure since data is moved b/w the n/w for multiple times and even data is
displayed
in the address bar.
3. All the views upto period where data is required to maintain should be dynamic views.

This option is used in following cases:


1. If we want to maintain small amount of data and if it is not required to be secure for a short
period.
2. If in a view generated we have multiple links to the same path but requires to generate
different o/p based on the link selected, in such a situation we have to use this option.
Hidden Form Fields: is one of the input fields. This type of field can be encapsulated within
the form. This field data is also included into the request while submitting the form i.e. along
with other type of field data. But this type of field is not displayed onto the screen i.e. not
visible in the view.
<input type=”hidden” name=”uname” value=”user1”>

Using these fields to make the data available for the next requests is almost same as
URLRewrittin but instead of appending the data to url in the server it will be done itself in the
client when the form is submitted.

And using this option we can submit the data using POST method also.
Cookies: Cookie is a small data unit saved in the client side for given host and path.
Each of cookies consists of following attributes….
Name, value, maxTime, host, path, isSecure.

These are saved in client side and when a client makes a request all the cookies whose path &
host matches with request url’s host & path are included into the request and sent to the
server.

In support for this under the specification it has given


Javax.servlet.http.Cookie
This follows DTO pattern i.e. used to exchange the data b/w container and component

In javax.servlet.http.HttpServletResponce
addCookie(Cookie)
In javax.servlet.http.HttpServletRequest
Cookie[] getCookies()

Advantages of using Cookies over above 2 options:


1. n/w traffic is reduced.
2. Can use static views in b/w the requests where we want to maintain the data.
3. Data dependency is reduced.
4. Reduces the appln logic complexity.

Limitations of using Cookies:


1. It is http specific.
2. Cookie size is allocated in the client is limited and varies from one client to the other.
3. Client has an option to disable cookies i.e. it may not allow us to save cookie in its system.

HTTPSession: In this case data which is required to be maintained in the server and a unique
identity for this data unit is generated by the container is required to be maintained by client.
For each of the client one HTTPSession type of object is created and all the data of the client
will be stored into this object.

Under Servlet specification javax.servlet.HttpSession is an interface declared with the methods


required to store and retrieves the data.

In support of this feature in HttpServletRequest 2 methods are included


HttpSession getSession()
HttpSession getSession(boolean)
In HttpSession we have following methods
boolean isNew(), setAttribute(String, Object)
Object getAttribute(String), removeAttribute(String), inValid()
putValue(String, Object), Object getValue(String)
String[] getValueNames(), String getID(), invalidate(), setMaxInactiveInterval(int)

Object set into session are not thread safe by default and there is a possibility that multiple
threads may use the same object at a time. So if required we need to make it synchronized.

Session created in one context, it will not extended to another context.

To test whether session id is maintained in cookie or using URLRewritting……..


Boolean isSessionIDFromCookie()
Boolean is SessionIDFromURL()

If multiple clients makes a request for the same Servlet then container creates or locates
multiple threads i.e. one threads for each request.
javax.servlet.SingleThreadModel: is a marker interface which marks our Servlet instance
to be thread safe and if multiple requests to same Servlet are made at a time then in this case
container may creates multiple instances to process these requests.

If we have any set of statements to be thread safe we are recommend using synchronized
blocks.

Connection Pool: To establish connection to the database & close the connection it consumes
some time and resources of DBMS.
By reducing the no. of connections establishing and closing operations, we will be able to
reduce the load on the database.

We require an intelligent appln which can be accessed by our appln and can manage the
connection objects perfectly and such an appln is known as Connection Pool Manager.

CPM is responsible for establishing the required no. of connections to DB, preparing a logical
connection & maintaining the connections.

Security: JAAS is a standard specification which allows us to provide a fine grained user
based security.
Authentication: is a process of finding whether the security details submitted by the user are
valid or not.
Authorization: is a process of finding whether an authenticated user has permission to
access the requested service or not.

Under Servlet specification in support of this feature HttpServletRequest interface is included


with the following methods…….
– javax.security.Principal getUserPrincipal()
– boolean isUserInRole(String)

Filters: These components are used to encapsulate the logic which has to be executed before
or after the actual request processing which is done by the requested resource.
Advantages: The interception points and the number of interceptions, order of various
interception can be declared at the time of deploying the appln instead of at the time of
developing the appln.

Some of the uses of filters are Session Validation, Encoding format verification, Logging
operations, Security verification, Output content transformation.
Javax.servlet.Filter interface is declared with 3 methods….
– init(FilterConfig)
– doFilter(ServlerRequest,ServletResponce,FilterChain) this method is invoked when a request
is made to the resource which is configured to be intercepted by this filter.
– destroy()
When we configure multiple filter-mappings for a Servlet, some of them with url-pattern and
some other with Servlet name in such a case first the filters configured with url-pattern are
given with preference then filter mapped with Servlet name.

Listeners: A listener is called when the user does something to the user interface that causes
an event. Although these events usually come from the user interface, they can have other
sources (eg, a Timer).
Wrappers: The Wrapper class represents the base class for a set of data sources. This class
provides library initialization services and access to the data source servers that the wrapper
supports.
In servlets2.3 specification we have been given with 4 wrapper classes i.e.
ServlerRequestWrapper, ServlerResponceWrapper
HttpServlerRequestWrapper, HttpServlerResponceWrapper
These wrapper classes allows us to perform some decorator services to the request and
response objects i.e. we can write a subclass for these wrappers and add some required
decorator logic.

As we know that Servlet allows us to provide a server side extension which is even use to
present some dynamic content and in this case this server side extension is provided in the
form of java class which follows some java standards.

JSP: provides tag based simplified approach to develop server side extension to present some
dynamic content.

Architecture:

Phases of JSP life cycle:


1. Translation: In this phase jsp translator reads jsp page resolves jsp instructions and write
an equivalent Servlet for the given instructions.
2. Compilation: JSP translator uses a java compiler and generates a class file for the Servlet
equivalent of our jsp which is written by it under the translation phase.
3. Loading & Initializing: The Servlet equivalent class is loaded into jvm & it is initialized
where under initialization process an instance of Servlet equivalent class is created then jsp
init method is called on it.
4. Request Processing: A request & response objects are created and are injected into the
instance which is created for Servlet equivalent class of our jsp(i.e._jsp method is called).
5. Destroying: The instance created in initialization phase is destroys in this phase.

The Servlet equivalent class which is prepared by the JSP translator should be sub type of
javax.servlet.jsp.JspPage

The methods declared in this interface are


– jspInit()
– _jspService()
Apart from those 2 methods destroy method is inherited from Servlet interface.

JSP TAGS:
Scripting Tags: these allows us to include some script content into the JSP document where
in a jsp document we are allowed to use java as scripting language.
Scriptlet: this tag used to encapsulate some script content which is part of _jsp method.
<% script code(can be multiple statements) %>
Declarative: This tag allows us to declare instance & class variables & implement some utility
methods. <%! Script content(can be multiple statements) %>
Expression: This tag takes a java expression which is resolved and then result value is
included into O/P. <% =java expression %>

Directives: These tags give some direction to jsp translator while translating the jsp
document and these tags are resolved and executed at the time of translation phase itself.
Page directive: This directive holds the directions which are used by the translator at the
time of translation and these instructions are used to effect various properties associated with
the page.
<%@page attributes %>
Attribute are import(takes imports), extends(is not recommended), erorPage(takes error page
path), isErrorPage(takes true or false), isThreadSafe(takes true or false), session(takes true or
false), language(takes scripting language), contentType(default is text/html),
autoFlush(default is true), buffer(takes buffer size).
Include Directive: is used to include some other page content into our page at a specified
location.
<%@include file=”” %>
Taglib directive: is used to declare any custom tag library in our jsp document so that tags
related to that custom tag can be used in this document.

Action Tags: These tags are XML complaint.


useBean: this tag is used to create or locate a java bean instance & set into required scope.
<jsp:useBean attributes> </ jsp:useBean>
Attributes are class(takes the qualified class name), id, scope, type(takes a class which is
super type of class), beanName).
In a useBean tag either class or beanName any one of them has been used not both.
setProperty: this tag lets us to invoke setXXX method of a java bean.
<jsp:setProperty attributes />
Attributes are name(takes ref variable name), property, value, param(takes request
parameter name).
getProperty: this tag used to invoke getXXX method & include return values into the O/P.
<jsp:getProperty name=”” property=”” />
forward: this tag is used to dispatch the request to another page in forward mode.
<jsp:forward page=”” > </jsp:forward>
include: this tag is also used to dispatch the request to another page in include mode.
<jsp:include page=””> </jsp:include>
param: this tag is used to set one parameter. This is allows to be used in include, forward &
params. <jsp:include page=”” >
<jsp:param name=”” value=”” />
</jsp:include>
plugin: this tag is used to include an applet/GUI based java bean into our O/P.
<jsp:plugin attributes> </jsp:plugin>
Attributes are code(takes class name), codeBase(takes base url where given class can be
located), width, height, vspace, hspace, achieve, jreversion.
params: this is allowed to be used inside plugin tag and this holds one or more param tags.
<jsp:params>
<jsp:param name=”” value=””/>
</jsp:params>
fallback: this tag is used inside plugin tag this tag takes some content which is included into
the O/P if the client cannot load the applet properly.
<jsp:fallback> </jsp:fallback>

Differences B/W directive include and action include:

action include directive include

1 Page which has to be included Included in translation phase


into our SEC at the time of
2 execution phase. In this case it is not possible
We can decide page which has
3 to be included at runtime. It doesn’t
It takes path dynamically.

IMPLICIT OBJECTS: this part of jsp specification standardized some object reference names
and their types so that the responsibility of initializing these ref variables in _jspService
method.

These are config(ServletConfig), application(ServletContext), expression(java.lang.Throwable


type), request(ServletRequest), page(is of java.lang.Object type refers to current page),
session(HttpSession),response(ServletResponce),pageContext(is of
javax.servlet.jsp.PageContext type), out(JspWriter).

These ref variables can not be used in declaration tag.


Jsp Comment: <%– content –%>

CUSTOM TAGS: The above tags are not enough to separate the PL from AL i.e. in spite of
using these we are still required to write some java code in jsp document to meet our
requirement.
Various elements involved with custom tags are
1. Tag Handler: this is java class which should sub type of tag. This class defines behavior
which has to be executed for our tag.
2. Tag Lib Declaration(TLD): this is a simple XML document where we can declare our tags
like tag name, its attributes & tag handler class where the tags behavior is defined.

Now these tags can be used in jsp document and before we use in document we need to
declare these set of tags making translator aware that there are some set of tags being used
in the document which has to be resolved. This is done using tag lib directive.
And the tags which has to be evaluated by translator has to be used with the declared prefix
i.e. <%@taglib prefix=”” uri=”” %>

javax.servlet.jsp.tagext.Tag is an interface which has to be super type for every tag


handler. Methods in this interface are doStartTag(), doEndTag().

Classic Tags:

Tag Handler(Tag class): doStartTag(), doEndTag(), setParent(Tag), getParent(),


setPageContext(PageContext), release().

Life Cycle of Tag Handler:


To improve performance and increase the reusability of objects container uses pooling
technique.
These instance are initialized and maintained in pool.
When there is a requirement of this instance
i. Object is collected from the pool.
ii. Calls setParent(Tag).
iii. Calls setPageContext().
iv. If any attributes are declared from the tag then it calls setXXX
method for those attributes.
v. Calls doStrartTag(). In case of empty tag doStrartTag can return only SKIP_BODY.
vi. Calls doEndTag().
vii. Calls release().

For each of the attributes required we should implement one set and get method in the Tag
Handler.
While declaring the Tag we should even declare it to hold our required attributes also i.e. in tld
file.

BodyTag: if our tag is not empty tag, then the TagHandler used to define the behavior for
such a tag should sub type of BodyTag.
The additional methods which are included with respective to the body tags are
setBodyContent(BodyContent), doInitBody(), doAfterBody().
And some constants given are EVAL_BODY_BUFFERED, EVAL_BODY_INCLUDE,
EVAL_BODY_AGAIN.

Life Cycle of BodyTag:

Iteration Tags: In this case we are allowed to evaluate the body part of the tag for multiple
times. BodyTag interface extends this interface. One constant declared in this interface is
EVAL_BODY_AGAIN and this value can be the return value of doAfterBody which results into
evaluating the body content again.
If we want to handle abnormal conditions raised by our TagHandler methods which are called
by _jspService method or even if we want to execute some finalization logic the we can use
the following interface…….javax.servlet.jsp.tagext.TryCatchFinally with the following methods
doCatch(Throwable), doFinally().

Simple Tags:
In case of Simple Tags container uses caching i.e. as in the case of classic tags container was
using tag pool.
When a tag whose TagHandler is defined as subtype of SimpleTag is used
i. Creates a new instance using no-arg constructor.
ii. Calls setJspContext which takes JspContext as arg.
iii. Calls setParent.
iv. Calls setXXX methods
v. Calls doStart Tag.
vi. The remaining operations will be depending on return value of
doStartTag same as of Classic Tags.

EXPRESSION LANGUAGE: is a simple scripting language.


${expression}
The expression is not built using java language syntax rather it is built according to EL syntax.
The built expression using EL syntax, we can use the Implicit objects(page scope, result
scope, session scope, application scope, param values, header, cookie, initparam).
JSTL: is initially released as a separated Taglib project later is developed following JSP spec.
Jstl tags are divided into 4 parts…..
1. core tags 2. sql tags 3. formatting tags 4. Xml tags

1. Core tags: these set of tags allows us to perform some basic prgming oprtns like setting
the attributes, using if condition, preparing loops…
URI to use these set of tags http://java.sun.com/jstl/core
Recommended prefix is ‘c’
For ex: <%@taglib uri=”http://java.sun.com/jstl/core” prefix=”c”%>
out: this tag is used to include some values to the o/p
<c:out value=”” scope=””/>
set: is used to set an attribute.
<c:set attributes/>
Attributes are value, var, scope, property
<c:set value=”${param.uname}” var=”username” scope=”session”/>
if: takes condition & if the given condition is resolved to true then it evaluate its body content.
<c:if test=”” var=”” scope=””>body part</c:if>
when: <c:when test=””>body part</c:when>
otherwise: <c:otherwise> body part </c:otherwise>
choose: is used in combination with when & otherwise.
<c:choose> body part </c:choose>
forEach: it takes a collection & iterates its body content for each of the element in the given collection.
<c:forEach attributes> body part </c:forEach>
Attributes are collection, scope, var, start, end, step
forToken: same as forEach but it takes a String.
<c:forTokens> body part </c:forTokens>

2. SQL tags: these set of tags allows us to communicate with DB.


setDataSource: is used to create data source for the page.
<sql:setDataSource attributes/>
Attributes are driver, url, user, password, var, scope, datasource.
query: is used to submit an sql query which can generate some results.
<sql:query attributes></sql:query>
Attributes are datasource, sql, var, scope, startRow, maxRows.
update: used to perform DML operations like insert, update, create, delete.
<sql:update attributes></sql:update>
param: used to set the value of the parameters
<sql:param value=””/>
dateParam: <sql:dateParam value=”” type=””/>
transaction: used to enclose one or more queries executed by query/update tags into on transaction.
<sql:transaction attributes></sql: transaction >
Attributes are datasource, isolation.

3. Formatting tags: this part of JSTL tags allows us to present the data in locale specific format and
even get the values of given message resolve key.
URI to use these set of tags http://java.sun.com/jstl/fmt
Recommended prefix is ‘fmt’
setBundle: <fmt:setBundle attributes/>
Attributes are basename, var, scope.
setLocale: <fmt:setLocale attributes/>
Attributes are value, var, scope.
message: this tag allows us to get the value specific to the locale for the given message
resource key and print it to the o/p or store it into the o/p.
<fmt:message attributes></fmt:message>
Attributes are bundle, key, var, scope.
param: used as a child tag of a message element & used to set the parameters of a message.
One param tag can set only one value.
<fmt:param value=””/>
bundle: used to pack some message tags.
<fmt:bundle basename=”” prefix=””></fmt:bundle>
formatNumber: <fmt:formatNumber attributes/>
Attributes are value, type, pattern, currencyCode, maxIntegerDigits, minIntegerDigits,
maxFractionDigits, minFractionDigits.
parseNumber: allows us to parse the formatted no. into number.
<fmt:parseNumber attributes/>
Attributes are value, type, integerOnly, var, scope, pattern.
formatDate: <fmt:formatDate attributes/>
Attributes are value, type, pattern, dateStyle, timeStyle, var, Scope.
parseDate: allows us to parse the formatted date value into a date type.
<fmt:parseDate value=”” type=”” var=”” scope=”” pattern=””/>

4. XML tags: these tags allows us to parse the xml content & get the data from the parsed
document even we can use these to perform some logical operations & looping.
parse: <x:parse value=”” var=”” scope=””/>
Some of xml tags are out, set, if, choose, when, otherwise, forEach, transform.

JavaScript Notes

Section I.1How to Put a JavaScript into an HTML Page:

<html>

<body>

<script type=”text/javascript”>

document.write(”Hello World!”)

</script>

</body>
</html>

The word document.write is a standard JavaScript command for writing output to a


page.

<!–

document.write(”Hello World!”)

//–>

The two forward slashes at the end of comment line (//) are a JavaScript comment
symbol. This prevents the JavaScript compiler from compiling the line.

<!--[if !supportLists]-->11. <!--[endif]-->Java Scripts in the body section will be executed


WHILE the page loads.

<html>

<head>

</head>

<body>

<script type=”text/javascript”>

document.write(”This message is written when the page loads”)

</script>

</body>

</html>

<!--[if !supportLists]-->12. <!--[endif]-->Java Scripts in the head section will be executed


when CALLED.

<html>

<head>

<script type=”text/javascript”>

function message()

alert(”This alert box was called with the onload event”)

}
</script>

</head>

<body onload=”message()”>

</body>

</html>

<!--[if !supportLists]-->13. <!--[endif]-->JavaScript in a page will be executed


immediately while the page loads into the browser. This is not always what we want.
Sometimes we want to execute a script when a page loads, other times when a user
triggers an event.

Scripts in the head section: Scripts to be executed when they are called, or when an
event is triggered, go in the head section. When you place a script in the head section,
you will ensure that the script is loaded before anyone uses it.

<html>

<head>

<script type=”text/javascript”>

….

</script>

</head>

Scripts in the body section: Scripts to be executed when the page loads go in the
body section. When you place a script in the body section it generates the content of the
page.

<html>

<head>

</head>

<body>

<script type=”text/javascript”>

….

</script>

</body>
Scripts in both the body and the head section: You can place an unlimited number
of scripts in your document, so you can have scripts in both the body and the head
section.

<html>

<head>

<script type=”text/javascript”>

….

</script>

</head>

<body>

<script type=”text/javascript”>

….

</script>

</body>

Using an External JavaScript:

Sometimes you might want to run the same JavaScript on several pages, without
having to write the same script on every page.

To simplify this, you can write a JavaScript in an external file. Save the external
JavaScript file with a .js file extension.

Note: The external script cannot contain the <script> tag!

To use the external script, point to the .js file in the “src” attribute of the <script>
tag:
<html>

<head>

<script src=”xxx.js”></script>

</head>

<body>

</body>

</html>

<!--[if !supportLists]-->1. <!--[endif]-->A variable is a “container” for


information you want to store. A variable’s value can change during
the script. You can refer to a variable by name to see its value or to
change its value.

You can create a variable with the var statement:

var strname = some value

You can also create a variable without the var statement:

strname = some value


<!--[if !supportLists]-->1. <!--[endif]-->If you declare a variable
outside a function, all the functions on your page can access it. The
lifetime of these variables starts when they are declared, and ends
when the page is closed.

If Statement:
<script type=”text/javascript”>

//Write a “Good morning” greeting if

//the time is less than 10

var d=new Date()

var time=d.getHours()

if (time<10)

document.write(”<b>Good morning</b>”)

</script>
If…else Statement:
<script type=”text/javascript”>

//If the time is less than 10,

//you will get a “Good morning” greeting.

//Otherwise you will get a “Good day” greeting.

var d = new Date()

var time = d.getHours()

if (time < 10)

document.write(”Good morning!”)

else

document.write(”Good day!”)

</script>
If…else if…else Statement:
<script type=”text/javascript”>

var d = new Date()

var time = d.getHours()

if (time<10)

document.write(”<b>Good morning</b>”)

else if (time>10 && time<16)

document.write(”<b>Good day</b>”)

else

document.write(”<b>Hello World!</b>”)

</script>

<!--[if gte vml 1]> <![endif]--><!--[if !vml]-->

<!--[endif]-->
The JavaScript Switch Statement:
<script type=”text/javascript”>

//You will receive a different greeting based

//on what day it is. Note that Sunday=0,

//Monday=1, Tuesday=2, etc.

var d=new Date()

theDay=d.getDay()

switch (theDay)

case 5:

document.write(”Finally Friday”)

break

case 6:

document.write(”Super Saturday”)

break

case 0:

document.write(”Sleepy Sunday”)

break

default:

document.write(”I’m looking forward to this weekend!”)

</script>

Conditional Operator:

JavaScript also contains a conditional operator that assigns a value to a variable based
on some condition.
Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor==”PRES”)?”Dear President “:”Dear ”

If the variable visitor is equal to PRES, then put the string “Dear President ” in the
variable named greeting. If the variable visitor is not equal to PRES, then put the string
“Dear” into the variable named greeting.

Alert Box:

An alert box is often used if you want to make sure information comes through to the
user.

When an alert box pops up, the user will have to click “OK” to proceed.

Syntax
alert(”sometext”)

Confirm Box:

A confirm box is often used if you want the user to verify or accept something.

When a confirm box pops up, the user will have to click either “OK” or “Cancel” to
proceed.

If the user clicks “OK”, the box returns true. If the user clicks “Cancel”, the box returns
false.

Syntax:

confirm(”sometext”)

Prompt Box:

A prompt box is often used if you want the user to input a value before entering a page.

When a prompt box pops up, the user will have to click either “OK” or “Cancel” to
proceed after entering an input value.

If the user clicks “OK” the box returns the input value. If the user clicks “Cancel” the
box returns null.

Syntax:
prompt(”sometext”,”defaultvalue”)

<!--[if !supportLists]-->1. <!--[endif]-->A function is a reusable code-


block that will be executed by an event, or when the function is
called.
<!--[if !supportLists]-->2. <!--[endif]-->Loops in JavaScript are used to
execute the same block of code a specified number of times or while
a specified condition is true.
<!--[if !supportLists]-->3. <!--[endif]-->The for…in statement is used
to loop (iterate) through the elements of an array or through the
properties of an object.
<!--[if !supportLists]-->4. <!--[endif]-->By using JavaScript, we have
the ability to create dynamic web pages. Events are actions that can
be detected by JavaScript.
<!--[if !supportLists]-->5. <!--[endif]-->Events are normally used in
combination with functions, and the function will not be executed
before the event occurs!

onload:

The onload event is often used to check the visitor’s browser type and
browser version, and load the proper version of the web page based on the
information. Both the onload and onUnload events are also often used to deal
with cookies that should be set when a user enters or leaves a page.

onFocus, onBlur and onChange:

The onFocus, onBlur and onChange events are often used in combination with
validation of form fields.

<input type=”text” size=”30″

id=”email” onchange=”checkEmail()”>;

onSubmit:

The onSubmit event is used to validate ALL form fields before submitting it.

<form method=”post” action=”xxx.htm”

onSubmit=”return checkForm()”>

onMouseOver and onMouseOut:

onMouseOver and onMouseOut are often used to create “animated” buttons.

<a href=”http://www.w3schools.com”

onmouseover=”alert(’An onMouseOver event’);return false”>

<img src=”w3schools.gif” width=”100″ height=”30″>

</a>
Try…Catch Statement:

The try…catch statement allows you to test a block of code for errors. The try
block contains the code to be run, and the catch block contains the code to be
executed if an error occurs.

<html>

<head>

<script type=”text/javascript”>

var txt=”"

function message()

try

addalert(”Welcome guest!”)

catch(err)

txt=”There was an error on this page.\n\n”

txt+=”Click OK to continue viewing this page,\n”

txt+=”or Cancel to return to the home page.\n\n”

if(!confirm(txt))

document.location.href=”http://www.w3schools.com/”

</script>

</head>
<body>

<input type=”button” value=”View message” onclick=”message()” />

</body>

</html>

The Throw Statement:

The throw statement allows you to create an exception. If you use this
statement together with the try…catch statement, you can control program
flow and generate accurate error messages.

<html>

<body>

<script type=”text/javascript”>

var x=prompt(”Enter a number between 0 and 10:”,”")

try

if(x>10)

throw “Err1″

else if(x<0)

throw “Err2″

catch(er)

if(er==”Err1″)

alert(”Error! The value is too high”)

if(er == “Err2″)

alert(”Error! The value is too low”)

</script>
</body>

</html>

The onerror Event:

Using the onerror event is the old standard solution to catch errors in a web
page. To use the onerror event, you must create a function to handle the
errors. Then you call the function with the onerror event handler. The event
handler is called with three arguments: msg (error message), url (the url of
the page that caused the error) and line (the line where the error occurred).

<html>

<head>

<script type=”text/javascript”>

onerror=handleErr

var txt=”"

function handleErr(msg,url,l)

txt=”There was an error on this page.\n\n”

txt+=”Error: ” + msg + “\n”

txt+=”URL: ” + url + “\n”

txt+=”Line: ” + l + “\n\n”

txt+=”Click OK to continue.\n\n”

alert(txt)

return true

function message()

adddlert(”Welcome guest!”)

</script>
</head>

<body>

<input type=”button” value=”View message” onclick=”message()” />

</body>

</html>

<!--[if !supportLists]-->21. <!--[endif]-->var txt=”We are the so-called \”Vikings\” from


the north.”

document.write(txt)

JavasScript will now output the proper text string: We are the so-called “Vikings” from the
north.

<!--[if !supportLists]-->22. <!--[endif]-->document.write (”You \& me are singing!”)

You & me are singing!

JavaScript Browser Detection:

23) The Navigator object contains information about the visitor’s browser name, browser
version, and more.

<!--[if !supportLists]--><!--[endif]-->appName - holds the name of the browser


<!--[if !supportLists]--><!--[endif]-->appVersion - holds, among other things, the
version of the browser
Example:
<html>

<body>

<script type=”text/javascript”>

var browser=navigator.appName

var b_version=navigator.appVersion

var version=parseFloat(b_version)

document.write(”Browser name: “+ browser)

document.write(”<br />”)

document.write(”Browser version: “+ b_version)

</script>

</body>

</html>

EJB Interview Questions

<!--[if gte mso 9]> Normal 0 MicrosoftInternetExplorer4 <![endif]-->

1 . What is EJB ?

EJB stands for Enterprise JavaBean and is a widely-adopted server side component
architecture for J2EE. It enables rapid development of mission-critical application that are
versatile, reusable and portable across middleware while protecting IT investment and
preventing vendor lock-in.

2 . What is session Facade?

Session Facade is a design pattern to access the Entity bean through local interface than
accessing directly. It increases the performance over the network. In this case we call session
bean which on turn call entity bean.

3 . What is EJB role in J2EE?

EJB technology is the core of J2EE. It enables developers to write reusable and portable
server-side business logic for the J2EE platform.
4 . What is the difference between EJB and Java beans?

EJB is a specification for J2EE server, not a product; Java beans may be a graphical
component in IDE

5 . What are the key features of the EJB technology?

1. EJB components are server-side components written entirely in the Java programming
language
2. EJB components contain business logic only - no system-level programming & services,
such as transactions, security, life-cycle, threading, persistence, etc. are automatically
managed for the EJB component by the EJB server.
3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and
secure.
4. EJB components are fully portable across any EJB server and any OS.
5. EJB architecture is wire-protocol neutral–any protocol can be utilized like IIOP,JRMP, HTTP,
DCOM,etc.

6 . What are the key benefits of the EJB technology?

1. Rapid application development


2. Broad industry adoption
3. Application portability
4. Protection of IT investment

7 . How many enterprise beans?

There are three kinds of enterprise beans:


1. session beans,
2. entity beans, and
3. message-driven beans.

8 . What is message-driven bean?

A message-driven bean combines features of a session bean and a Java Message Service
(JMS) message listener, allowing a business component to receive JMS. A message-driven
bean enables asynchronous clients to access the business logic in the EJB tier.

9 . What is Entity Bean and Session Bean ?

Entity Bean is a Java class which implements an Enterprise Bean interface and provides the
implementation of the business methods. There are two types: Container Managed
Persistence(CMP) and Bean-Managed Persistence(BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two types:
Stateless and Stateful. Stateless bean is the simplest bean. It doesn’t maintain any
conversational state with clients between method invocations. Stateful bean maintains state
between invocations.

10 . How EJB Invocation happens?

Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference
to the client. Create me a new EJB Object through Home Object interface. Create EJB Object
from the Ejb Object. Return EJB Object reference to the client. Invoke business method using
EJB Object reference. Delegate request to Bean (Enterprise Bean).
11 . Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a
value in the HttpSession from inside an EJB?

You can pass the HttpSession as parameter to an EJB method, only if all objects in session are
serializable.This has to be consider as passed-by-value, that means that it’s read-only in the
EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of
the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as
they are remote references. While it is possible to pass an HttpSession as a parameter to an
EJB object, it is considered to be bad practice in terms of object-oriented design. This is
because you are creating an unnecessary coupling between back-end objects (EJBs) and front-
end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than
passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a
class that acts as a value object (or structure) that holds all the data you need to pass back
and forth between front-end/back-end. Consider the case where your EJB needs to support a
non HTTP-based client. This higher level of abstraction will be flexible enough to support it.

12 . The EJB container implements the EJBHome and EJBObject classes. For every request from a
unique client, does the container create a separate instance of the generated EJBHome and
EJBObject classes?

The EJB container maintains an instance pool. The container uses these instances for the EJB
Home reference irrespective of the client request. while refering the EJB Object classes the
container creates a separate instance for each client request. The instance pool maintenance is
up to the implementation of the container. If the container provides one, it is available
otherwise it is not mandatory for the provider to implement it. Having said that, yes most of
the container providers implement the pooling functionality to increase the performance of the
application server. The way it is implemented is, again, up to the implementer.

13 . Can the primary key in the entity bean be a Java primitive type such as int?

The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For
example, you can use java.lang.Integer as the primary key class, but not int (it has to be a
class, not a primitive).

14 . Can you control when passivation occurs?

The developer, according to the specification, cannot directly control when passivation occurs.
Although for Stateful Session Beans, the container cannot passivate an instance that is inside
a transaction. So using transactions can be a a strategy to control passivation. The
ejbPassivate() method is called during passivation, so the developer has control over what to
do during this exercise and can implement the require optimized logic. Some EJB containers,
such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls.
Taken from the WebLogic 6.0 DTD -The passivation-strategy can be either default or
transaction. With the default setting the container will attempt to keep a working set of beans
in the cache. With the transaction setting, the container will passivate the bean after every
transaction (or method call for a non-transactional invocation).

15 . What is the advantage of using Entity bean for database operations, over directly using JDBC
API to do database operations? When would I use one over the other?

Entity Beans actually represents the data in a database. It is not that Entity Beans replaces
JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In
Container Managed Entity Bean - Whenever the instance of the bean is created the container
automatically retrieves the data from the DB/Persistance storage and assigns to the object
variables in bean for user to manipulate or use them. For this the developer needs to map the
fields in the database to the variables in deployment descriptor files (which varies for each
vendor). In the Bean Managed Entity Bean - The developer has to specifically make
connection, retrive values, assign them to the objects in the ejbLoad() which will be called by
the container when it instatiates a bean object. Similarly in the ejbStore() the container saves
the object values back the the persistance storage. ejbLoad and ejbStore are callback methods
and can be only invoked by the container. Apart from this, when you use Entity beans you
dont need to worry about database transaction handling, database connection pooling etc.
which are taken care by the ejb container.

16 . What is EJB QL?

EJB QL is a Query Language provided for navigation across a network of enterprise beans and
dependent objects defined by means of container managed persistence. EJB QL is introduced
in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity
beans with container managed persistenceand is portable across containers and persistence
managers. EJB QL is used for queries of two types of finder methods: Finder methods that are
defined in the home interface of an entity bean and which return entity objects. Select
methods, which are not exposed to the client, but which are used by the Bean Provider to
select persistent values that are maintained by the Persistence Manager or to select entity
objects that are related to the entity bean on which the query is defined.

17 . Brief description about local interfaces?

EJB was originally designed around remote invocation using the Java Remote Method
Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for
these calls using RMI/IIOP. This design allowed for maximum flexibility in developing
applications without consideration for the deployment scenario, and was a strong feature in
support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is,
some or all of their EJB calls are between beans in a single container. With this feedback in
mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface
may be defined for a bean during development, to allow streamlined calls to the bean if a
caller is in the same container. This does not involve the overhead involved with RMI like
marshalling etc. This facility will thus improve the performance of applications in which co-
location is planned. Local interfaces also provide the foundation for container-managed
relationships among entity beans with container-managed persistence.

18 . What are the special design care that must be taken when you work with local interfaces?

It is important to understand that the calling semantics of local interfaces are different from
those of remote interfaces. For example, remote interfaces pass parameters using call-by-
value semantics, while local interfaces use call-by-reference. This means that in order to use
local interfaces safely, application developers need to carefully consider potential deployment
scenarios up front, then decide which interfaces can be local and which remote, and finally,
develop the application code with these choices in mind. While EJB 2.0 local interfaces are
extremely useful in some situations, the long-term costs of these choices, especially when
changing requirements and component reuse are taken into account, need to be factored into
the design decision.

19 . What happens if remove( ) is never invoked on a session bean?

In case of a stateless session bean it may not matter if we call or not as in both cases nothing
is done. The number of beans in cache is managed by the container. In case of stateful
session bean, the bean may be kept in cache till either the session times out, in which case
the bean is removed or when there is a requirement for memory in which case the data is
cached and the bean is sent to free pool.

20 . What is the difference between Message Driven Beans and Stateless Session beans?
In several ways, the dynamic creation and allocation of message-driven bean instances mimics
the behavior of stateless session EJB instances, which exist only for the duration of a
particular method call. However, message-driven beans are different from stateless session
EJBs (and other types of EJBs) in several significant ways: Message-driven beans process
multiple JMS messages asynchronously, rather than processing a serialized sequence of
method calls. Message-driven beans have no home or remote interface, and therefore cannot
be directly accessed by internal or external clients. Clients interact with message-driven beans
only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly
interacts with a message-driven bean by creating bean instances and passing JMS messages
to those instances as necessary. The Container maintains the entire lifecycle of a message-
driven bean; instances cannot be created or removed as a result of client requests or other
API calls

21 . How can I call one EJB from inside of another EJB?

EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the
other bean, then acquire an instance reference, and so forth.

22 . What is an EJB Context?

EJBContext is an interface that is implemented by the container, and it is also a part of the
bean-container contract. Entity beans use a subclass of EJBContext called EntityContext.
Session beans use a subclass called SessionContext. These EJBContext objects provide the
bean class with information about its container, the client using the bean and the bean itself.
They also provide other functions. See the API docs and the spec for more details.

23 . Is it possible for an EJB client to marshal an object of class java.lang.Class to an EJB?

Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class
to obtain information about the declared members that are not otherwise accessible to the
enterprise bean because of the security rules of the Java language.

24 . Is it legal to have static initializer blocks in EJB?

Although technically it is legal, static initializer blocks are used to execute some piece of code
before executing any constructor or method while instantiating a class. Static initializer blocks
are also typically used to initialize static fields - which may be illegal in EJB if they are
read/write - In EJB this can be achieved by including the code in either the ejbCreate(),
setSessionContext() or setEntityContext() methods.

25 . Is it possible to stop the execution of a method before completion in a SessionBean?

Stopping the execution of a method inside a Session Bean is not possible without writing code
inside the Session Bean. This is because you are not allowed to access Threads inside an EJB.

26 . What is the default transaction attribute for an EJB?

There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that
the deployer must specify a value for the transaction attribute for those methods having
container managed transaction. In WebLogic, the default transaction attribute for EJB is
SUPPORTS.

27 . What is the difference between session and entity beans? When should I use one or the
other?
An entity bean represents persistent global data from the database; a session bean represents
transient user-specific data that will die when the user disconnects (ends his session).
Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call
entity beans (e.g. Account.deposit, Account.withdraw)

28 . Is there any default cache management system with Entity beans ?

In other words whether a cache of the data in database will be maintained in EJB ? - Caching
data from a database inside the AAApplication Server are what Entity EJB’s are used for.The
ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the
persistent storage(database). Transactions also play an important role in this scenario. If data
is removed from the database, via an external application - your Entity Bean can still be alive
the EJB container. When the transaction commits, ejbStore() is called and the row will not be
found, and the transaction rolled back.

29 . Why is ejbFindByPrimaryKey mandatory?

An Entity Bean represents persistent data that is stored outside of the EJB Container/Server.
The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the
container, similar to a SELECT statement in SQL. By making this method mandatory, the client
programmer can be assured that if they have the primary key of the Entity Bean, then they
can retrieve the bean without having to create a new bean each time - which would mean
creating duplications of persistent data and break the integrity of EJB.

30 . Why do we have a remove method in both EJBHome and EJBObject?

With the EJBHome version of the remove, you are able to delete an entity bean without first
instantiating it (you can provide a PrimaryKey object as a parameter to the remove method).
The home version only works for entity beans. On the other hand, the Remote interface
version works on an entity bean that you have already instantiated. In addition, the remote
version also works on session beans (stateless and stateful) to inform the container of your
loss of interest in this bean.

31 . How can I call one EJB from inside of another EJB?

EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the
other bean, then acquire an instance reference, and so forth.

32 . What is the difference between a Server, a Container, and a Connector?

An EJB server is an application, usually a product such as BEA WebLogic, that provides (or
should provide) for concurrent client connections and manages system resources such as
threads, processes, memory, database connections, network connections, etc. An EJB
container runs inside (or within) an EJB server, and provides deployed EJB beans with
transaction and security management, etc. The EJB container insulates an EJB bean from the
specifics of an underlying EJB server by providing a simple, standard API between the EJB
bean and its container. A Connector provides the ability for any Enterprise Information System
(EIS) to plug into any EJB server which supports the Connector architecture. See Sun’s J2EE
Connectors for more in-depth information on Connectors.

33 . How is persistence implemented in enterprise beans?

Persistence in EJB is taken care of in two ways, depending on how you implement your beans:
container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB
container which your beans run under takes care of the persistence of the fields you have
declared to be persisted with the database - this declaration is in the deployment descriptor.
So, anytime you modify a field in a CMP bean, as soon as the method you have executed is
finished, the new data is persisted to the database by the container. For BMP, the EJB bean
developer is responsible for defining the persistence routines in the proper places in the bean,
for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the
bean developer to make calls to the database. The container is responsible, in BMP, to call the
appropriate method on the bean. So, if the bean is being looked up, when the create() method
is called on the Home interface, then the container is responsible for calling the ejbCreate()
method in the bean, which should have functionality inside for going to the database and
looking up the data.

34 . What is an EJB Context?

EJBContext is an interface that is implemented by the container, and it is also a part of the
bean-container contract. Entity beans use a subclass of EJBContext called EntityContext.
Session beans use a subclass called SessionContext. These EJBContext objects provide the
bean class with information about its container, the client using the bean and the bean itself.
They also provide other functions. See the API docs and the spec for more details.

35 . Is method overloading allowed in EJB?

Yes you can overload methods

36 . Should synchronization primitives be used on bean methods?

No. The EJB specification specifically states that the enterprise bean is not allowed to use
thread primitives. The container is responsible for managing concurrent access to beans at
runtime.

37 37. Are we allowed to change the transaction isolation property in middle of a transaction?

No. You cannot change the transaction isolation level in the middle of transaction.

38 38. For Entity Beans, What happens to an instance field not mapped to any persistent storage,
when the bean is passivated?

The specification infers that the container never serializes an instance of an Entity bean (unlike
stateful session beans). Thus passivation simply involves moving the bean from the ready to
the pooled bin. So what happens to the contents of an instance variable is controlled by the
programmer. Remember that when an entity bean is passivated the instance gets logically
disassociated from it’s remote object. Be careful here, as the functionality of
passivation/activation for Stateless Session, Stateful Session and Entity beans is completely
different. For entity beans the ejbPassivate method notifies the entity bean that it is being
disassociated with a particular entity prior to reuse or for dereference.

39 39. What is a Message Driven Bean, what functions does a message driven bean have and how
do they work in collaboration with JMS?

Message driven beans are the latest addition to the family of component bean types defined
by the EJB specification. The original bean types include session beans, which contain business
logic and maintain a state associated with client sessions, and entity beans, which map objects
to persistent data. Message driven beans will provide asynchrony to EJB based applications by
acting as JMS message consumers. A message bean is associated with a JMS topic or queue
and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and
session beans, message beans do not have home or remote interfaces. Instead, message
driven beans are instantiated by the container as required. Like stateless session beans,
message beans maintain no client-specific state, allowing the container to optimally manage a
pool of message-bean instances. Clients send JMS messages to message beans in exactly the
same manner as they would send messages to any other JMS destination. This similarity is a
fundamental design goal of the JMS capabilities of the new specification. To receive JMS
messages, message driven beans implement the javax.jms.MessageListener interface, which
defines a single onMessage() method. When a message arrives, the container ensures that a
message bean corresponding to the message topic/queue exists (instantiating it if necessary),
and calls its onMessage method passing the client’s message as the single argument. The
message bean’s implementation of this method contains the business logic required to process
the message. Note that session beans and entity beans are not allowed to function as
message beans.

40 40. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP
connection in the same way as RMI does across a JRMP connection?

Yes. The JDK 1.2 support the dynamic class loading. The EJB container implements the
EJBHome and EJBObject classes. For every request from a unique client

41 41. Does the container create a separate instance of the generated EJBHome and EJBObject
classes?

The EJB container maintains an instance pool. The container uses these instances for the EJB
Home reference irrespective of the client request. while refering the EJB Object classes the
container creates a separate instance for each client request. The instance pool maintainence
is up to the implementation of the container. If the container provides one, it is available
otherwise it is not mandatory for the provider to implement it. Having said that, yes most of
the container providers implement the pooling functionality to increase the performance of the
application server. The way it is implemented is again up to the implementer

42 42. What is the advantage of putting an Entity Bean instance from the Ready State to Pooled
state?

The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has
been created, but has not been yet synchronized or assigned to an EJBObject. This mean that
the instances do represent entity beans, but they can be used only for serving Home methods
(create or findBy), since those methods do not relay on the specific values of the bean. All
these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon
Thorarinsson has also added: It can be looked at it this way: If no client is using an entity
bean of a particular type there is no need for cachig it (the data is persisted in the database).
Therefore, in such cases, the container will, after some time, move the entity bean from the
Ready State to the Pooled state to save memory. Then, to save additional memory, the
container may begin moving entity beans from the Pooled State to the Does Not Exist State,
because even though the bean’s cache has been cleared, the bean still takes up some memory
just being in the Pooled State.

Potrebbero piacerti anche