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

Java Unit 5 Complete

The document provides an overview of Java Swing, highlighting its components and differences from AWT, including details on various Swing components such as JLabel, JTextField, JButton, JTabbedPane, JScrollPane, JList, and JComboBox. It also covers Java Servlets, their lifecycle, and the use of Tomcat for servlet development, detailing steps for setting up and creating servlets. Key features of Swing and Servlets are emphasized, showcasing their importance in building Java-based applications.

Uploaded by

syedhamid1491
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 views27 pages

Java Unit 5 Complete

The document provides an overview of Java Swing, highlighting its components and differences from AWT, including details on various Swing components such as JLabel, JTextField, JButton, JTabbedPane, JScrollPane, JList, and JComboBox. It also covers Java Servlets, their lifecycle, and the use of Tomcat for servlet development, detailing steps for setting up and creating servlets. Key features of Swing and Servlets are emphasized, showcasing their importance in building Java-based applications.

Uploaded by

syedhamid1491
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/ 27

PREPARED BY: SHAIK RASOOL, ASST. PROF.

, MJCET

Unit 5
5.1 Swings
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java. Unlike AWT, Java Swing provides platform-independent and lightweight
components.
Difference between AWT and Swing:
There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
1) AWT components are platform- Java swing components are platform-
dependent. independent.
2) AWT components are heavyweight. Swing components are lightweight.
3) AWT doesn't support pluggable look Swing supports pluggable look and feel.
and feel.
4) AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.
5) AWT doesn't follows MVC(Model Swing follows MVC
View Controller) where model
represents data, view represents
presentation and controller acts as an
interface between model and view.

The Swing Packages:

The main package is javax.swing. This package must be imported into any program that uses
Swing. It contains the classes that implement the basic Swing components, such as push
buttons, labels, and check boxes.

5.2 Swing Component

1
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

5.2.1 JLabel and ImageIcon


JLabel can be used to display text and/or an icon. It is a passive component in that it does not
respond to user input. JLabel defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label. The align argument specifies the
horizontal alignment of the text and/or icon within the dimensions of the label. It must be one
of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. These constants
are defined in the SwingConstants interface, along with several others used by the Swing
classes.
The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon
and encapsulates an image. ImageIcon constructor:
ImageIcon(String filename) It obtains the image in the file named filename.
The icon and text associated with the label can be obtained by the following methods:
Icon getIcon( )
String getText( )
The icon and text associated with a label can be set by these methods:
void setIcon(Icon icon)
void setText(String str)
Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it is possible
to change the text inside a label during program execution.
5.2.2 JtextField
The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
JTextField class declaration i.e. javax.swing.JTextField class.
public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text
columns) and columns.
JTextField(int columns) Creates a new empty TextField with the specified number
of columns.

2
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Commonly used Methods:


Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener
to receive action events from this textfield.
Action getAction() It returns the currently set Action for this
ActionEvent source, or null if no Action is
set.
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener l) It is used to remove the specified action
listener so that it no longer receives action
events from this textfield.

5.2.3 Swing Buttons


The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:
Constructor Description
JButton() It creates a button with no text and icon.
JButton(String s) It creates a button with the specified text.
JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:


Methods Description
void setText(String s) It is used to set specified text on button
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the
button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this
object.

5.2.4 Java JTabbedPane


The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.
JTabbedPane class declaration
3
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Let's see the declaration for javax.swing.JTabbedPane class.


public class JTabbedPane extends JComponent implements Serializable, Accessible,
SwingConstants
Commonly used Constructors:
Constructor Description
JTabbedPane() Creates an empty TabbedPane with a default tab
placement of JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab
placement.
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab
tabLayoutPolicy) placement and tab layout policy.

5.2.5 Java JScrollPane


A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.
Constructors
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when present,
JScrollPane(Component) sets the scroll pane's client. The two int parameters, when
JScrollPane(int, int) present, set the vertical and horizontal scroll bar policies
JScrollPane(Component, (respectively).
int, int)
Useful Methods
Modifier Method Description
void setColumnHeaderView(Component) It sets the column header for the scroll
pane.
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int
Component getCorner(String) parameter specifies which corner and
must be one of the following constants
defined in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
void setViewportView(Component) Set the scroll pane's client.

4
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

5.2.6 Java JList


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.
JList class declaration
Let's see the declaration for javax.swing.JList class.
public class JList extends JComponent implements Scrollable, Accessible
Commonly used Constructors:
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non-
dataModel) null, model.

Commonly used Methods:


Methods Description
Void It is used to add a listener to the list, to be
addListSelectionListener(ListSelectionListener notified each time a change to the selection
listener) occurs.
int getSelectedIndex() It is used to return the smallest selected
cell index.
ListModel getModel() It is used to return the data model that
holds a list of items displayed by the JList
component.
void setListData(Object[] listData) It is used to create a read-only ListModel
from an array of objects

5.2.7 Java JComboBox


The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable, ListData
Listener, ActionListener, Accessible

5
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Commonly used Constructors:


Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] Creates a JComboBox that contains the elements in the
items) specified array.
JComboBox(Vector<?> Creates a JComboBox that contains the elements in the
items) specified Vector.

Commonly used Methods:


Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is
editable.
void It is used to add the ActionListener.
addActionListener(ActionListener a)
void addItemListener(ItemListener i) It is used to add the ItemListener.

5.3 Servlets
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server. Using Servlets, you can collect input from users through web
page forms, present records from a database or another source, and create web pages
dynamically. Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with
the CGI.
• Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not necessary to create
a separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
5.3.1 Lifecycle
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.

6
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

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. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException


4) service method is invoked
The web container calls the service method each time when request for the servlet is received.
If servlet is not initialized, it follows the first three steps as described above then calls the

7
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

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 Servle
tException, 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()
5.3.2 Using Tomcat for Servlet Development
Tomcat is an open-source product maintained by the Jakarta Project of the Apache Software
Foundation. It contains the class libraries, documentation, and runtime support that you will
need to create and test servlets.
You can download Tomcat from jakarta.apache.org.
• The default location for Tomcat is C:\Program Files\Apache Software
Foundation\Tomcat\
• To start Tomcat, select Configure Tomcat in the Start | Programs menu, and then press
Start in the Tomcat Properties dialog. When you are done testing servlets, you can stop
Tomcat by pressing Stop in the Tomcat Properties dialog.
• The directory C:\Program Files\Apache Software Foundation\Tomcat\common\lib\
contains servlet-api.jar. This JAR file contains the classes and interfaces that are needed
to build servlets. To make this file accessible, update your CLASSPATH environment
variable so that it includes
C:\Program Files\Apache Software Foundation\Tomcat\common\lib\servlet-api.jar
• Alternatively, you can specify this file when you compile the servlets. For example, the
following command compiles the first servlet example
javac HelloServlet.java -classpath "C:\Program Files\Apache Software Foundation\
Tomcat 5.5\common\lib\servlet-api.jar"
• Once you have compiled a servlet, you must enable Tomcat to find it. This means
putting it into a directory under Tomcat’s webapps directory and entering its name into
a web.xml file.
Tomcat supplies its own example servlets that can be used to run our programs:
• First, copy the servlet’s class file into the following directory:
C:\Program Files\Apache Software Foundation\Tomcat\webapps\servlets-examples\WEB-
INF\classes
• Next, add the servlet’s name and mapping to the web.xml file in the following directory:
C:\Program Files\Apache Software Foundation\Tomcat\webapps\servlets-examples\WEB-
INF

8
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

For instance, assuming the first example, called HelloServlet, you will add the following
lines in the section that defines the servlets:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
Next, you will add the following lines to the section that defines the servlet mappings.
<servlet-mapping>
++++<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
5.3.3 Simple Servlet
There are 6 steps to create a servlet example. These steps are required for all the servers.
The servlet example can be created by three ways:
1. By implementing Servlet interface,
2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as follows:
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet
1) Create a directory structure
The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.
The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's
see the directory structure that must be followed to create the servlet.

9
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

As you can see that the servlet class file must be in the classes folder. The web.xml file must
be under the WEB-INF folder.
2) Create a Servlet

There are three ways to create the servlet.


1. By implementing the Servlet interface
2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class
The HttpServlet class is widely used to create the servlet because it provides methods to handle http
requests such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this example, we
are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice
that get request is the default request.

DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{

10
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

public void doGet(HttpServletRequest req,HttpServletResponse res) throws Servlet


Exception,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}}
3) Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different
jar files:

Jar file Server


servlet-api.jar Apache Tomcat
weblogic.jar Weblogic
javaee.jar Glassfish
javaee.jar JBoss

Two ways to load the jar file


1. set classpath
2. paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file, paste the class file of servlet
in WEB-INF/classes directory.
4) Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked. The web container uses the Parser to get the information from
the web.xml file.
There are many elements in the web.xml file. Here is given some necessary elements to run the
simple servlet program.
web.xml file

11
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

<web-app>
<servlet>
<servlet-name> DemoServlet </servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> DemoServlet </servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Description of the elements of web.xml file
There are too many elements in the web.xml file. Here is the illustration of some elements that
is used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.

5) Start the Server and deploy the project


To start Apache Tomcat server, open windows start menu and click on “Configure Tomcat”
and “start” the server.
One Time Configuration for Apache Tomcat Server
set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).

12
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Copy the project and paste it in the webapps folder under apache tomcat.
But there are several ways to deploy the project. They are as follows:
• By copying the context(project) folder into the webapps directory
• By copying the war folder into the webapps directory
• By selecting the folder path from the server
• By selecting the war file from the server
• Here, we are using the first approach.
You can also create war file, and paste it inside the webapps directory. To do so, you need to
use jar tool to create the war file. Go inside the project directory (before the WEB-INF), then
write:
projectfolder> jar cvf myproject.war *
Creating war file has an advantage that moving the project from one location to another takes
less time.
6) How to access the servlet
Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:
http://localhost:8080/demo/welcome

13
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

5.3.4 The Servlet API


Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servlet and javax.servlet.http.
The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
5.3.5 The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
The following table summarizes the core interfaces that are provided in this package. The most
significant of these is Servlet. All servlets must implement this interface or extend a class that
implements the interface.

The following table summarizes the core classes that are provided in the javax.servlet package:

The Servlet Interface:


All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy(
) methods that are called by the server during the life cycle of a servlet.

14
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

The ServletConfig Interface:


The ServletConfig interface allows a servlet to obtain configuration data when it is loaded.

The ServletContext Interface:


The ServletContext interface enables servlets to obtain information about their environment.

The ServletRequest Interface:


The ServletRequest interface enables a servlet to obtain information about a client request.

15
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

The ServletResponse Interface:


The ServletResponse interface enables a servlet to formulate a response for a client.

The GenericServlet Class:


The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
GenericServlet implements the Servlet and ServletConfig interfaces

The ServletInputStream Class:


The ServletInputStream class extends InputStream. It is implemented by the servlet container
and provides an input stream that a servlet developer can use to read the data from a client
request

16
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

The ServletOutputStream Class:


The ServletOutputStream class extends OutputStream. It is implemented by the servlet
container and provides an output stream that a servlet developer can use to write data to a client
response. A default constructor is defined. It also defines the print( ) and println( ) methods,
which output data to the stream.
The Servlet Exception Classes:
javax.servlet defines two exceptions.
• The first is ServletException, which indicates that a servlet problem has occurred.
• The second is UnavailableException, which extends ServletException. It indicates that
a servlet is unavailable.
5.3.6 Reading Servlet Parameters
The ServletRequest interface includes methods that allow you to read the names and values of
parameters that are included in a client request.
Example:
The example contains two files. Aweb page is defined in PostParameters.htm, and a servlet is
defined in PostParametersServlet.java.
The HTMLsource code for PostParameters.htm is shown in the following listing. It defines a
table that contains two labels and two text fields. One of the labels is Employee and the other
is Phone. There is also a submit button. Notice that the action parameter of the form tag
specifies a URL. The URL identifies the servlet to process the HTTP POST request
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/ReadingParameters/PostParametersServlet">
<table> <tr>
<td><B>Employee</td> <td><input type=textbox name="e" size="25" value=""></td>
</tr> <tr>
<td><B>Phone</td> <td><input type=textbox name="p" size="25" value=""></td> </tr>
</table>
<input type=submit value="Submit">
</body>
</html>

The source code for PostParametersServlet.java is shown in the following listing. The service()
method is overridden to process client requests. The getParameterNames() method returns an
enumeration of the parameter names. These are processed in a loop. You can see that the
parameter name and value are output to the client. The parameter value is obtained via the
getParameter( ) method.

17
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}

Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml file, as
previously described. Then, perform these steps to test this example:
1. Start Tomcat (if it is not already running).
2. Display the web page in a browser.
3. Enter an employee name and phone number in the text fields.
4. Submit the web page.
After following these steps, the browser will display a response that is dynamically generated
by the servlet.
5.3.7 The javax.servlet.http Package
The javax.servlet.http package contains a number of interfaces and classes that are commonly
used by servlet developers.
The following table summarizes the core interfaces that are provided in this package:

18
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

The following table summarizes the core classes that are provided in this package. The most
important of these is HttpServlet. Servlet developers typically extend this class in order to
process HTTP requests.

The HttpServletRequest Interface:


The HttpServletRequest interface enables a servlet to obtain information about a client request.

The HttpServletResponse Interface:


The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.

19
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

The HttpSession Interface:


The HttpSession interface enables a servlet to read and write the state information that is
associated with an HTTP session.

The Cookie Class:


The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state
information. Cookies are valuable for tracking user activities. Aservlet can write a cookie to a
user’s machine via the addCookie( ) method of the HttpServletResponse interface. The data for
that cookie is then included in the header of the HTTP response that is sent to the browser.

20
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

Some of the information that is saved for each cookie includes the following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)

The HttpServlet Class:


The HttpServlet class extends GenericServlet. It is commonly used when developing servlets
that receive and process HTTP requests.

21
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

5.3.8 Handling HTTP Requests and Responses


The HttpServlet class provides specialized methods that handle the various types of HTTP
requests.. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut(
), and doTrace( ).
he GET and POST requests are commonly used when handling form input
Handling HTTP GET Requests:
A servlet that handles an HTTPGET request. The example contains two files. A web page is
defined in ColorGet.htm, and a servlet is defined in ColorGetServlet.java.
The HTML source code for ColorGet.htm is shown in the following listing. It defines a form
that contains a select element and a submit button. Notice that the action parameter of the form
tag specifies a URL. The URL identifies a servlet to process the HTTP GET request.
<html>
<body>
<center>
<form name= "Form1" action= "http://localhost:8080/HTTPGETRequests/ColorGetServlet">
<B>Color:</B> <select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select> <br><br> <input type=submit value="Submit">
</form>
</body>
</html>

The source code for ColorGetServlet.java is shown in the following listing. The doGet( )
method is overridden to process any HTTP GET requests that are sent to this servlet. It uses
the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the
user. A response is then formulated
import java.io.*; import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color); pw.close();
}
}

22
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

After completing execution steps, the browser will display the response that is dynamically
generated by the servlet. One other point: Parameters for an HTTPGET request are included as
part of the URL that is sent to the web server.
The URL sent from the browser to the server is
http://localhost:8080/HTTPGETRequests/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string.

Handling HTTP POST Requests:


Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked
when a form on a web page is submitted.
The example contains two files. A web page is defined in ColorPost.htm, and a servlet is
defined in ColorPostServlet.java.
The HTML source code for ColorPost.htm is shown in the following listing. It is identical to
ColorGet.htm except that the method parameter for the form tag explicitly specifies that the
POST method should be used, and the action parameter for the form tag specifies a different
servlet.
<html>
<body>
<center>
<form name="Form1" method="post" action="http://localhost:8080/HTTPPOSTRequests
/ColorPostServlet">
<B>Color:</B> <select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select> <br><br> <input type=submit value="Submit">
</form>
</body>
</html>

The source code for ColorPostServlet.java is shown in the following listing. The doPost( )
method is overridden to process any HTTP POST requests that are sent to this servlet. It uses
the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the
user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
23
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color); pw.close();
}
}
Parameters for an HTTP POST request are not included as part of the URL that is sent to the
web server. In this example, the URL sent from the browser to the server is
http://localhost:8080/HTTPPOSTRequests/ColorPostServlet. The parameter names and values
are sent in the body of the HTTP request.
Get vs. Post
There are many differences between the Get and Post request. Let's see these differences:
GET POST

1) In case of Get request, only limited amount In case of post request, large amount of
of data can be sent because data is sent in data can be sent because data is sent in
header. body.
2) Get request is not secured because data is Post request is secured because data is
exposed in URL bar. not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
4) Get request is idempotent . It means second Post request is non-idempotent.
request will be ignored until response of first
request is delivered
5) Get request is more efficient and used more Post request is less efficient and used
than Post. less than get.

5.3.9 Using Cookies


Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a
form on a web page is submitted.

The HTML source code for AddCookie.htm is shown in the following listing. This page
contains a text field in which a value can be entered. There is also a submit button on the page.
When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP
POST request.

24
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

<html>
<body>
<center> <form name="Form1" method="post"action="http://localhost:8080/Cookies
/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>

The source code for AddCookieServlet.java is shown in the following listing. It gets the value
of the parameter named “data”. It then creates a Cookie object that has the name “MyCookie”
and contains the value of the “data” parameter. The cookie is then added to the header of the
HTTP response via the addCookie( ) method. A feedback message is then written to the
browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest
request, HttpServletResponse response) throws ServletException, IOException
{
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data); pw.close();
}
}

The source code for GetCookiesServlet.java is shown in the following listing. It invokes the
getCookies( ) method to read any cookies that are included in the HTTP GET request. The
names and values of these cookies are then written to the HTTP response. Observe that the
getName( ) and getValue( ) methods are called to obtain this information.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

25
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

public class GetCookiesServlet extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name + "; value = " + value);
}
pw.close();
}
}
After completing execution steps, you will observe that a feedback message is displayed by the
browser. Next, request the following URL via the browser:
http://localhost:8080/Cookies/GetCookieServlet
Observe that the name and value of the cookie are displayed in the browser.

5.3.10 Session Tracking


HTTP is a stateless protocol. Each request is independent of the previous one. However, in
some applications, it is necessary to save state information so that information can be collected
from several interactions between a browser and a server. Sessions provide such a mechanism.
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession
object is returned. This object can store a set of bindings that associate names with objects. The
setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of
HttpSession manage these bindings. It is important to note that session state is shared among
all the servlets that are associated with a particular client.
The following servlet illustrates how to use session state. The getSession( ) method gets the
current session. A new session is created if one does not already exist.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

26
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET

public class DateServlet extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null)
{
pw.print("Last access: " + date + "<br>"); }
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}
When you first request this servlet, the browser displays one line with the current date and time
information. On subsequent invocations, two lines are displayed. The first line shows the date
and time when the servlet was last accessed. The second line shows the current date and time.

27

You might also like