0% found this document useful (0 votes)
49 views

Model Answer DAA

The document provides answers to questions about algorithms and data structures. It defines algorithm validation as verifying an algorithm meets its specifications. It states that selection sort has a tightest upper bound of O(n) swaps. Greedy algorithms are used to solve optimization problems by making locally optimal choices. The control abstraction for divide and conquer divides a problem into smaller instances, solves them recursively, and combines the solutions.

Uploaded by

jjkk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Model Answer DAA

The document provides answers to questions about algorithms and data structures. It defines algorithm validation as verifying an algorithm meets its specifications. It states that selection sort has a tightest upper bound of O(n) swaps. Greedy algorithms are used to solve optimization problems by making locally optimal choices. The control abstraction for divide and conquer divides a problem into smaller instances, solves them recursively, and combines the solutions.

Uploaded by

jjkk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Model Answer

Design & Analysis Of Algorithm


Q.1 Answer the following question (any 5):
a) What is algorithm validation ?

Ans :- Algorithm validation is the process of verifying that an algorithm meets


its specifications and performs as intended.

It involves checking the logic, the inputs, the outputs, and the behavior of the
algorithm under different scenarios and conditions.

b) What is tightest upper bound that represents the no of swaps


required to sort n numbers using selection sort.

Ans :- :- The tightest upper bound that represents the number of swaps
required to sort n numbers using selection sort is O(n).

(O(n)) is represents the tightest upper bound for the number of swaps required
to sort n numbers using selection sort.

c) Algorithm based on greedy method are used for solving

i. Liner problem.
ii. Optimization problem.
iii. Quadratic problem.
iv. Biquadratic problem.

Ans :- The correct answer is ii) Optimization problems.

Greedy algorithms are a problem-solving approach that involves making a locally


optimal choice at each step, hoping that these choices will lead to a globally
optimal solution.

d) Write the control abstraction for divide and conquer method.

Ans :- A control abstraction is a procedure whose flow of control is clear but


whose primary operations are specified by other procedures whose precise
meanings are left undefined. The control abstraction for divide and conquer
technique is DANDC(P), where P is the problem to be solved.

 DANDC (P)
 {
 if SMALL (P) then return S (p);
 else
 {
 divide p into smaller instances p1, p2, …. Pk, k  1;
 apply DANDC to each of these sub problems;
 return (COMBINE (DANDC (p1) , DANDC (p2),…., DANDC
(pk));
 }
 }

e) Define feasible and optimal solution.

Ans :-

Feasible solution :

A feasible solution is a set of values for the decision variables that satisfies all of
the constraints in an optimization problem. The set of all feasible solutions
defines the feasible region of the problem.

Optimal solution :

An optimal solution is a feasible solution where the objective function reaches its
maximum (or minimum) value.

f) What is code tuning technique ?

Ans :- Code tuning, also known as code optimization or performance tuning,


refers to the process of improving the performance of a computer program by
making changes to its source code.

The goal of code tuning is to enhance the program's execution speed, reduce its
memory usage, and generally optimize its resource utilization.

Q.2
a) Write short note on optimal merge pattern.

Ans :- Given n number of sorted files, the task is to find the minimum
computations done to reach the Optimal Merge Pattern.

When two or more sorted files are to be merged altogether to form a single file,
the minimum computations are done to reach this file are known as Optimal
Merge Pattern.

If more than 2 files need to be merged then it can be done in pairs. For
example, if need to merge 4 files A, B, C, D. First Merge A with B to get X1,
merge X1 with C to get X2, merge X2 with D to get X3 as the output file.
If we have two files of sizes m and n, the total computation time will be m+n.
Here, we use the greedy strategy by merging the two smallest size files among
all the files present.

Example :

Given a set of unsorted files: 5, 3, 2, 7, 9, 13

Now, arrange these elements in ascending order: 2, 3, 5, 7, 9, 13

After this, pick two smallest numbers and repeat this until we left with only one
number.

Step 1 : Insert 2, 3

Step 2 :

Step 3 : Insert 5

Step 4 : Insert 13
Step 5 : Insert 7 And 9

Step 6 :

So, The merging cost = 5 + 10 + 16 + 23 + 39 = 93

b) Explain Knapsack problem in detail.

Ans :- The knapsack problem is an optimization problem used to illustrate both


problem and solution. It derives its name from a scenario where one is
constrained in the number of items that can be placed inside a fixed-size
knapsack.

Given a set of items with specific weights and values, the aim is to get as much
value into the knapsack as possible given the weight constraint of the knapsack.

The knapsack problem is an example of a combinational optimization problem, a


topic in mathematics and computer science about finding the optimal object
among a set of objects.

This is a problem that has been studied for more than a century and is a
commonly used example problem in combinatorial optimization, where there is a
need for an optimal object or finite solution where an exhaustive search is not
possible.
The problem can be found real-world scenarios like resource allocation in
financial constraints or even in selecting investments and portfolios.

It also can be found in fields such as applied mathematics, complexity theory,


cryptography, combinatorics and computer science. It is easily the most
important problem in logistics.

In the knapsack problem, the given items have two attributes at minimum – an
item’s value, which affects its importance, and an item’s weight or volume,
which is its limitation aspect.

Since an exhaustive search is not possible, one can break the problems into
smaller sub-problems and run it recursively. This is called an optimal sub-
structure. This deals with only one item at a time and the current weight still
available in the knapsack.

The problem solver only needs to decide whether to take the item or not based
on the weight that can still be accepted. However, if it is a program, re-
computation is not independent and would cause problems.

This is where dynamic programming techniques can be applied. Solutions to


each sub-problem are stored so that the computation would only need to happen
once.

Q.3
a) Explain binary search? Write algorithm for it. Consider the following
elements of array A.

Index 1 2 3 4 5 6 7 8 9 10

element -15 -10 0 7 12 30 45 58 82 104

Ans :-

b) Explain activity selection problem.

Ans :- The activity selection problem is a mathematical optimization problem.


Our first illustration is the problem of scheduling a resource among several
challenge activities. We find a greedy algorithm provides a well designed and
simple method for selecting a maximum- size set of manually compatible
activities.

Activity Selection problem is a approach of selecting non-conflicting tasks based


on start and end time and can be solved in O(N logN) time using a simple greedy
approach. Modifications of this problem are complex and interesting which we
will explore as well. Suprising, if we use a Dynamic Programming approach, the
time complexity will be O(N^3) that is The problem statement for Activity
Selection is that "Given a set of n activities with their start and finish times, we
need to select maximum number of non-conflicting activities that can be
performed by a single person, given that the person can handle only one activity
at a time." The Activity Selection problem follows Greedy approach i.e. at every
step, we can make a choice that looks best at the moment to get the optimal
solution of the complete problem.

Steps for Activity Selection Problem :

Step 1 : Sort the given activities in ascending order according to their finishing
time.

Step 2 : Select the first activity from sorted array act[] and add it to sol[] array.

Step 3 : Repeat steps 4 and 5 for the remaining activities in act[].

Step 4 : If the start time of the currently selected activity is greater than or
equal to the finish time of previously selected activity, then add it to
the sol[] array.

Step 5 : Select the next activity in act[] array.

Step 6 : Print the sol[] array.

Q.4
a) What is minimum spanning tree ? Explain Kruskal’s algorithm with
following example.

Ans :-

Minimum Spanning Tree :

A minimum spanning tree (MST) is defined as a spanning tree that has the
minimum weight among all the possible spanning trees

A spanning tree is defined as a tree-like subgraph of a connected, undirected


graph that includes all the vertices of the graph. Or, to say in Layman’s words, it
is a subset of the edges of the graph that forms a tree (acyclic) where every
node of the graph is a part of the tree.

The minimum spanning tree has all the properties of a spanning tree with an
added constraint of having the minimum possible weights among all possible
spanning trees. Like a spanning tree, there can also be many possible MSTs for a
graph.
i. Sort all the edges in non-decreasing order of their weight.
ii. Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far. If the cycle is not formed, include this edge. Else, discard
it.
iii. Repeat step#2 until there are (V-1) edges in the spanning tree.

The graph contains 9 vertices and 14 edges. So, the minimum spanning tree
formed will be having (9 – 1) = 8 edges.
After sorting :

Weight Source Destination


1 7 6
2 8 2
2 6 5
4 0 1
4 2 5
6 8 6
7 2 3
7 7 8
8 0 7
8 1 2
9 3 4
10 5 4
11 1 7
14 3 5

Step 1 : Pick edge 7-6. No cycle is formed, include it.

Step 2 : Pick edge 8-2. No cycle is formed, include it.


Step 3 :

Step 4 : Pick edge 0-1. No cycle is formed, include it.

Step 5 : Pick edge 2-5. No cycle is formed, include it.


Step 6 : Pick edge 8-6. Since including this edge results in the cycle, discard
it. Pick edge 2-3: No cycle is formed, include it.

Step 7 : Pick edge 7-8. Since including this edge results in the cycle, discard
it. Pick edge 0-7. No cycle is formed, include it.

Step 8 : Pick edge 1-2. Since including this edge results in the cycle, discard
it. Pick edge 3-4. No cycle is formed, include it.
Note : Since the number of edges included in the MST equals to (V – 1), so the
algorithm stops here

b) How are Application builder categorized ?

Ans :- Builder tools allow a developer to work with JavaBeans in a convenient


way. By examining a JavaBean by a process known as Introspection, a builder
tool exposes the discovered features of the JavaBean for visual manipulation. A
builder tool maintains a list of all JavaBeans available. It allows you to compose
the Bean into applets, application, servlets and composite components (e.g. a
JFrame), customize its behavior and appearance by modifying its properties and
connect other components to the event of the Bean or vice versa.

Some Examples of Application Builder tools:

TOOL VENDOR DESCRIPTION Java


Java Workshop2.0 Sun Micro Systems., Inc. Complete IDE that
support applet,
application and bean
development.
Visual age for java IBM Bean Oriented visual
development toolset.
Jbuilder Borland Inc. Suit of bean oriented
java development tool.
Beans Development Kit Sun Micro Systems., Supports only Beans
Inc., development.

Q.5
a) Write a code to design login form (user name and password) and also
check valid user.

Ans :-

 import javax.swing.*;
 import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 public class LoginFrame extends JFrame implements ActionListener
 {
 Container container = getContentPane();
 JLabel userLabel = new JLabel("USERNAME");
 JLabel passwordLabel = new JLabel("PASSWORD");
 JTextField userTextField = new JTextField();
 JPasswordField passwordField = new JPasswordField();
 JButton loginButton = new JButton("LOGIN");
 JButton resetButton = new JButton("RESET");
 JCheckBox showPassword = new JCheckBox("Show Password");
 LoginFrame()
 {
 setLayoutManager();
 setLocationAndSize();
 addComponentsToContainer();
 addActionEvent();

 }
 public void setLayoutManager()
 {
 container.setLayout(null);
 }
 public void setLocationAndSize()
 {
 userLabel.setBounds(50, 150, 100, 30);
 passwordLabel.setBounds(50, 220, 100, 30);
 userTextField.setBounds(150, 150, 150, 30);
 passwordField.setBounds(150, 220, 150, 30);
 showPassword.setBounds(150, 250, 150, 30);
 loginButton.setBounds(50, 300, 100, 30);
 resetButton.setBounds(200, 300, 100, 30);
 }
 public void addComponentsToContainer()
 {
 container.add(userLabel);
 container.add(passwordLabel);
 container.add(userTextField);
 container.add(passwordField);
 container.add(showPassword);
 container.add(loginButton);
 container.add(resetButton);
 }

 public void addActionEvent()
 {
 loginButton.addActionListener(this);
 resetButton.addActionListener(this);
 showPassword.addActionListener(this);
 }
 @Override
 public void actionPerformed(ActionEvent e)
 {
 if (e.getSource() == loginButton)
 {
 String userText;
 String pwdText;
 userText = userTextField.getText();
 pwdText = passwordField.getText();
 if (userText.equalsIgnoreCase("Rajpardeshi") &&
pwdText.equalsIgnoreCase("2231"))
 {
 JOptionPane.showMessageDialog(this, "Login Successful");
 }
 Else
 {
 JOptionPane.showMessageDialog(this, "Invalid Username or
Password");
 }
 }
 if (e.getSource() == resetButton)
 {
 userTextField.setText("");
 passwordField.setText("");
 }
 if (e.getSource() == showPassword)
 {
 if (showPassword.isSelected())
 {
 passwordField.setEchoChar((char) 0);
 }
 Else
 {
 passwordField.setEchoChar('*');
 }

 }
 }
 }
 public class Login
 {
 public static void main(String[] a)
 {
 LoginFrame frame = new LoginFrame();
 frame.setTitle("Login Form");
 frame.setVisible(true);
 frame.setBounds(10, 10, 370, 600);
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setResizable(false);
 }
 }

b) For what purpose you will use JList and how ?

Ans :- JList A component that displays a list of objects and allows the user to
select one or more items. A separate model, ListModel , maintains the contents
of the list. A ListModel can be supplied directly to a JList by way of a constructor
or the setModel method.

The object of JList class represents a list of text items. The list of text items can
be set up so that the user can choose either one item or multiple items. It
inherits JComponent class.

Given below are the constructors explained :

 JList( ) : This Constructor in the JList class will create a List with a read-
only, empty, model.
 JList( Array[ ] list data ) : This Constructor in the JList class will create
a list that will display the elements from the array specified within the
parameter.
 JList( ListModel<Array> data model ) : This Constructor in the JList
class will create a list that will display the elements from the specified, no-
null, model.
 JList( Vector <?> list data ) : This Constructor in the JList class will
create a list that will display the elements from the vector specified within
the parameter.

Example :

 import javax.swing.*;
 public class ListExample
 {
 ListExample()
 {
 JFrame f= new JFrame();
 DefaultListModel<String> l1 = new DefaultListModel<>();
 l1.addElement("Item1");
 l1.addElement("Item2");
 l1.addElement("Item3");
 l1.addElement("Item4");
 JList<String> list = new JList<>(l1);
 list.setBounds(100,100, 75,75);
 f.add(list);
 f.setSize(400,400);
 f.setLayout(null);
 f.setVisible(true);
 }
 public static void main(String args[])
 {
 new ListExample();
 }
 }

Q.6 Solve any five of the following :


a) What is the purpose JSP ?

Ans :- The JSP engine compiles the servlet into an executable class and
forwards the original request to a servlet engine.

A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format.

b) What is session bean ?

Ans :- A session bean represents a single client inside the Application Server. To
access an application that is deployed on the server, the client invokes the
session bean's methods.

The session bean performs work for its client, shielding the client from
complexity by executing business tasks inside the server.

c) What is Request – response model ?

Ans :- In request/response communication mode, one software module sends a


request to a second software module and waits for a response.

Because the first software module performs the role of the client, and the
second, the role of the server, this mode is also referred to as client/server
interaction.

d) What is web . xml ?

Ans :- web. xml defines mappings between URL paths and the servlets that
handle requests with those paths.

The web server uses this configuration to identify the servlet to handle a given
request and call the class method that corresponds to the request method.

For example: the doGet() method for HTTP GET requests.

e) What is the use of import directives in jsp ?


Ans :- In JavaServer Pages (JSP), import directives are used to import Java
packages or classes into a JSP page. The import directive is similar to the import
statement in regular Java programming and serves the same purpose.

Q.7
a) Describe servlet life cycle.

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


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After
invoking the init() method, Servlet comes in the ready state. In the ready state,
servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.

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

The web container calls the init method only once after creating the servlet instance. Th
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Se
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()

b) Differentiate between forward and sendRedirect method of Request


Dispatcher.

Ans :-

Forward() SendRedirect()

forward() is method of sendRedirect() is the method of


RequestDispatcher interface HttpServletResponse In forward().
In forward() redirect happens at In sendRedirect() ,redirection happens
server end and not visible to client. at client end and it’s visible to client.
It is faster than the redirect. It is slower than a forward, since it
requires two browser requests(one for
actual request and another for
redirected request ).
In case of forwarding() original URL In the case of sendRedirect() browser
remains unaffected. knows that it’s making a new request,
so the original URL changes.
Transfer the request to the same Transfer the request different server.
server
When forward is called on In the case of SendRedirect call old
RequestDispather object we pass request and response, the object is
request and response object so our lost because it’s treated as a new
old request object is present on a new request by the browser.
resource which is going to process our
request
Syntax: forward(ServletRequest Syntax: void sendRedirect(String url)
request, ServletResponse response)

Q.8
a) Explain Custom tags of JSP.

Ans :- Custom tags are user-defined action tags that can be used within Java
Server Pages. A tag handler is associated with each tag to implement the
operations.

Therefore, it separates the business logic from JSP and helps avoid the use of
scriptlet tags.

The scriptlet tag embeds java code inside the JSP page itself rendering the page
difficult to understand therefore, it is better to avoid the use of scriptlet.

Syntax to use custom tag :

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

empty custom tag(without body) :

• <prefix : suffix attribute = "value"/>

Non-empty custom tag :

• <prefix : suffix attribute = "value">body</prefix : suffix>

THE FOLLOWING THREE COMPONENTS ARE REQUIRED TO DEVELOP CUSTOM TAGS :

1. Tag Handler :

It is a container-managed object created by a JSP container at runtime. A Java


class is used to implement the processing logic for the tag. It may contain
certain properties corresponding to the attributes or body of the tag. All tag
handlers have a pageContext property for the JSP page where the tag is located,
and a parent property for the tag handler to the closest enclosing parent tag. It
must implement/extend one of the following interfaces/classes present in
javax.servlet.jsp.tagext package.
 Tag Interface : Tag interface can be implemented by a tag handler to
provide the processing logic if the body of the tag is not required to be
evaluated.
 IterationTag Interface : IterationTag interface can be implemented if
the body of the tag needs to be repeated a certain number of times.
 TagSupport class : It is a base class that implements Tag and
IterationTag interfaces. It can be used to implement a tag handler in case
implementation for all the methods is not required. It provides the default
implementation of all the abstract methods of its parent interfaces.
 BodyTag Interface : BodyTag interface can be implemented by a tag
handler if the body of the tag is to be evaluated.
 BodyTagSupport class : It is a base class that implements BodyTag
class and extends TagSupport class. It provides the default
implementation of its parent interfaces.
 SimpleTag Interface : A tag handler can implement the SimpleTag
interface in order to provide the processing logic. It consists of a much
simpler lifecycle as compared to classic tag handlers.
 SimpleTagSupport class : It is a base class of the SimpleTag interface.
It can be extended to provide the handler code. From the above
discussion, it can be concluded that a tag handler must implement one of
the following interfaces: Tag, IterationTag, SimpleTag or extend any of the
following classes: TagSupport, BodyTagSupport, SimpleTagSupport to
provide the processing logic for the tag.

2. TLD(Tag Library Descriptor) :

It is a file saved with a .tld extension that contains a set of related tags mapped
to their respective tag handlers along with their description such as the name of
the tag, attributes of the tag, etc. The root tag of the TLD document is <taglib>
in which multiple tags can be encapsulated using <tag> tag. It is stored inside
the WEB-INF folder.
3. Taglib Directive :

Taglib directive is used to access a particular tag library within a JSP. It specifies
the URI of the tag library and its prefix.

Syntax:

<%@taglib uri=" " prefix=" "%>

b) How to create session in JSP? How to access it? Write a sample code.

Ans :- In any normal website, the user performs multiple interactions on


different pages of the site. It is beneficial for the site to customize the data
according to each user. This allows the user to maintain a personal space for
their specific activities according to their interests.

For all these purposes, the JSP provides the "session implicit object". In this
chapter, you will learn about various methods and concepts used to create and
manage a session using JSP.

A session can be defined as an object associated with each user with a unique
session ID, and the user's data is based on the account they have registered.
Different forms of data can be set in a session;

These data related to each user of the site help the user and the website owner
in different ways. As you know, HTTP is a "stateless" protocol; Whenever a user
visits a web page, the user opens a separate connection with the webserver, and
the server does not keep a record of preceding client requests.

1. Creating a Session :
 Implicitly : A session is created automatically when a user accesses a
JSP page for the first time.
 Explicitly : Use the HttpSession object in a servlet or JSP page :
HttpSession session = request.getSession();

2. Setting Session Attributes :


 Store data in the session using setAttribute() :
session.setAttribute("username", "Rajpardeshi");
session.setAttribute("userID", 2231);

3. Accessing Session Attributes :


 Retrieve data using getAttribute() :
String username = (String) session.getAttribute("username");
int userID = (int) session.getAttribute("userID");

4. Sample Code (JSP) :


 <%@ page import="javax.servlet.http.HttpSession" %>
 <%
 HttpSession session = request.getSession();
 String username = (String) session.getAttribute("username");
 int userID = (int) session.getAttribute("userID");
 if (username == null) {
 session.setAttribute("username", "Rajpardeshi");
 session.setAttribute("userID", 2231);
 username = (String) session.getAttribute("username"); // Retrieve again
for display
 }
 %>
 <h2>Welcome, <%= username %>!</h2>
 <h3>Your user ID is: <%= userID %></h3>

Q.9
a) Design a login form. Write a servlet to retrieve form values an display
whether user is valid or not.

Ans :-

 Login Form (index.jsp) :


 <form action="LoginServlet" method="post">
 <label for="username">Username:</label>
 <input type="text" id="username" name="username"><br><br>
 <label for="password">Password:</label>
 <input type="password" id="password" name="password"><br><br>
 <input type="submit" value="Login">
 </form>
 Login Servlet (LoginServlet.java) :
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.io.*;
 public class LoginServlet extends HttpServlet
 {
 @Override
 protected void doPost(HttpServletRequest request,
HttpServletResponse response)
 throws ServletException, IOException
 {
 String username = request.getParameter("username");
 String password = request.getParameter("password");
 boolean isValidUser = username.equals("admin") &&
password.equals("password123");
 HttpSession session = request.getSession();
 if (isValidUser)
 {
 session.setAttribute("username", username);
 response.sendRedirect("welcome.jsp");
 }
 else
 {
 response.sendRedirect("login_error.jsp");
 }
 }
 }
 Welcome Page (welcome.jsp) :
 <h2>Welcome, <%= session.getAttribute("username") %>!</h2>
 Error Page (login_error.jsp):
 <h2>Invalid username or password.</h2>
 <a href="index.jsp">Try again</a>

b) Explain request and response implicit objects of JSP with any its two
methods.

Ans :-

 Request :
o The request object is an instance of java.servlet.http.HttpServletRequest
and it is one of the argument of service method.
o It will be created by container for every request.
o It will be used to request the information like parameter, header
information , server name, etc.
o It uses getParameter() to access the request parameter.
o The request object provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc.
o We can cover a complete set of methods associated with the request
object in a subsequent chapter − JSP - Client Request.
 Commonly used methods :
o getParameter(String name) : Retrieves the value of a form parameter
or query string parameter.
Example: String userName = request.getParameter("username");
o getHeader(String name) : Retrieves the value of an HTTP header.
Example: String userAgent = request.getHeader("User-Agent");

 Response :
o “Response” is an instance of class which implements HttpServletResponse
interface.
o Container generates this object and passes to _jspservice() method as
parameter.
o “Response object” will be created by the container for each request.
o It represents the response that can be given to the client.
o The response implicit object is used to content type, add cookie and
redirect to response page.
o 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.
o We will cover a complete set of methods associated with the response
object in a subsequent chapter − JSP - Server Response.
 Commonly used methods :
o setContentType(String type) : Sets the content type of the response
(e.g., "text/html", "application/json").
Example: response.setContentType("text/html");
o sendRedirect(String url) : Redirects the client to another URL.
Example: response.sendRedirect("welcome.jsp");

Q.10
a) Explain the life cycle of enterprise bean.

Ans :-
 The Life Cycles of Enterprise Beans : An enterprise bean goes through
various stages during its lifetime, or life cycle. Each type of enterprise
bean--session, entity, or message-driven--has a different life cycle.

1. The Life Cycle of a Stateful Session Bean :

The stages that a session bean passes through during its lifetime. The client
initiates the life cycle by invoking the create method. The EJB container
instantiates the bean and then invokes.

The setSessionContext and ejbCreate methods in the session bean. The bean is
now ready to have its business methods invoked.

2. The Life Cycle of an Entity Bean :

The stages that an entity bean passes through during its lifetime. After the EJB
container creates the instance, it calls the setEntityContext method of the entity
bean class. The setEntityContext method passes the entity context to the bean.

After instantiation, the entity bean moves to a pool of available instances. While
in the pooled stage, the instance is not associated with any particular EJB object
identity. All instances in the pool are identical. The EJB container assigns an
identity to an instance when moving it to the ready stage.
3. The Life Cycle of a Message-Driven Bean :

He EJB container usually creates a pool of message-driven bean instances. For


each instance, the EJB container instantiates the bean and performs these tasks:

o It calls the setMessageDrivenContext method to pass the context object to


the instance.
o It calls the instance's ejbCreate method.

Like a stateless session bean, a message-driven bean is never passivated, and it


has only two states: nonexistent and ready to receive messages.

At the end of the life cycle, the container calls the ejbRemove method. The
bean's instance is then ready for garbage collection.

b) Explain message driven beans.

Ans :-
Message Driven Bean :

A message driven bean (MDB) is a bean that contains business logic. But, it is
invoked by passing the message. So, it is like JMS Receiver.

MDB asynchronously receives the message and processes it.

A message driven bean receives message from queue or topic, so you must have
the knowledge of JMS API.

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 Bean Example :

To create the message driven bean, you need to declare @MessageDriven


annotation and implement MessageListener interface.

In eclipse ide, create EJB Project then create a class as given below:

 package com.javatpoint;
 import javax.ejb.MessageDriven;
 import javax.jms.*;
 @MessageDriven(mappedName="myTopic")
 public class MyListener implements MessageListener{
 @Override
 public void onMessage(Message msg) {
 TextMessage m=(TextMessage)msg;
 try{
 System.out.println("message received: "+m.getText());
 }catch(Exception e){System.out.println(e);}
 }
 }

You might also like