Você está na página 1de 37

Sem- 6

ADVANCE JAVA-2

QB
UNIT 1.
1.difference between Generic servlet and https servlet.
Generic servlet
https servlet
GenericServlet defines a generic, protocolHttpServlet defines a HTTP protocol specific
independent servlet.
servlet.
GenericServlet is an abstractclass it can handle
all types of protocols
Generic Servlet only supports service()
method.

HttpServlet can handle only Http specific


protocols.
HttpServlet supports also
doGet(),doPost(),doPut(),doDelete(),doHead(),do
Trace(),doOptions()etc.

GenericServlet class is direct subclass of


Servlet interface.

HttpServlet class is the direct subclass of Generic


Servlet.

Defined javax.servlet package.

Defined javax.servlet.http package.

2.what is servlet? Difeerent types of servlet?


->Servlet can be described in many ways, depending on the context.
o

Servlet is a technology i.e. used to create web application.

Servlet is an API that provides many interfaces and classes including documentations.

Servlet is an interface that must be implemented for creating any servlet.

There are two main servlet types, generic and HTTP:


1) Generic servlet- GenericServlet defines a generic, protocol-independent servlet.
Generic Servlet only supports service() method.
Defined javax.servlet package.
2) https servlet- HttpServlet defines a HTTP protocol specific servlet.
HttpServlet supports also doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions()etc.
Defined javax.servlet.http package.

Sem- 6

ADVANCE JAVA-2

QB
Overriding Method of servlet1)The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
2)The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

4. explain how get and post requests are handled using servlets with appropriate examples.

Sem- 6

ADVANCE JAVA-2

QB
-> 1)Handling GET requests-Handling GET requests involves overriding the doGet method. The
following example shows the BookDetailServlet doing this.
examplespublic class BookDetailServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" +
"<head><title>Book Description</title></head>" +
...);
//Get the identifier of the book to display
String bookId = request.getParameter("bookId");
if (bookId != null) {
// and the information about the book and print it
...
}
out.println("</body></html>");
out.close();
}
...
}
The servlet extends the HttpServlet class and overrides the doGet method.
Within the doGet method, the getParameter method gets the servlet's expected argument.
To respond to the client, the example doGet method uses a Writer from
the HttpServletResponse object to return text data to the client. Before accessing the writer, the
example sets the content-type header. At the end of the doGet method, after the response has been
sent, the Writer is closed.

Sem- 6

ADVANCE JAVA-2

QB

2) Handling POST Requests-Handling POST requests involves overriding the doPost method. The
following example shows the ReceiptServlet doing this
public class ReceiptServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" +
"<head><title> Receipt </title>" +
...);
out.println("<h3>Thank you for purchasing your books from us " +
request.getParameter("cardname") +
...);
out.close();
}
...
}
The servlet extends the HttpServlet class and overrides the doPost method.
Within the doPost method, the getParameter method gets the servlet's expected argument.
To respond to the client, the example doPost method uses a Writer from
the HttpServletResponse object to return text data to the client. Before accessing the writer the
example sets the content-type header. At the end of the doPost method, after the response has been
set, the Writer is closed.

Sem- 6

ADVANCE JAVA-2

QB
5.write a short note on Servlet Life Cycle.
-> The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:

1.Servlet class is loaded- The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.
2.Servlet instance is created- The web container creates the instance of

a servlet after loading the

servlet class. The servlet instance is created only once in the servlet life cycle.
3.init method is invokedThe web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
4.service method is invoked- The web container calls the service method each time when request for
the servlet is received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet
is initialized only once. The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5.destroy method is invoked- The web container calls the destroy method before removing the
servlet instance from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:
public void destroy()

Sem- 6

ADVANCE JAVA-2

QB
6.Explain methods used for reading Form Data From Servlets.
-> reading Form Data using Servlet:
Servlets handles form data parsing automatically using the following methods depending on the
situation:

getParameter(): You call request.getParameter() method to get the value of a form


parameter.

getParameterValues(): Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.

getParameterNames(): Call this method if you want a complete list of all parameters in the
current request.

Sem- 6

ADVANCE JAVA-2

QB

7.State and Explain any five methods of HttpServletRequest.


->HttpServletRequest is an interface and extends the ServletRequest interface. By extending the
ServletRequest this interface is able to allow request information for HTTP Servlets. Object of the
HttpServletRequest is created by the Servlet container and, then, it is passed to the service method
(doGet(), doPost(), etc.) of the Servlet.
Extends the ServletRequest interface to provide request information for HTTP servlets.
The servlet container creates an HttpServletRequest object and passes it as an argument to the
servlet's service methods (doGet, doPost, etc.).
i. public String getAuthType()
Returns the name of the authentication scheme used to protect the servlet.
ii. public String getContextPath ()
Returns the portion of the request URI that indicates the context of the request.
iii. public Cookie [] getCookies ( )
Returns an array containing all of the cookie objects the client sent with this request.
iv public long getDateHeader(String name)
Returns the value of the specified request header as a long value that represents a date object.
v public String getHeader(String name)
Returns the value of the specified request header as a string.

8. State and Explain any five methods of HttpServletResponce.


->HttpServletResponse is a predefined interface present in javax.servlet.http package. It can be
said that it is a mirror image of request object. The response object is where the servlet can
write information about the data it will send back. Whereas the majority of the methods in the
request object start with GET, indicating that they get a value, many of the important methods in
the response object start with SET, indicating that they change some property. Note that these
interfaces adhere to the usual naming conventions for beans.
Methods in HttpServletResponse
i. public void addCookie(Cookie cookie)

Sem- 6

ADVANCE JAVA-2

QB
Adds the specified cookie to the response. This method can be called multiple times to set more than
one cookie.
ii. public void addDateHeader (String name, long date)
Adds a response header with the given name and date-value.
iii. public void addHeader(String name,String value)
Adds a response header with the given name and value.
iv public void addlntHeader(String name,int value)
Adds a response header with the given name and integer value.
v public boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.

9.Explain The Java Servlet Architecture.


->

Servlets read the explicit data sent by the clients (browsers).


This includes an HTML form on a Web page or it could also come from
an applet or a custom HTTP client program.

Read the implicit HTTP request data sent by the clients


(browsers). This includes cookies, media types and compression
schemes the browser understands, and so forth.

Sem- 6

ADVANCE JAVA-2

QB

Process the data and generate the results. This process may
require talking to a database, executing an RMI or CORBA call,
invoking a Web service, or computing the response directly.

Send the explicit data (i.e., the document) to the clients


(browsers). This document can be sent in a variety of formats,
including text (HTML or XML), binary (GIF images), Excel, etc.

Send the implicit HTTP response to the clients (browsers). This


includes telling the browsers or other clients what type of document
is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.

10.11.Write a short note on HttpSession.


-> HttpSession object is used to store entire session with a specific client. We can store, retrieve and
remove attribute from HttpSession object. Any servlet can have access to HttpSession object
throughout the getSession() method of the HttpServletRequest object.
How HttpSession works--1.

On client's first request, the Web Container generates a unique session ID and gives it back
to the client with response. This is a temporary session created by web container.

2.

The client sends back the session ID with each request. Making it easier for the web
container to identify where the request is coming from.

3.

The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.

Methods of HttpSession--String getId()

returns a string containing the unique identifier assigned to the session.

Sem- 6

ADVANCE JAVA-2

QB
void invalidate()

destroy the session

boolean isNew()

returns true if the session is new else false

Use of HttpSession class To use the Java servlet API for session tracking,
first create a session object using the getSession method in the HttpServletRequest interface
like this:
HttpSession session = request.getSession(true);
This obtains the session or creates a new session if the client does not have a session on the
server.
The HttpSession class provides the methods for reading and storing data to the session, and
for manipulating the session.

12.Explain following interface a)ServletContext b)ServletConfig


->
a)ServletContext Interface-- An object of ServletContext is created by the web container.
This object can be used to get configuration information from web.xml file. There is only one
ServletContext object per web application.
Advantage of ServletContext1. Provides communication between servlets
2. Available to all servlets and JSPs that are part of the web app
3. Used to get configuration information from web.xml
methods of ServletContext interface1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Object getAttribute(String name):Returns the attribute for the specified name.

Sem- 6

ADVANCE JAVA-2

QB
b)ServletConfig Interface- An object of ServletConfig is created by the web container for each
servlet. This object can be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the
servlet. So it is easier to manage the web application if any specific content is modified from time to
time.
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.
Methods of ServletConfig
1. public String getServletName():Returns the name of the servlet.
2. public ServletContext getServletContext():Returns an object of ServletContext.

16.what are cookies?


-> A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

Sem- 6

ADVANCE JAVA-2

QB

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1)Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.

Sem- 6

ADVANCE JAVA-2

QB
2)Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Constructor of Cookie class

Cookie()

constructs a cookie.

Cookie(String name, String value)

constructs a cookie with a specified name and value.

Methods of Cookie class


public String getValue()

Returns the value of the cookie.

public void setName(String name)

changes the name of the cookie.

Sem- 6

ADVANCE JAVA-2

QB

18.what is role of filter in servlets ? explain any five servlet filters.


-> A filter is an object that is invoked at the preprocessing and postprocessing of a request.
It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption
and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of
filter from the web.xml file, filter will be removed automatically and we don't need to change the
servlet.
Role of Filter
o

recording all incoming requests

logs the IP addresses of the computers from which the requests originate

conversion

data compression

encryption and decryption

input validation etc.

There are are various types of filters suggested by the specifications:

Authentication Filters.

Data compression Filters.

Encryption Filters.

Filters that trigger resource access events.

Image Conversion Filters.

Advantage of Filter
1. Filter is pluggable.

Sem- 6

ADVANCE JAVA-2

QB
2. One filter don't have dependency onto another resource.
3. Less Maintenance

23.Write a note on RequestDispatcher Interface.


-> The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the content of
another resource also. It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface


1. public

void

forward(ServletRequest

request,ServletResponse

response)throws

ServletException,java.io.IOException:Forwards a request from a servlet to another


resource (servlet, JSP file, or HTML file) on the server.
2. public

void

include(ServletRequest

request,ServletResponse

response)throws

ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page,


or HTML file) in the response.

Syntax of getRequestDispatcher method


public RequestDispatcher getRequestDispatcher(String resource);

Sem- 6

ADVANCE JAVA-2

QB

UNIT-2

1.Explain advantages of JSP over Servlets.


-> Advantages of JSP over Servlets

Servlets use println statements for printing an HTML document which is usually very
difficult to use. JSP has no such tedius task to maintain.

JSP needs no compilation, CLASSPATH setting and packaging.

In a JSP page visual content and logic are seperated, which is not possible in a servlet.

There is automatic deployment of a JSP, recompilation is done automatically when changes


are made to JSP pages.

Usually with JSP, Java Beans and custom tags web application is simplified.

2) how does web server process jsp file


->

1. Web browser sends an HTTP request to the web server requesting JSP page.
2. Web server recognizes that the HTTP request by web browser is for JSP page by checking
the extension of the file (i.e .jsp)
3. Web server forwards HTTP Request to JSP engine.
4. JSP engine loads the JSP page from disk and converts it into a servlet
5. JSP engine then compiles the servlet into an executable class and forward original request
to a servlet engine.

Sem- 6

ADVANCE JAVA-2

QB
6. Servlet engine loads and executes the Servlet class.
7. Servlet produces an output in HTML format
8. Output produced by servlet engine is then passes to the web server inside an HTTP
response.
9. Web server sends the HTTP response to Web browser in the form of static HTML content.
10. Web browser loads the static page into the browser and thus user can view the
dynamically generated page.

4.Write a short note on JSP Access model.


-> JSP Access Models
The early JSP specifications advocated two philosophical approaches, popularly known as Model 1
and Model 2 architectures, for applying JSP technology. These approaches differ essentially in the
location at which the bulk of the request processing was performed, and offer a useful paradigm for
building applications using JSP technology.
Model 1 architecture

Sem- 6

ADVANCE JAVA-2

QB
In the Model 1 architecture, the incoming request from a web browser is sent directly to the JSP
page, which is responsible for processing it and replying back to the client. There is still separation
of presentation from content, because all data access is performed using beans.
Although the Model 1 architecture is suitable for simple applications, it may not be desirable for
complex implementations. Indiscriminate usage of this architecture usually leads to a significant
amount of scriptlets or Java code embedded within the JSP page, especially if there is a significant
amount of request processing to be performed. While this may not seem to be much of a problem
for Java developers, it is certainly an issue if your JSP pages are created and maintained by
designers--which is usually the norm on large projects. Another downside of this architecture is that
each of the JSP pages must be individually responsible for managing application state and verifying
authentication and security.
Model 2 architecture

The Model 2 architecture, shown above, is a server-side implementation of the popular


Model/View/Controller design pattern. Here, the processing is divided between presentation and
front components. Presentation components are JSP pages that generate the HTML/XML response
that determines the user interface when rendered by the browser. Front components (also known as
controllers) do not handle any presentation issues, but rather, process all the HTTP requests. Here,
they are responsible for creating any beans or objects used by the presentation components, as well

Sem- 6

ADVANCE JAVA-2

QB
as deciding, depending on the user's actions, which presentation component to forward the request
to. Front components can be implemented as either a servlet or JSP page.
The advantage of this architecture is that there is no processing logic within the presentation
component itself; it is simply responsible for retrieving any objects or beans that may have been
previously created by the controller, and extracting the dynamic content within for insertion within
its static templates. Consequently, this clean separation of presentation from content leads to a clear
delineation of the roles and responsibilities of the developers and page designers on the
programming team. Another benefit of this approach is that the front components present a single
point of entry into the application, thus making the management of application state, security, and
presentation uniform and easier to maintain.

7.Write a short note on JSP include directive.


->

Jsp Include Directive

The include directive is used to include the contents of any resource it may be jsp file, html file or
text file. The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include static resource).
Advantage of Include directive
Code Reusability
Syntax of include directive
1.

<%@ include file="resourceName" %>


Example of include directive
In this example, we are including the content of the header.html file. To run this example you must
create an header.html file.

1.

<html>

2.

<body>

3.

Sem- 6

ADVANCE JAVA-2

QB
4.

<%@ include file="header.html" %>

5.
6.

Today is: <%= java.util.Calendar.getInstance().getTime() %>

7.
8.

</body>

9.

</html>

8.state and explain scope of JSP object.


->Scope of JSP Objects-The availability of a JSP object for use from a particular place of the application is defined as the
scope of that JSP object. Every object created in a JSP page will have a scope. Object scope in JSP
is segregated into four parts and they are page, request, session and application.

page
page scope means, the JSP object can be accessed only from within the same page where it
was created. The default scope for JSP objects created using <jsp:useBean> tag is page. JSP
implicit objects out, exception, response, pageContext, config and page have page scope.

request
A JSP object created using the request scope can be accessed from any pages that serves
that request. More than one page can serve a single request. The JSP object will be bound to
the request object. Implicit object request has the request scope.

session
session scope means, the JSP object is accessible from pages that belong to the same
session from where it was created. The JSP object that is created using the session scope is
bound to the session object. Implicit object session has the session scope.

Sem- 6

ADVANCE JAVA-2

QB

application
A JSP object created using the application scope can be accessed from any pages across the
application. The JSP object is bound to the application object. Implicit object application
has the application scope.

9.Explain page directive with any five attributes.


->JSP page directive
The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive<%@ page attribute="value" %>
Attributes of JSP page directive
1)import- The import attribute is used to import class,interface or all the
members of a package.It is similar to import keyword in java class or
interface.
Example of import attribute
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>

2)errorPage-The errorPage attribute is used to define the error page, if


exception occurs in the current page, it will be redirected to the error page.
Example of errorPage attribute
<%@ page errorPage="myerrorpage.jsp" %>

3)isErrorPage-The isErrorPage attribute is used to declare that the current


page is the error page.
Example of isErrorPage attribute
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>

Sem- 6

ADVANCE JAVA-2

QB

The exception is: <%= exception %>

4)buffer-The buffer attribute sets the buffer size in kilobytes to handle output
generated by the JSP page.The default size of the buffer is 8Kb.
Example of buffer attribute
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>

5)info-This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet interface.
Example of info attribute
<%@ page info="composed by Sonoo Jaiswal" %>
Today is: <%= new java.util.Date() %>

13.What is custom tag ?how can it be used in JSP.


-> Custom tags are user-defined tags. They eliminates the possibility of
scriptlet tag and separates the business logic from the JSP page.
The same business logic can be used many times by the use of custom tag.

Advantages of Custom Tags

The key advantages of Custom tags are as follows:


1. Eliminates the need of scriptlet tag The custom tags eliminates the need
of scriptlet tag which is considered bad programming approach in JSP.

Sem- 6

ADVANCE JAVA-2

QB
2. Separation of business logic from JSP The custom tags separate the the
business logic from the JSP page so that it may be easy to maintain.
3. Re-usability The custom tags makes the possibility to reuse the same
business logic again and again.

Syntax to use custom tag

There are two ways to use the custom tag. They are given below:
1.

<prefix:tagname attr1=value1....attrn=valuen />

1.

<prefix:tagname attr1=value1....attrn=valuen >

2.

body code

3.

</prefix:tagname>

14.Explain Four JSP action elements.


-> JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or
generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />

1)The <jsp:include> Action

Sem- 6

ADVANCE JAVA-2

QB
This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a
servlet, this action inserts the file at the time the page is requested.
Following is the list of attributes associated with include action:
Attribute

Description

page

The relative URL of the page to be included.

flush

The boolean attribute determines whether the included resource has its buffer
flushed before it is included.

2)The <jsp:useBean> Action


The useBean action is quite versatile. It first searches for an existing object utilizing the id and
scope variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows:
<jsp:useBean id="name" class="package.class" />
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and
retrieve bean properties.
Following is the list of attributes associated with useBean action:
Attribute

Description

Sem- 6

ADVANCE JAVA-2

QB
class

Designates the full package name of the bean.

type

Specifies the type of the variable that will refer to the object.

3)The <jsp:forward> Action


The forward action terminates the action of the current page and forwards the request to another
resource such as a static page, another JSP page, or a Java Servlet.
The simple syntax of this action is as follows:
<jsp:forward page="Relative URL" />
Following is the list of required attributes associated with forward action:
Attribute

Description

page

Should consist of a relative URL of another resource such as a static page,


another JSP page, or a Java Servlet.

4)The <jsp:getProperty> Action


The getProperty action is used to retrieve the value of a given property and converts it to a string,
and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required ans simple syntax is as
follows:
<jsp:useBean id="myName" ... />
...
<jsp:getProperty name="myName" property="someProperty" .../>

Sem- 6

ADVANCE JAVA-2

QB
Following is the list of required attributes associated with setProperty action:
Attribute

Description

name

The name of the Bean that has a property to be retrieved. The Bean must have
been previously defined.

property

The property attribute is the name of the Bean property to be retrieved.

17.what are implicit objects? Explain any four implicit object of jsp.
-> JSP Implicit Objects are the Java objects that the JSP Container makes available to developers
in each page and developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables.

1) The request Object:


The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a
client requests a page the JSP engine creates a new object to represent that request.
The request object provides methods to get HTTP header information including form data,
cookies, HTTP methods etc.

Sem- 6

ADVANCE JAVA-2

QB

2)The response Object:


The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the
server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers.
Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes
etc.

3)The page Object:


This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
The page object is really a direct synonym for the this object.

4)The exception Object:


The exception object is a wrapper containing the exception thrown from the previous page. It is
typically used to generate an appropriate response to the error condition.

UNIT-3

1)what is Enterprise java beans? Explain types of EJB.


->EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems to
develop secured, robust and scalable distributed applications.
To run EJB application, you need an application server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc. It performs:
a. life cycle management,
b. security,
c. transaction management, and

Sem- 6

ADVANCE JAVA-2

QB
d. object pooling.
EJB application is deployed on the server, so it is called server side component also.
EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from Java
Bean, RMI and Web Services.

Types of Enterprise Java Bean


There are 3 types of enterprise bean in java.

Session BeanSession bean contains business logic that can be invoked by local, remote or webservice client.

Message Driven BeanLike Session Bean, it contains the business logic but it is invoked by passing message.

Entity Bean
It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is replaced
with JPA (Java Persistent API).

2.Explain the life cycle of Stateless Session Bean.

Sem- 6

ADVANCE JAVA-2

QB

1.Does Not Exit-The client initiates the life cycle by obtaining a reference to a stateless session
bean.the container performs any dependency injection ,and then invokes the method
@PostConstruct,if any .the client can now invoke the business methods of the bean.

2.Ready to Does Not Exit At the end of session bean like cyckle,the EJB container calls the
method ,the bean instance is then ready for garbage collection.

Callback method @postConstruct-the container invokes this method on newly contructed bean instance
after all dependency injection are completed, and before the first business method is
invoked on the enterprise bean.

@PreDestroy-these

method are invoked after any method @remove is completed,and

before the container removes the enterprices bean instance.

Sem- 6

ADVANCE JAVA-2

QB

3.Explain the life cycle of Stateful Session Bean.


->

Moving from the Does Not Exist to the Ready State


When a client invokes a create method on a stateful session bean, the EJB container creates a new
instance and invokes the callback method public void setSessionContext(SessionContext ctx). This
method has the parameter javax.ejb.SessionContext, which contains a reference to the session
context, that is, the interface to the EJB container, and can be used to self-reference the session bean
object.

The Ready State


A stateful bean instance in the ready state is tied to a particular client for the duration of their
conversation. During this conversation the instance can the execute component methods invoked by
the client.

Activation and Passivation


If after passivation a client application continues the conversation by invoking a business method,
the passivated bean instance is reactivated; its data stored on disk is used to restore the bean
instance state. Right after the state has been restored, the callback method ejbActivate is invoked. If
your session bean needs to execute some custom logic after activation, you can implement it using
this callback method. The caller (a client application or another EJB) of the session bean instance
will be unaware of passivation (and reactivation) having taken place.

Moving from the Ready to the Does Not Exist State


When a client application invokes a remove method on the stateful session bean, it terminates the
conversation and tells the EJB container to remove the instance. Just prior to deleting the instance,
the EJB container will call the callback method ejbRemove. If your session bean needs to
execute some custom logic prior to deletion, you can implement it using this callback method.

Sem- 6

ADVANCE JAVA-2

QB
An inactive stateful session bean that is set up to use the NRU (not recently used) cache-type
algorithm can time out, which moves it to the does not exist state, that is, it is removed. Prior to
removal the EJB container will call the callback method ejbRemove. If a stateful session bean set
up to use the LRU (least recently used) algorithm times out, it always moves to the passivated state,
and is not removed.

4.Explain the life cycle of Message Driven Bean.

There are two states: does not exist and method-ready pool. To transition from the does not exist
state to the method-ready pool state, the following occurs: the newInstance method is invoked,
dependency injection occurs (if any), the MDB method annotated as PostConstruct (if any) or the
ejbCreate method (if present) is invoked. While in the method-ready pool state, the following
methods may be invoked: message listener method or ejbTimeout. To transition from the methodready pool state to the does not exist state, the following occurs: the MDB method annotated as
PreDestroy (if any) or the ejbRemove method (if present) is invoked .

Sem- 6

ADVANCE JAVA-2

QB

5.What is a Message-Driven Bean. State its characteristics.


->

A message-driven bean is an enterprise bean that allows Java EE applications to


process messages asynchronously. This type of bean normally acts as a JMS message
listener, which is similar to an event listener but receives JMS messages instead of
events. The messages can be sent by any Java EE component (an application client,
another enterprise bean, or a web component) or by a JMS application or system that
does not use Java EE technology. Message-driven beans can process JMS messages
or other kinds of messages.

Message-driven beans have the following characteristics.

They execute upon receipt of a single client message.

They are invoked asynchronously.

They are relatively short-lived.

They do not represent directly shared data in the database, but they can access and
update this data.

They can be transaction-aware.

They are stateless.

6.What is message listener ?explain onMessage method.


-> A MessageListener object is used to receive asynchronously delivered messages.
Each session must ensure that it passes messages serially to the listener. This means that a listener
assigned to one or more consumers of the same session can assume that the onMessage method is
not called with the next message until the session has completed the last call.
onMessage
void onMessage(Message message)

Sem- 6

ADVANCE JAVA-2

QB
Passes a message to the listener.
Parameters:
message - the message passed to the listener

11)what is Enterprise java beans? Benifits of EJB.


-> EJB is an acronym for enterprise java bean. It is a specification provided by Sun Microsystems to
develop secured, robust and scalable distributed applications.
To run EJB application, you need an application server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc. It performs:
a. life cycle management,
b. security,
c. transaction management, and
d. object pooling.
EJB application is deployed on the server, so it is called server side component also.
EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from Java
Bean, RMI and Web Services.

Benefits

Simplified development of large scale enterprise level application.

Application Server/ EJB container provides most of the system level services like
transaction handling, logging, load balancing, persistence mechanism, exception handling
and so on. Developer has to focus only on business logic of the application.

EJB container manages life cycle of ejb instances thus developer needs not to worry about
when to create/delete ejb objects.

Sem- 6

ADVANCE JAVA-2

QB

15. difference between java bean and ejb.


->

Jave bean
1.they can be either visible or
non-visible
2.they are intended to be local to
single process on the client side.

Ejb
1.they are non-visible remote
objects.
2.they are remotely executable
components deployed on the
server.
3.they use the deployment
descriptor to describe themselves

3.they use Beaninfo classes and


property editors.and they
customize to describe themselves.
4.they can also be deployed as
4.they cannot be deployed as
active control
active control,since OCXs run on
desktop.

16. . difference between stateless session beans and stateful session


beans.
stateless session beans
1.they do not posses internal
state.

stateful session beans


1.they possess internal state .

Sem- 6

ADVANCE JAVA-2

QB

2.they cannot be passivated.


3.they can surve for multiple
client.
4.they create network traffic.

2.they can undergo passivation


and activation.
3.they are specific to a single
client.
4.stateful beans hurt scalability.

14.explain any two annotations used for developing ejb.


-> EJB container uses compiler tool to generate required artifacts like interfaces,
deployment descriptors by reading those annotations. Following is the list of
commonly used annotations.
javax.ejb.Stateless

Specifies that a given ejb class is a stateless session bean.


Attributes

javax.ejb.Stateful

name - Used to specify name of the session bean.

mappedName - Used to specify the JNDI name of the session bean.

description - Used to provide description of the session bean.

Specifies that a given ejb class is a stateful session bean.

Sem- 6

ADVANCE JAVA-2

QB
Attributes

name - Used to specify name of the session bean.

mappedName - Used to specify the JNDI name of the


session bean.

UNIT-4

6.what is JAX-WS ?explain the uses of JAX-WS.


->Java API for XML Web Services (JAX-WS) is a technology for building web services and clients
that communicate using XML. JAX-WS allows developers to write message-oriented as well as
Remote Procedure Call-oriented (RPC-oriented) web services.
In JAX-WS, a web service operation invocation is represented by an XML-based protocol, such as
SOAP. The SOAP specification defines the envelope structure, encoding rules, and conventions for
representing web service invocations and responses. These calls and responses are transmitted as
SOAP messages (XML files) over HTTP.
Although SOAP messages are complex, the JAX-WS API hides this complexity from the application
developer. On the server side, the developer specifies the web service operations by defining
methods in an interface written in the Java programming language. The developer also codes one
or more classes that implement those methods. Client programs are also easy to code. A client
creates a proxy (a local object representing the service) and then simply invokes methods on the
proxy. With JAX-WS, the developer does not generate or parse SOAP messages. It is the JAX-WS
runtime system that converts the API calls and responses to and from SOAP messages.
With JAX-WS, clients and web services have a big advantage: the platform independence of the
Java programming language. In addition, JAX-WS is not restrictive: A JAX-WS client can access a
web service that is not running on the Java platform, and vice versa. This flexibility is possible
because JAX-WS uses technologies defined by the W3C: HTTP, SOAP, and WSDL. WSDL specifies
an XML format for describing a service as a set of endpoints operating on messages.

Sem- 6

ADVANCE JAVA-2

QB

7.Explain SOAP ,UDDI, AND WDSL .


->SOAP provides the envelope for sending Web Services messages over the Internet/Internet. It is
part of the set of standards specified by the W3C. SOAP is an alternative to Representational State
Transfer (REST) and JavaScript Object Notation (JSON).
The SOAP envelope contains two parts:
1.

An optional header providing information on authentication, encoding of data, or how a


recipient of a SOAP message should process the message.
2.
The body that contains the message. These messages can be defined using the WSDL
specification.
SOAP commonly uses HTTP, but other protocols such as Simple Mail Transfer Protocol (SMTP)
may by used. SOAP can be used to exchange complete documents or to call a remote procedure.

Você também pode gostar