OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
UNIT-V
Exploring Swing: JLabel, ImageIcon, JTextField, the Swing buttons, JTabbedpane, JScrollPane,
JList, JComboBox. Servlet: Life cycle, using tomcat, simple servlet, servlet API, [Link]
package, reading servletparameters,[Link] package, handling HTTP requests and responses.
Course Objective: Exploring Swing and implementing Servlets.
Course Outcome: Create graphical user interface and Applets in java as well as apply knowledge of
event handling.
EXPLORING SWING
JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
import [Link].*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
[Link](50,50, 100,30);
l2=new JLabel("Second Label.");
[Link](50,100, 100,30);
[Link](l1); [Link](l2);
[Link](300,300);
[Link](null);
[Link](true);
}}
ImageIcon
Icon is small fixed size picture, typically used to decorate components. ImageIcon is an
implementation of the Icon interface that paints icons from images. Images can be created from
a URL, filename, or byte array.
ImageIcon has several constructors, including:
ImageIcon(byte[] imageData) — creates an ImageIcon from an array of bytes.
ImageIcon(Image image) — creates an ImageIcon from an image object.
ImageIcon(String filename) — creates an ImageIcon the specified file.
ImageIcon(URL location) — creates an ImageIcon from the specified URL.
JTextField
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.
1
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
import [Link].*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
[Link](50,100, 200,30);
t2=new JTextField("AWT Tutorial");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
} }
The 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
Abstract Button class.
import [Link].*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
[Link](130,100,100, 40);//x axis, y axis, width, height
[Link](b);//adding button in JFrame
[Link](400,500);//400 width and 500 height
[Link](null);//using no layout managers
[Link](true);//making the frame visible
} }
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.
import [Link].*;
public class TabbedPaneExample {
JFrame f;
2
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
[Link](ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
[Link](50,50,200,200);
[Link]("main",p1);
[Link]("visit",p2);
[Link]("help",p3);
[Link](tp);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
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.
import [Link];
import [Link];
import [Link];
import [Link];
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Scroll Pane Example");
// Display the window.
[Link](500, 500);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
[Link]().setLayout(new FlowLayout());
3
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
[Link](JScrollPane.HORIZONTAL_SCROLLBAR_A
LWAYS);
[Link](JScrollPane.VERTICAL_SCROLLBAR_ALWA
YS);
[Link]().add(scrollableTextArea);
}
public static void main(String[] args) {
[Link](new Runnable() {
public void run() {
createAndShowGUI();
} }); } }
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.
import [Link].*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
[Link]("Item1");
[Link]("Item2");
[Link]("Item3");
[Link]("Item4");
JList<String> list = new JList<>(l1);
[Link](100,100, 75,75);
[Link](list);
[Link](400,400);
[Link](null);
[Link](true);
} public static void main(String args[]) {
new ListExample(); }}
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.
import [Link].*;
public class ComboBoxExample {
4
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
[Link](null);
[Link](400,500);
[Link](true);
}
public static void main(String[] args) {
new ComboBoxExample();
} }
Servlet Life Cycle
Java Servlet life cycle consists of a series of events that begins when the Servlet container loads
Servlet, and ends when the container is closed down Servlet. A servlet container is the part of a
web server or an application server that controls a Servlet by managing its life cycle. Basically
there are three phases of the life cycle.
The web container maintains the life cycle of a servlet instance.
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.
5
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Servlet using tomcat
// Java program to show servlet example
// Importing required Java libraries
import [Link].*;
import [Link].*;
import [Link].*;
// Extend HttpServlet class
public class AdvanceJavaConcepts extends HttpServlet
{
private String output;
// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}
// Requesting and printing the output
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
[Link](output);
}
public void destroy()
{
[Link]("Over");
}}
Simple servlet
/ Import required java libraries
import [Link].*;
import [Link].*;
import [Link].*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}
6
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
[Link]("text/html");
// Actual logic goes here.
PrintWriter out = [Link]();
[Link]("<h1>" + message + "</h1>");
}
public void destroy()
{ // do nothing.
} }
Servlet API
The [Link] and [Link] packages represent interfaces and classes for servlet api.
The [Link] package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.
The [Link] package contains interfaces and classes that are responsible for http requests
only.
[Link] package
Interfaces in [Link] package
There are many interfaces in [Link] package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
Classes in [Link] package
1. There are many classes in [Link] package. They are as follows:
2. GenericServlet
3. ServletInputStream
4. ServletOutputStream
5. ServletRequestWrapper
6. ServletResponseWrapper
7. ServletRequestEvent
8. ServletContextEvent
9. ServletRequestAttributeEvent
7
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
10. ServletContextAttributeEvent
11. ServletException
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.
[Link]:
This prepares the response as HTML file that displays request parameters
import [Link].*;
import [Link].*;
import [Link].*;
public class ReadParamsServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException {
PrintWriter pw = [Link]();
Enumeration list = [Link]();
while([Link]()) {
String paramname = (String)[Link]();
[Link](paramname + " = ");
String paramvalue = [Link](paramname); [Link](paramvalue);
} [Link](); } }
PrintWriter out = [Link]();
[Link]("text/html");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>InitParams! </title>");
outprintln("</head>");
[Link]("<body>");
[Link]("<h1>Init Params from Serylet!</h1>");
Iterator<[Link]> iter = [Link]().iterator();
while ([Link]) [Link] entry = [Link]();
String key = (String)[Link]();
String value = (String)[Link]();
[Link]("InitParameter :" +key +" Its Value:"+value+ …..") }
[Link]("</body>");
[Link]("</html>");
[Link](); }}
[Link]
<servlet> tag maps your servlet class with internal name
<servlet-mapping> tag maps internal name with url-pattern that your invoke
-<web-app xmlns="[Link]
xmins:xsi="[Link]
xsi:schemaLocation="[Link] version="2.4">
8
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
-<servlet>
<servlet-name>paramsservlet</servlet-name>
<servlet-class>ReadParamsServiet</servlet-class>
</servlet> <servlet-mapping>
-<servlet-name>paramsservlet</servlet-name>
<url-pattern>/[Link]</url-pattern>
</servlet-mapping>
</web-app>
[Link]
<html>
<body> <center> <hl align="center">Welcome to Student Registration Page...</h1>
<form name="StudentForm" method="post" action="[Link]">
<table> <tr> <td><B>Name of Student : </td>
<td><input type=textbox name="StudentNameParam" size="25" value=""></td>
</tr> <tr> <td><B>Registration # : </td>
<td><input type=textbox name="RollNumberParam" s' value=""> </td>
</tr> <tr> <td><B>Father's Name : </td>
<td><input type=textbox name="FatherName" size="25" value="">'</td>
</tr> </table></form></center></body></html>
[Link] package
This package of servlet contains more interfaces and classes which are capable of handling any
specified http types of protocols on the servlet. This [Link] package containing many
interfaces and classes that are used for http requests only for servlet
Interfaces in [Link]
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
Classes in [Link] package
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
Handling HTTP Requests And Responses
The HttpServlet class provides specialized methods that handle the various types of HTTP
requests. A servlet developer typically overrides one of these methods. These methods are
doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). A complete
description of the different types of HTTP requests is beyond the scope of this book. However,
the GET and POST requests are commonly used when handling form input.
9
OOP using JAVA (PC303CS) (AICTE) III-SEMESTER
Handling HTTP GET Requests
The URL identifies a servlet to process the HTTP GET request.
Handling HTTP POST Requests
The POST method should be used and the action parameter for the form tag specifies a different
servlet.
Example program:
// Import required java libraries
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
// Extend HttpServlet class
public class Refresh extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set refresh, autoload time as 5 seconds
[Link]("Refresh", 5);
// Set response content type
[Link]("text/html");
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = [Link]([Link]);
int minute = [Link]([Link]);
int second = [Link]([Link]);
if([Link](Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
PrintWriter out = [Link]();
String title = "Auto Refresh Header Setting";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
[Link](docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
); }
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
END OF UNIT - V
10