0% found this document useful (0 votes)
69 views23 pages

Model Answer AJ

The document provides answers to questions related to advanced Java concepts. It includes definitions of JApplet, port, scrollpane, InetAddress, Java bean, and BDK. It also describes two layout managers - BorderLayout and FlowLayout - with examples. The document provides code to implement a GUI for a factorial application. It discusses the roles of stub and skeleton in RMI and outlines the steps to implement an RMI application. Finally, it provides code to implement an online chat application using TCP/IP.

Uploaded by

jjkk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views23 pages

Model Answer AJ

The document provides answers to questions related to advanced Java concepts. It includes definitions of JApplet, port, scrollpane, InetAddress, Java bean, and BDK. It also describes two layout managers - BorderLayout and FlowLayout - with examples. The document provides code to implement a GUI for a factorial application. It discusses the roles of stub and skeleton in RMI and outlines the steps to implement an RMI application. Finally, it provides code to implement an online chat application using TCP/IP.

Uploaded by

jjkk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Model Answer

Advanced JAVA
Q.1 Solve any five :
a) What is JApplet?

Ans :- JApplet is a simple extension of java. applet. Applet to use when creating
Swing programs designed to be used in a web browser (or appletviewer ).

As a direct subclass of Applet , JApplet is used in much the same way, with the
init( ) , start( ) , and stop( ) methods still playing critical roles.

b) Define Port.

Ans :- The port number is used to uniquely identify different applications. It acts
as a communication endpoint between applications.

The port number is associated with the IP address for communication between
two applications.

c) What is the use of scrollpane?

Ans :- A JScrollPane provides a scrollable view of a component. When screen


real estate is limited, use a scroll pane to display a component that is large or
one whose size can change dynamically.

Other containers used to save screen space include split panes and tabbed
panes.

d) Define lnet address.

Ans :- InetAddress class is Java's encapsulation of an IP address. It is used by


most of the other networking classes, including Socket , ServerSocket , URL ,
DatagramSocket , DatagramPacket , and more.

This class represents an Internet address as two fields: hostName (a String )


and address (an int ).

e) What is the use of java bean?

Ans :- According to Java white paper, it is a reusable software component. A


bean encapsulates many objects into one object so that we can access this
object from multiple places. Moreover, it provides easy maintenance.
It implements the Serializable interface, has a public no-argument constructor,
and provides getter and setter methods for its properties name and age . The
advantages of using Java Beans include code reusability, encapsulation of logic,
and easy interaction with other components.

f) What is BDK ?

Ans :- The BDK for Java is Symphony's preferred tooling for Java developers to
build bots. It is a library of tools and API bindings that provides simplified
configuration and authentication, intuitive message and room management,
customizable message templating and an activities API that makes it easy to
build bot workflows.

The Beans Development Kit (BDK) includes example beans and the BeanBox
tool. The BDK is optional; you can create beans without it. However, the
BeanBox tool is extremely useful and is used throughout this book.

Q.2
a) Describe any two layout manager with an example.

Ans :-
1. Border Layout :
This layout will display the components along the border of the container. This
layout contains five locations where the component can be displayed. Locations
are North, South, East, west, and Center. The default region is the center. The
above regions are the predefined static constants belonging to the BorderLayout
class.

Whenever other regions’ spaces are not in use, automatically container is


selected as a center region default, and the component occupies the surrounding
region’s spaces of the window, which damages the look and feel of the user
interface.

Example :

 import java.awt.*;
 public class BorderLayoutDemo
 {
 public static void main (String[]args)
 {
 Frame f1 = new Frame ();
 f1.setSize (250, 250);
 Button b1 = new Button ("Button1");
 Button b2 = new Button ("Button2");
 Button b3 = new Button ("Button3");
 Button b4 = new Button ("Button4");
 Button b5 = new Button ("Button5");
 f1.add (b1, BorderLayout.NORTH);
 f1.add (b2, BorderLayout.EAST);
 f1.add (b3, BorderLayout.WEST);
 f1.add (b4, BorderLayout.SOUTH);
 f1.add (b5);
 f1.setVisible (true);
 }
 }

2. Flow Layout :

This layout will display the components from left to right, from top to bottom.
The components will always be displayed in the first line and if the first line is
filled, these components are displayed on the next line automatically.

In this Layout Manager, initially, the container assumes 1 row and 1 column of
the window. Depending on the number of components and size of the window,
the number of rows and columns count is decided dynamically.

Example :

 import java.awt.*;
 import javax.swing.*;
 public class FlowLayoutDemo
 {
 JFrame f;
 FlowLayoutDemo ()
 {
 f = new JFrame ();
 JLabel l1 = new JLabel ("Enter Name");
 JTextField tf1 = new JTextField (10);
 JButton b1 = new JButton ("SUBMIT");
 f .add (l1);
 f.add (tf1);
 f.add (b1);
 f.setLayout (new FlowLayout (FlowLayout.RIGHT));
 f.setSize (300, 300);
 f.setVisible (true);
 }
 public static void main (String[]args)
 {
 new FlowLayoutDemo ();
 }
 }
b) Design GUI for factorial application and display factorial of given
number.

Ans :-

 import javax.swing.JOptionPane;
 public class mainclass
 {
 public static void main(String[] args)
 {
 String number;
 int result,inputNumber;
 number = JOptionPane.showInputDialog("enter a number");
 inputNumber = Integer.parseInt(number);
 result = computeFactorial(inputNumber);
 JOptionPane.showMessageDialog(null, "the factorial is :" + result);
 }
 public static int computeFactorial(int n)
 {
 int i;
 int result = 1;
 for (i = 1; i <= n; i++)
 {
 result = result * i;
 }
 return result;
 }
 }

Q.3
a) What is the role of stub and skeleton in RMI? What are the steps to
implement RMI application ?

Ans :-

Stub :

The stub is an object, acting on the client side as a gateway. It routes all the
outgoing applications. It lies on the side of the client and represents the object
remote. When calling technique on the stub item, the caller performs the
following duties :

 It initiates a remote virtual machine (JVM) link/connection.


 The parameters are written and transmitted (marshals) to the remote
Virtual Machine (JVM) by it.
 It is waiting for the outcome/result.
 It reads the return value or exception (unmarshals) and
 At the end, it returns the value/response to the caller.
Skeleton :

The skeleton is an object that acts as a gateway to the side object of the server.
It routes all incoming requests through it. When the incoming request is received
by the skeleton, the following tasks are performed:

 It reads the remote method parameter


 It executes/invokes the method on the actual remote object.
 It writes and transmits the result to the caller (marshals).

The 6 - six steps to write the RMI program in java :

1. First Define the java remote interface :

First thing to do is create an interface to describe the techniques that can be


invoked by distant clients. This interface should extend the Remote interface and
throw the RemoteException inside the interface using the method prototype.

2. Implement the java remote interface :

The next step is to implement the remote interface. To execute the remote
interface, the class should extend to the UnicastRemoteObject class java.rmi
package. In addition, a default constructor must be formed to transfer the
java.rmi.RemoteException from its class parent constructor.

3. Writing Stub and Skeleton objects from the implementation class


using rmic :

The rmic instrument is used to invoke the rmi compiler which produces the Stub
and Skeleton items. His prototype is the rmic class's name. For the above
program, the following command must be executed at the rmicSearchQuery
command prompt.

4. Start/Invoke the rmiregistry :

Start the service of the registry by putting the following command on the prompt
of start rmiregistry.

5. Write and execute the server application program :

The next step is the development and execution on a separate command prompt
of the server application program.
 The server program uses the creation technique of the LocateRegistry
class to produce rmiregistry with the passed port number as the argument
within the JVM server.
 The Naming class rebind method is used to bind the remote object to the
new name.
6. Write and execute the client application program :

The last stage is to generate and implement the client application program on a
distinct command prompt. The Naming class lookup method is used to get the
Stub object reference.

b) Write a code to implement online chat application using TCP/IP.

Ans :-

Chatserver.java :

 import java.net.*;
 import java.io.*;
 public class chatserver
 {
 public static void main(String args[]) throws Exception
 {
 ServerSocket ss=new ServerSocket(2000);
 Socket sk=ss.accept();
 BufferedReader cin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
 PrintStream cout=new PrintStream(sk.getOutputStream());
 BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
 String s;
 while ( true )
 {
 s=cin.readLine();
 if (s.equalsIgnoreCase("END"))
 {
 cout.println("BYE");
 break;
 }
 System.out.print("Client : "+s+"\n");
 System.out.print("Server : ");
 s=stdin.readLine();
 cout.println(s);
 }
 ss.close();
 sk.close();
 cin.close();
 cout.close();
 stdin.close();
 }
 }

Chatclient.java :

 import java.net.*;
 import java.io.*;
 public class chatclient
 {
 public static void main(String args[]) throws Exception
 {
 Socket sk=new Socket("127.0.0.1",2000);
 BufferedReader sin=new BufferedReader(new
InputStreamReader(sk.getInputStream()));
 PrintStream sout=new PrintStream(sk.getOutputStream());
 BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
 String s;
 while ( true )
 {
 System.out.print("Client : ");
 s=stdin.readLine();
 sout.println(s);
 s=sin.readLine();
 System.out.print("Server : "+s+"\n");
 if ( s.equalsIgnoreCase("BYE") ) break;
 }
 sk.close();
 sin.close();
 sout.close();
 stdin.close();
 }
 }

Q.4
a) Explain property change event with an example.

Ans :- A "PropertyChange" event gets delivered whenever a bean changes a


"bound" or "constrained" property. A PropertyChangeEvent object is sent as an
argument to the PropertyChangeListener and VetoableChangeListener methods.

Normally PropertyChangeEvents are accompanied by the name and the old and
new value of the changed property. If the new value is a primitive type (such as
int or boolean) it must be wrapped as the corresponding java.lang.* Object type
(such as Integer or Boolean).

Null values may be provided for the old and the new values if their true values
are not known.
An event source may send a null object as the name to indicate that an arbitrary
set of if its properties have changed. In this case the old and new values should
also be null.

Example :

 import javafx.beans.property.SimpleStringProperty;
 import javafx.beans.property.StringProperty;
 import javafx.beans.value.ChangeListener;

 public class Person

 {
 private StringProperty name = new SimpleStringProperty();
 public Person(String name)
 {
 this.name.set(name);
 this.name.addListener((observable, oldValue, newValue) ->
 {
 System.out.println("Name changed from " + oldValue + " to " +
newValue);
 });
 }
 public String getName()
 {
 return name.get();
 }
 public void setName(String name)
 {
 this.name.set(name);
 }
 public StringProperty nameProperty()
 {
 return name;
 }
 public static void main(String[] args)
 {
 Person person = new Person("John");
 person.setName("Jane");
 }
 }

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