Java Unit 5 Complete
Java Unit 5 Complete
, 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 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.
1
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
2
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
4
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
5
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
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
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:
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
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
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:
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.
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
The following table summarizes the core classes that are provided in the javax.servlet package:
14
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
15
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
16
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
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.
19
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
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)
21
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
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.
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.
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
26
PREPARED BY: SHAIK RASOOL, ASST. PROF., MJCET
27