0% found this document useful (0 votes)
4 views16 pages

AdvJava IMP

The document explains various concepts related to Java GUI programming, including Layout Managers like BorderLayout, the Event Delegation Model for handling events, and components such as TextField and TextArea in AWT. It also covers the class hierarchy of AWT controls, the MVC architecture of Swing, features of Java Foundation Classes (JFC), and Swing UI control elements. Additionally, it describes marshalling and unmarshalling in remote method invocation (RMI), along with the roles of stub and skeleton in client-server communication.

Uploaded by

malikrayyan313
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)
4 views16 pages

AdvJava IMP

The document explains various concepts related to Java GUI programming, including Layout Managers like BorderLayout, the Event Delegation Model for handling events, and components such as TextField and TextArea in AWT. It also covers the class hierarchy of AWT controls, the MVC architecture of Swing, features of Java Foundation Classes (JFC), and Swing UI control elements. Additionally, it describes marshalling and unmarshalling in remote method invocation (RMI), along with the roles of stub and skeleton in client-server communication.

Uploaded by

malikrayyan313
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/ 16

Q1. What is Layout Manager? Explain any one in detail with example.

ANS:- The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout managers. There are
the following classes that represent the layout managers: one of this is
Java BorderLayout:-The BorderLayout is used to arrange the components in five regions: north,
south, east, west, and center. Each region (area) may contain one component only. It is the default
layout of a frame or window. The BorderLayout provides five constants for each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:BorderLayout(): creates a border layout but with no gaps
between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border() {
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true); }
public static void main(String[] args) {
new Border();
}}
Output:
Q2. Explain Event Delegation Model.
ANS:- The Event Delegation model is a design pattern used in event handling to manage and
handle events in a more efficient and centralized way. It is often applied in graphical user
interface (GUI) programming, where numerous components may generate events. Instead of
each component directly handling its own events, the Event Delegation model introduces a
mediator (event listener) that manages and dispatches events to appropriate handlers.

Key concepts of the Event Delegation model:


Event Source: The component that generates an event is called the event source. This could be a
button, checkbox, text field, etc.
Event Listener (Delegator): The event listener (delegator) is a centralized object that listens for
events from multiple sources. It is responsible for dispatching events to appropriate handlers.
Event Handling Methods: Event handling methods are implemented in separate classes (handlers)
that are specific to the type of event. The event listener determines which handler to invoke based
on the type of the event.

Q3 Explain TextField and TextArea in AWT.


ANS:- The TextField class in Java AWT is a GUI component in the ‘java.awt’ package. It allows the
user to enter a single line of text as an input. It is a simple way to collect text-based information from
the user. You can use the TextField component to create various input fields for username,
password, search boxes, etc.Whenever a key is pressed or typed into the input field, an event is sent
to the TextField. The registered KeyListener then receives the KeyEvent. ActionEvent can also be
used for this purpose. If the ActionEvent is configured on the text field, then it will be triggered when
the Return key is pressed. The ActionListener interface handles the event.
Syntax of Java AWT TextField:- public class TextField extends TextComponent
Textarea:-The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps us to scroll
the text up and down, or right and left. The object of a TextArea class is a multiline region that
displays text. It allows the editing of multiple line text. It inherits TextComponent class.
Syntax of Java AWT TextField:- public class TextArea extends TextComponent
Fields of TextArea Class:-The fields of java.awt.TextArea class are as follows:
static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical scrollbars.
static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the horizontal scrollbar.
static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical scrollbar.
static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text area.
Q4.Describe class hierarchy of AWT Controls in detail.
ANS:- The hierarchy of Java AWT classes are given below.

Components:-All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a container.
Container:-The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as Frame,
Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations. Thus it
contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
Window:-The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel:-The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc. An
instance of Panel class creates a container, in which we can add components.
Frame:-The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used container
while developing an AWT application.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this component.
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
public void setVisible(boolean status) Changes the visibility of the component, by default
false.
Q5. Describe MVC architecture of Swing in detail.
ANS:- The model-view-controller (MVC) architecture serves as the foundation for all of Swing’s
component designs. MVC divides GUI components into three main parts. Every one of these
components is essential to the way the component functions. In MVC terminology
• Model corresponds to the state information associated with the component (data). For
example, in case of a check box, the model contains a field that indicates if the box is
checked or unchecked.
• The view visual appearance of the component based upon model data.
• The controller acts as an interface between view and model. It intercepts all the requests i.e.
receives input and commands to Model / View to change accordingly.

In reality, Swing uses a condensed version of model-delegate architecture for MVC. The
approach integrates the view and the controller object into a single component, the UI
delegate, which manages GUI events and draws the component the screen. Since Swing
handles a large portion of the event management, it is relatively simple to combine graphical
capabilities with the event processing in Java. The model and UI delegate can then
communicate with each other in both directions, as you might anticipate.
➢ MVC advantages
• It facilitates the concurrent creation of software by multiple teams; some may focus on
the model, while others may work on the view.
• They simply need to make a choice prior to model interface.
• It makes software maintenance easier since we can modify the view without having to
rebuild the model. It also permits several views on a single model.
Swing Feature
• Swing is Lightweight compared to AWT.
• Pluggable Look and Feel: This feature allow the user to change the Swing components’
appearance and feel without having to restart an application.
• Sophisticated features like JScollPane, JTable, JTabbedPane,etc.
• An application’s GUI built using Swing components is unaffected by GUI’s ownership and
delivery by a platform-specific operating system.
• Swing controls can be customized in a very easy way as visual appearance is
independent of internal representation.
• Rich controls- Swing provides a rich set of advanced controls like Tree TabbedJPane,
slider, colorpicker, and table controls.
• Uses MVC architecture.
• Platform Independent.
Q6. What are the different features of JFC? Explain.
Ans:- JFC stands for Java Foundation Classes. It is a rich and comprehensive set of GUI components
and services that simplify the development and deployment of desktop, client-side, and internet
applications. It is a superset that contains AWT. JFC extends AWT by adding many components and
services that are as follows:
API/ Feature Description
Swing GUI It includes everything from buttons to split panes to tables. Many components are capable of sorting,
Components printing, and drag and drop, to name a few of the supported features.
Pluggable The look and feel of Swing applications is pluggable, allowing a choice of look and feel. For example, the
Look-and- same program can use either the Java or the Windows look and feel. Additionally, the Java platform
Feel Support supports the GTK + look and feel, which makes hundreds of existing looks and feels available to Swing
programs. Many more look-and-feel packages are available from various sources.
Accessibility It is a part of JFC that works with alternate input and output devices. It enables assistive technologies,
API such as screen readers, screen magnifiers, and Braille terminals, to get information from the UI.
Java 2D API It enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and
applets. Java 2D includes extensive APIs for generating and sending high-quality output to printing
devices.
International It allows developers to build applications that can interact with users worldwide in their own languages
ization and cultural conventions. With the input method framework, developers can build applications that
accept text in languages that use thousands of different characters, such as Japanese, Chinese, or Korean.
Drag and Drag and Drop is one of the more common metaphors used in GUI. The user is allowed to click and "hold"
Drop (DnD) a GUI object, moving it to another window or frame in the desktop with predictable results. It allows
users to implement droppable elements that transfer information between Java applications and native
applications. Although DnD is not part of Swing, it is crucial to a commercial-quality application.

Q7. Explain Swing Class hierarchy.


Class Description
Component An abstract base class that defines any object that can be displayed.
Container An abstract class that defines any component that can contain other
components.
Window The AWT class that defines a window without a title bar or border.
Frame The AWT class that defines a window with a titlebar or border.
JFrame The Swing class that defines a window with a titlebar or border.
JComponent A base class for Swing components such as JPanel, JButton, JLabel, and
JTextField.
JPanel The Swing class that defines a panel, which is used to hold other
components.
JLabel The Swing class that defines a Label.
JTextField The Swing class that defines a textfield.
JButton The Swing class that defines a button.

Fig: Swing Class Hierarchy


Q8. Explain Swing UI Control Elements.
ANS:- Swing UI Control Elements are as follows.
i.JLabel Class:- JLabel is used to insert text into a container. It is read-only content. An application
has the ability to alter the text; a user cannot edit-it directly. It is inherited from JComponent class.
Syntax:- public class JLabel extends JComponent implements SwingConstants,Accessible
ii. JButton Class:- You can create a platform-independent labeled button with the JButton class.
Pressing the button causes the application to perform some action. The AbstractButton class is
inherited by it. Syntax:- public class JButton extends AbstractButton implements Accessible
iii. JComboBox:- The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of menu. It inherits JComponent class. Syntax:- public class JComboBox
extends JComponent implements ItemSelectable, ListDataListeer, ActionListner, Accessible
iv. JTextField Class:- JTextField class allows user to pass single line input which you may the edit. It
inherits JTextComponent class.
Syntax:- public class JTextField extends JTextComponent implements SwingConstant
v. JTextArea Class:- The object of a JTextArea class is multiline region that displays text. It allows
editing of multiple line text. It inherits JTextComponent class.
Syntax:- public class JTextArea extends JTextComponent
vi. JpasswordField Class:- JpasswordField inherits properties of JTextField class and it specialized for
password entry, In this enter character are encrypted.
Syntax:-public class JpasswordField extends JTextField
vii. JcheckBox Class:- The JcheckBox class is used to create a checkbox which allows user to select
part or all options from given choice list. Clicking on a CheckBox changes its state from “on” to “off”
or from “off” to “on”. It inherits JToggleButton class.
Syntax:- public class JCheckBox extends JToggleButton implements Accessible
viii. JRadioButton Class:- The JRadioButton Class is used to create a radio button which allows
choosing one option from multiple options. It should be added in ButtonGroup to select one radio
button only. Syntax:- public class JRadioButton extends JToggleButton implements Accessible
ix. JSlider Class:- The Java JSlider class is used to create the slider which to let users adjust a numeric
value between minimum and maximum values. By using JSlider, a user can select a value from a
specific range.
x. JTabbedPane Class:- It provides flexibility to user to switch between different groups of
components desires to see, by simply clicking on one of the tabs It inherits JComponent class.
Syntax:- public class JTabbedPane extends JComponent implements Serializable, Accessible,
SwingConstants
xi. JTree Class:- The JTree class is used to display tree structured data or hierarchical data. JTree is a
complex component. It has a ‘root node’ at the top most which is a parent for all nodes in the tree. It
inherits JComponent class. Syntax:- public class JTree extends JComponent implements Scrollable,
Accessible
xii. JTable Class:- The JTable class is used to display data in tabular format. It is composed of rows
and columns.
xiii. JToggleButton Class:- JToggleButton is two state button. It has two-states i.e. either on or off.

Q9. Explain the following terms :


a. Marshalling:- Whenever a client invokes a method that accepts parameters on a remote object,
the parameters are bundled into a message before being sent over the network. These
parameters may be of primitive type or objects. In case of primitive type, the parameters are put
together and a header is attached to it. In case the parameters are objects, then they are
serialized. This process is known as marshalling
b. Unmarshalling:- At the server side, packed parameters are unbundled and then required method
is invoked.(When client-side RRL receives request, it invokes a method called invoke() of object
remoteRef) This process is known as unmarshalling.
Q10. Explain the term stub and skeleton in detail.
ANS:- RMI uses stub and skeleton object for communication with the remote object. A remote
object is an object whose method can be invoked from another JVM.

STUB:- The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When caller invokes
method on stub object, it does following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshallls) the parameters to remote Virtual Machine (JVM)
3. It waits for result.
4. It reads (unmarshals) return value or exception, and
5. It finally returns the value to caller.

SKELETON:- The skeleton is an object, acts as a gateway for server-side object. All incoming requests
are routed through it. When skeleton receives incoming request, it does following tasks:
1. It reads parameter for remote method.
2. It invokes method on actual remote object, and
3. It writes and transmits (marshalls) result to caller.
4.
Q11. Explain networking basic terminologies.
ANS:- Networking Basic Terminologies
Q12 . Explain Java Networking Classes and Interfaces.

ANS:- Java Networking Classes :-

Java Networking Interfaces:-


Q13. Explain the role of the ResultSet interface in JDBC and provide an example of its usage.
ANS:- The object of ResultSet maintain a cursor pointing to a row of a table. Initially, cursor points to
before the first row.By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well
as we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
1) public boolean next(): is used to move the cursor to the one row next from
the current position.
2) public boolean previous(): is used to move the cursor to the one row previous
from the current position.
3) public boolean first(): is used to move the cursor to the first row in result
set object.
4) public boolean last(): is used to move the cursor to the last row in result
set object.
5) public boolean absolute(int row): is used to move the cursor to the specified row
number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative row
number in the ResultSet object, it may be positive
or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column index
of the current row as int.
8) public int getInt(String columnName): is used to return the data of specified column name
of the current row as int.
9) public String getString(int columnIndex): is used to return the data of specified column index
of the current row as String.
10) public String getString(String is used to return the data of specified column name
columnName): of the current row as String.

Example of Scrollable ResultSet


Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");

//getting the record of 3rd row


rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}
Q14. What is the difference between Statement and PreparedStatement interface.
1. Statement :
It is used for accessing your database. Statement interface cannot accept parameters and useful
when you are using static SQL statements at runtime. If you want to run SQL query only once then
this interface is preferred over PreparedStatement.
Example –
//Creating The Statement Object
Statement prep_statement = con.createStatement();
//Executing The Statement
prep_statement.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL, NAME
VARCHAR)");
2. PreparedStatement :
It is used when you want to use SQL statements many times. The PreparedStatement interface
accepts input parameters at runtime.
Example –
//Creating the PreparedStatement object
PreparedStatement prep_statement = con.prepareStatement("update STUDENT set NAME = ?
where ID = ?");
//Setting values to place holders
//Assigns "RAM" to first place holder
prep_statement.setString(1, "RAM");

//Assigns "512" to second place holder


prep_statement.setInt(2, 512);

//Executing PreparedStatement
prep_statement.executeUpdate();
Difference between Statement and PreparedStatement :

Statement PreparedStatement
It is used when SQL query is to be executed It is used when SQL query is to be executed
only once. multiple times
.You can not pass parameters at runtime. You can pass parameters at runtime.
Used for CREATE, ALTER, DROP statements. Used for the queries which are to be executed
multiple times.
Performance is very low. Performance is better than Statement.
It is base interface. It extends statement interface.
Used to execute normal SQL queries. Used to execute dynamic SQL queries.
We can not use statement for reading binary We can use Preparedstatement for reading
data. binary data.
It is used for DDL statements. It is used for any SQL Query.
We can not use statement for writing binary We can use Preparedstatement for writing
data. binary data.
No binary protocol is used for communication. Binary protocol is used for communication.
Q15. What are jdbc statements explain its types.
ANS:- Java Database Connectivity basically is an application programming interface(API) for Java.
This helps in connecting and executing a query with the database. Thus, it helps us in defining how a
client accesses the database. This can be classified as a Java-based data access technology for
connecting to a Database.
When using JDBC, we will come across several other statements that basically define how we will be
accessing the database and up to which level of access. In this blog, we will learn about the different
types of statements in JDBC and how we can use them as an API to the database.
JDBC is used to create SQL statements in Java by providing methods to execute queries with the
database. Thus, JDBC works as an API for Java-Based Programs. JDBC also provides universal data
access from the Java programming language. These interfaces also define the methods that are
generally known to assist the bridge data type differences that exist between Java and SQL data
types basically used in a database.
There are basically three types of statements in JDBC: Create statements, Prepared statements,
Callable statements.
1.Create statement:- This is usually used when we want a general-purpose access to the database
and can be very helpful when running static SQL statements in the runtime.
Syntax:- Statement statement = connection.createStatement();
Example
Statement statement = con.createStatement();
String sql = "select * from orders";
ResultSet result = statement.executeQuery(sql);
You can also try this code with Online Java Compiler
Run Code
2.Prepared statement
These types of statements basically represent recompiled SQL statements that can be executed
many times. Thus, instead of having actual parameters in the SQL Queries it has “?” in place of the
parameters to be passed dynamically by using the methods of prepared statements at the run time.
Syntax:- String query = "INSERT INTO ORDERS(id, product) VALUES(?,?)";
` Statement test = connection.createStatement();
test.setInt(1, 45);
test.setString(2, "Pen");
Example
PreparedStatement test = con.prepareStatement("
SELECT product FROM ORDERS WHERE ID = ?");
test.setInt(1,45);
ResultSet result = test.executeQuery();
3.Callable statement
In some cases we need to work with multiple databases for some task and the scenario becomes
very complex here. Thus, rather than sending multiple queries we can simply send the required data
to the stored procedure. This will decrease the load on the database significantly. This is where
callable statements work as the stored procedures which are essentially a group of statements that
we compile in the database and are very beneficial.
Syntax:-CallableStatement cs = con.prepareCall("{call procedure_name(?,?)}")
Example
CallableStatement test = con.prepareCall("{call orderinfo(?,?)}");
test.setInt(1, 45);
test.setString(2, "Pen");
Q16. Write steps to Create Servlet Application using tomcat server.
ANS:- All these 5 steps to create our first Servlet Application.
1. Creating the Directory Structure:-Sun Microsystem defines a unique directory structure that must
be followed to create a servlet application.
servlet directory strucutre
Create the directory structure inside Apache-Tomcat\webapps directory. All HTML, static
files(images, css etc) are kept directly under Web application folder. While all the Servlet classes are
kept inside classes folder.
The web.xml (deployement descriptor) file is kept under WEB-INF folder.
2. Creating a Servlet:- There are three different ways to create a servlet.
By implementing Servlet interface
By extending GenericServlet class
By extending HttpServlet class
But mostly a servlet is created by extending HttpServlet abstract class. As discussed earlier
HttpServlet gives the definition of service() method of the Servlet interface. The servlet class that we
will create should not override service() method. Our servlet class will override only doGet() or
doPost() method.
When a request comes in for the servlet, the Web Container calls the servlet's service() method and
depending on the type of request the service() method calls either the doGet() or doPost() method.
NOTE: By default a request is Get request.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResposne response)
throws ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello Readers</h1>");
out.println("</body></html>");
}
}
Write above code in a notepad file and save it as MyServlet.java anywhere on your PC. Compile
it(explained in next step) from there and paste the class file into WEB-INF/classes/ directory that you
have to create inside Tomcat/webapps directory.
3. Compiling a Servlet:- To compile a Servlet a JAR file is required. Different servers require different
JAR files. In Apache Tomcat server servlet-api.jar file is required to compile a servlet class.
Steps to compile a Servlet:
• Set the Class Path.
• compiling a Servlet
• Download servlet-api.jar file.
• Paste the servlet-api.jar file inside Java\jdk\jre\lib\ext directory.
• compiling a Servlet
• Compile the Servlet class.
• compiling a Servlet
NOTE: After compiling your Servlet class you will have to paste the class file into WEB-INF/classes/
directory.
4. Create Deployment Descriptor:- Deployment Descriptor(DD) is an XML document that is used by
Web Container to run Servlets and JSP pages. DD is used for several important purposes such as:
• Mapping URL to Servlet class.
• Initializing parameters.
• Defining Error page.
• Security roles.
• Declaring tag libraries.
Now we will see how to create a simple web.xml file for our web application.
web.xml file
5. Start the Server:- Double click on the startup.bat file to start your Apache Tomcat Server.
Or, execute the following command on your windows machine using RUN prompt.
C:\apache-tomcat-7.0.14\bin\startup.bat
6. Starting Tomcat Server for the first time:- If you are starting Tomcat Server for the first time you
need to set JAVA_HOME in the Enviroment variable. The following steps will show you how to set it.
• Right Click on My Computer, go to Properites.- setting JAVA_HOME for Tomcat
• Go to Advanced Tab and Click on Enviroment Variables... button.- setting JAVA_HOME for
Tomcat
• Click on New button, and enter JAVA_HOME inside Variable name text field and path of JDK
inside Variable value text field. Click OK to save.- setting JAVA_HOME for Tomcat
7. Run Servlet Application
Open Browser and type http:localhost:8080/First/hello
Running first servlet application.

Q17. What is cookie? Explain working of Cookie.


ANS:- A cookie is a small bit of information that a website stores on your computer. When you revisit
the website, your browser sends the information back to the site. Usually a cookie is designed to
remember and tell a website some useful information about you. For example, an online bookstore
might use a persistent cookie to record the authors and titles of books you have ordered. When you
return to the online bookstore, your browser lets the bookstore’s site read the cookie. The site might
then compile a list of books by the same authors, or books on related topics, and show you that list.
This activity is invisible to you. Unless you have set your preferences so that you will be alerted when
a cookie is being stored on your computer, you won’t know about it. When you return to a website,
you won’t know that a cookie is being read. From your point of view, in the example above, you’d
simply visit the online bookstore, and a list of books that might be of interest to you would magically
appear.
There are two commonly known types of cookies. One is called a “session” or “non-persistent
cookie.” It is a cookie that only lasts as long as your session on the website and expires as soon as
you leave. It is used to facilitate your activities within that site. For example, if you are shopping on
an e-commerce site, this cookie enables their server to remember the items you are purchasing as
you move about within the site. These are very common in many websites, as they are a standard
part of Microsoft’s Active Server Page environment, an industry standard Web tool.
The second type of cookie, called a “persistent cookie” is so called because it persists beyond the life
of your session and may live for months or years. A persistent cookie is created in order to recognize
a user when they return to a website. It enables the site to offer a customized experience tailored to
that user – such as remembering your name and password on protected login pages.
Q18.Explain in detail:1) HTTP Request 2) HTTP Response
Q19. Explain jsp Conditionls with example.
ANS:- JSP if else loop is a conditional statement that enables a code snippet to be executed if a
particular condition stands true. This conditional statement works similarly to the if else conditional
statements in traditional coding languages like C/C++/Java and many more. This is a powerful impact
and is commonly used in programming languages. Programmers can provide more than one
condition using this loop with the help of “else-if” functionality.
Syntax of JSP if else
The syntax for JSP if-else loop is given below:
<%
if(condition)
{
Code or set of executable statements that should be processed if conditions stand true.
}
Else if() //optional
{
Code or set of executable statements that should be processed if second condition is true while the
first one stands false.
}
Else //optional
{
This condition should be executed if all conditions stand false.
}
%>
The if-else statement should be present on the JSP page. JSP page should be present in a specific
directory called “WEB-INF”.
If else statement reads True or False. The conclusion of “True or False” or “1 or 0” is reached when
the condition is being evaluated against the given parameters.
Example
NewFile.jsp
Code:
<%! int day = 3; %>
<html>
<head>
<title>JSP IF-ELSE</title>
</head>
<body>
<p>This is an JSP IF-ELSE Example in which today's day is compared with Sunday and according the
output
screen will show the result. Here, prerequisite is that today's date should be in sync with system
date.</p>
<% if (day == 1) { %>
<p> yaaay! Today is Sunday.. </p>
<% } else { %>
<p> Gosh! Today is a Work-day.. </p>
<% } %>
</body>
</html>

You might also like