AOT Unit-1 - Merged
AOT Unit-1 - Merged
AOT Unit-1 - Merged
UNIT-1
• Introduction to Javascript-
JavaScript is a lightweight, cross-platform, and interpreted compiled
programming language which is also known as the scripting language for
webpages. It is well-known for the development of web pages, many non-
browser environments also use it. JavaScript can be used for Client-
side developments as well as Server-side developments. Javascript is both
imperative and declarative type of language .JavaScript contains a standard
library of objects, like Array, Date, and Math, and a core set of language
elements like operators, control structures, and statements.
• Objects in Javascript-
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc. JavaScript is an object-
based language. Everything is an object in JavaScript. JavaScript is template based not
class based. Here, we don't create class to get the object. But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
object={property1:value1,property2:value2.....propertyN:valueN}
Example:
emp={id:102,name:"Shyam Kumar",salary:40000}
Example:
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
Following are the various examples, which describes how to use the JavaScript
technology with the DHTML(Dynamic HTML):
Document.write() Method
<HTML>
<head>
<title>
Method of a JavaScript
</title>
</head>
<body>
<script type="text/javascript">
document.write("JavaTpoint");
</script>
</body>
</html>
Output:
A JavaScript code can also be executed when some event occurs. Suppose, a user clicks
an HTML element on a webpage, and after clicking, the JavaScript function associated
with that HTML element is automatically invoked. And, then the statements in the
function are performed.
Example 1: The following example shows the current date and time with the JavaScript
and HTML event (Onclick). In this example, we type the JavaScript code in the <head>
tag.
<html>
<head>
<title>
DHTML with JavaScript
</title>
<script type="text/javascript">
function dateandtime()
{
alert(Date());
}
</script>
</head>
Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
</p> </center>
</body>
</html>
Output:
• XML
XML Usage
A short list of XML usage says it all −
• XML can work behind the scene to simplify the creation of HTML
documents for large web sites.
• XML can be used to exchange the information between organizations
and systems.
• XML can be used for offloading and reloading of databases.
• XML can be used to store and arrange the data, which can customize
your data handling needs.
• XML can easily be merged with style sheets to create almost any
desired output.
• Virtually, any type of data can be expressed as an XML document
.
• Document Type Definition – DTD
A Document Type Definition (DTD) describes the tree structure of a document
and something about its data. It is a set of markup affirmations that actually
define a type of document for the SGML family, like GML, SGML, HTML, XML.
• Example
<address>
<name>
<first>Rohit</first>
<last>Sharma</last>
</name>
<email>sharmarohit@gmail.com</email>
<phone>9876543210</phone>
<birthday>
<year>1987</year>
<month>June</month>
<day>23</day>
</birthday>
</address>
The DTD above is interpreted like this:
o !DOCTYPE address defines that the root element of this document is address.
o !ELEMENT address defines that the address element must contain four
elements: “name, email, phone, birthday”.
o !ELEMENT name defines that the name element must contain two elements:
“first, last”.
o !ELEMENT first defines the first element to be of type “#PCDATA”.
o !ELEMENT last defines the last element to be of type “#PCDATA”.
o !ELEMENT email defines the email element to be of type “#PCDATA”.
o !ELEMENT phone defines the phone element to be of type “#PCDATA”.
o !ELEMENT birthday defines that the birthday element must contain three
elements “year, month, day”.
o !ELEMENT year defines the year element to be of type “#PCDATA”.
o !ELEMENT month defines the month element to be of type “#PCDATA”.
o !ELEMENT day defines the day element to be of type “#PCDATA”.
• XML Schema
• An XML Schema describes the structure of an XML document.
XSD Example
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
In other words: The XML DOM is a standard for how to get, change,
add, or delete XML elements.
This code retrieves the text value of the first <title> element in an XML
document:
Example
txt = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
Example Explained
The easiest way to find an HTML element in the DOM, is by using the
element id.
Example
var myElement = document.getElementById("intro");
Finding HTML Elements by Tag Name
Example
var x = document.getElementsByTagName("p");
If you want to find all HTML elements with the same class name, use
getElementsByClassName().
Example
var x = document.getElementsByClassName("intro");
If you want to find all HTML elements that matches a specified CSS selector (id,
class names, types, attributes, values of attributes, etc), use the
querySelectorAll() method.
Example
var x = document.querySelectorAll("p.intro");
• Review of Applets
APPLET
Applets are small applications that are accessed on an Internet server,
transported over the Internet, automatically installed, and run as part of a
Web document. After an applet arrives on the client, it has limited access
to resources, so that it can produce an arbitrary multimedia user interface
and run complex computations without introducing the risk of viruses or
breaching data integrity.
The second import statement imports the applet package, which contains
the class Applet. Every applet that you create must be a subclass of
Applet.
The next line in the program declares the class SimpleApplet. This class
must be declared as public, because it will be accessed by code that is
outside the program.
Inside SimpleApplet, paint( ) is declared. This method is defined by the
AWT and must be overridden by the applet. paint( ) is called each time
that the applet must redisplay its output.
oinit( )
ostart( )
opaint( )
When an applet is terminated, the following sequence of method calls takes
place:
o stop( )
o destroy( )
o
Let’s look more closely at these methods.
1. init( ) : The init( ) method is the first method to be called. This is where you
should initialize variables. This method is called only once during the run time of
your applet.
2. start( ) : The start( ) method is called after init( ). It is also called to restart
an applet after it has been stopped. Note that init( ) is called once i.e. when the
first time an applet is loaded whereas start( ) is called each time an applet’s
HTML document is displayed onscreen. So, if a user leaves a web page and
comes back, the applet resumes execution at start( ).
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page, for example.
When stop( ) is called, the applet is probably running. You should use stop( ) to
suspend threads that don’t need to run when the applet is not visible. You can
restart them when start( ) is called if the user returns to the page.
The width and height statements specify the dimensions of the display area used
by the applet. The APPLET tag contains several other options. After you create
this html file, you can use it to execute the applet.
2. Using appletviewer : This is the easiest way to run an applet. To execute
HelloWorld with an applet viewer, you may also execute the HTML file shown
earlier. For example, if the preceding HTML file is saved with
RunHelloWorld.html, then the following command line will run HelloWorld :
appletviewer RunHelloWorld.html
The Applet class provides a standard interface between applets and their
environment. The Applet class is the superclass of an applet that is embedded in
a Web page or viewed by the Java Applet Viewer. The Java applet class gives
several useful methods to give you complete control over the running of an
Applet. Like initializing and destroying an applet, It also provides ways that load
and display Web Colourful images and methods that load and play audio and
Videos Clips and Cinematic Videos.
Advantages of Applet
• It runs inside the browser and works on the Client-side, so it takes less
time to respond.
• It is more Secured
• It can be Executed By multi-platforms with any Browsers, i.e., Windows,
Mac Os, Linux Os.
Disadvantages of Applet
• A plugin is required at the client browser(User Side) to execute an Applet.
• Event Handling
An event can be defined as changing the state of an object or behavior by
performing actions. Actions can be a button click, cursor movement, keypress
through keyboard or page scrolling, etc.
Classification of Events
• Foreground Events
• Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate,
i.e., foreground events are generated due to interaction by the user on
components in Graphic User Interface (GUI). Interactions are nothing but
clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen
after an event occur. To handle the events, Java follows the Delegation Event
model.
Delegation Event model
• It has Sources and Listeners.
• Source: Events are generated from the source. There are various sources
like buttons, checkboxes, list, menu-item, choice, scrollbar, text
components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible
for handling events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
ActionListener
• actionPerformed()
AdjustmentListener
• adjustmentValueChanged()
• componentResized()
• componentShown()
• componentMoved()
ComponentListener
• componentHidden()
• componentAdded()
ContainerListener
• componentRemoved()
• focusGained()
FocusListener
• focusLost()
ItemListener
• itemStateChanged()
• keyTyped()
• keyPressed()
KeyListener
• keyReleased()
• mousePressed()
• mouseClicked()
• mouseEntered()
• mouseExited()
MouseListener
• mouseReleased()
• mouseMoved()
MouseMotionListener
• mouseDragged()
MouseWheelListener
• mouseWheelMoved()
TextListener
• textChanged()
Listener Interface Methods
• windowActivated()
• windowDeactivated()
• windowOpened()
• windowClosed()
• windowClosing()
• windowIconified()
WindowListener
• windowDeiconified()
• AWT Programming
• Java AWT (Abstract Window Toolkit) is an API to develop Graphical User
Interface (GUI) or windows-based applications in Java.
• Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
• The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
• The AWT tutorial will help the user to understand Java GUI programming in
simple and easy steps.
For example, an AWT GUI with components like TextField, label and button will have
different look and feel for the different platforms like Windows, MAC OS, and Unix.
The reason for this is the platforms have different view for their native components
and AWT directly calls the native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows
OS whereas it will look like a Mac application in the MAC OS.
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.
Types of containers:
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.
Method Description
AWTExample1.java
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the above
example that sets the position of the awt button.
Output:
AWTExample2.java
Output:
UNIT-II
Introduction to Swing, Differences between AWT Controls &
Swing Controls, JApplet, Swing Button: JButton, JToggleButton,
CheckBoxes, Radio Button, JComboBox, Text Boxes etc., Icons,
Labels, JTabbed Pains, JScroll Pains, JList, JTrees, JTables Java
Beans: Introduction to Java Beans, Advantages of Java Beans,
BDK Introspection, developing a home page using Applet &
Swing.
Swing has about four times the number of User Interface [U1] components
as AWT and is part of the standard Java distribution. By today’s application
GUI requirements, AWT is a limited implementation, not quite capable of
providing the components required for developing complex GUIs required in
modern commercial applications. The AWT component set has quite a few
bugs and really does take up a lot of system resources when compared to
equivalent Swing resources. Netscape introduced its Internet Foundation
Classes [IFC] library for use with Java. Its Classes became very popular with
programmers creating GUIs for commercial applications.
• Swing is a Set of API ( API- Set of Classes and Interfaces )
• Swing is Provided to Design a Graphical User Interfaces
• Swing is an Extension library to the AWT (Abstract Window Toolkit)
• Includes New and improved Components that have been enhancing
the looks and Functionality of GUI’s
• Swing can be used to build(Develop) The Standalone swing GUI
Apps Also as Servlets and Applets
• It Employs model/view design architecture
• Swing is more portable and more flexible than AWT, The Swing is
built on top of the AWT
• Swing is Entirely written in Java
• Java Swing Components are Platform-independent And The Swing
Components are lightweight
• Swing Supports Pluggable look and feels And Swing provides more
powerful components
• such as tables, lists, ScrollPane, Colour chooser, tabbed pane, etc
• Further Swing Follows MVC
Many programmers think that JFC and Swing is one and the same thing, but
that is not so.
JFC contains Swing [A UI component package] and quite a number of other
items:
• Cut and paste: Clipboard support
• Accessibility features: Aimed at developing GUI’s for users with
disabilities
• The Desktop Colors Features Has been Firstly introduced in Java
1.1
• The Java 2D: it has Improved colors, images, and also texts
support
Features Of Swing Class
• Pluggable look and feel
• Uses MVC architecture
• Lightweight Components
• Platform Independent
• Advance features such as JTables, JTabbedPane, JScrollPane etc
• Java is a platform-independent language and runs on any client
machine, the GUI look and feel, owned and delivered by a platform
specific O/S, simply does not affect an application’s GUI
constructed using Swing components
• Lightweight Components: Starting with the JDK 1.1, its AWT
supported lightweight component development. For a component to
qualify as lightweight, it must not depend on any non-Java [O/s
based) system classes. Swing components have their own view
supported by Java’s look and feel classes
• Pluggable Look and Feel: This feature enables the user to switch
the look and feel of Swing components without restarting an
application. The Swing library supports components look and feel
that remains the same across all platforms wherever the program
runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
Swing Classes Hierarchy
On the other hand, Swing is the part of JFC (Java Foundation Classes) built on the top
of AWT and written entirely in Java
. The javax.swing API provides all the component classes like JButton, JTextField, JCheckbox, JMenu,
etc.
API Package The AWT Component classes are The Swing component classes are provided
provided by the java.awt package. by the javax.swing package.
Operating System The Components used in AWT are The Components used in Swing are not
mainly dependent on the operating dependent on the operating system. It is
system. completely scripted in Java.
Weightiness The AWT is heavyweight since it uses The Swing is mostly lightweight since it
the resources of the operating doesn't need any Operating system object
system. for processing. The Swing Components are
built on the top of AWT.
Appearance The Appearance of AWT Components The Swing Components are configurable
is mainly not configurable. It generally and mainly support pluggable look and feel.
depends on the operating system's
look and feels.
Number of The Java AWT provides a smaller Java Swing provides a greater number of
Components number of components in components than AWT, such as list, scroll
comparison to Swing. panes, tables, color choosers, etc.
Full-Form Java AWT stands for Abstract Window Java Swing is mainly referred to as Java
Toolkit. Foundation Classes (JFC).
Peers Java AWT has 21 peers. There is one Java Swing has only one peer in the form of
peer for each control and one peer for OS's window object, which provides the
the dialogue. Peers are provided by drawing surface used to draw the Swing's
the operating system in the form of widgets (label, button, entry fields, etc.)
widgets themselves. developed directly by Java Swing Package.
Functionality and Java AWT many features that are Swing components provide the higher-level
Implementation completely developed by the inbuilt functions for the developer that
developer. It serves as a thin layer of facilitates the coder to write less code.
development on the top of the OS.
Memory Java AWT needs a higher amount of Java Swing needs less memory space as
memory for the execution. compared to Java AWT.
Speed Java AWT is slower than swing in Java Swing is faster than the AWT.
terms of performance.
JApplet
Java applets can be executed on multiple platforms which include
Microsoft Windows, UNIX, Mac OS and Linux. JApplet can also be run as
an application, though this would require a little extra coding. The
executable applet is made available on a domain from which it needs to
be downloaded. The communication of the applet is restricted only to this
particular domain.
JButton
The JButton class is used to create a labelled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits Abstract Button class.
Constructor Description
Methods Description
JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or
off.
Nested Classes
Modifier Class Description
and Type
Constructors
Constructor Description
JToggleButton(Icon icon, boolean It creates a toggle button with the specified image and
selected) selection state, but no text.
JToggleButton(String text, boolean It creates a toggle button with the specified text and
selected) selection state.
JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and
image, and that is initially unselected.
JToggleButton(String text, Icon icon, It creates a toggle button with the specified text, image,
boolean selected) and selection state.
Methods
CheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true)
or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off"
to "on ".It inherits JToggleButton
class.
Constructor Description
JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it
selected) is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.
Commonly used Methods:
Methods Description
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.
Constructor Description
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
Methods Description
void setText(String s) It is used to set specified text on button.
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.
Constructor Description
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.
void removeAllItems() It is used to remove all the items from the list.
JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.
Constructor Description
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 and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of columns.
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.
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.
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty
string for the title.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
Methods Description
void setText(String text) It defines the single line of text this component will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along the X axis.
alignment)
Icon getIcon() It returns the graphic image that the label displays.
int getHorizontalAlignment() It returns the alignment of the label's contents along the X
axis.
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.
Constructor Description
JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement
tabLayoutPolicy) and tab layout policy.
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, sets the
scroll pane's client. The two int parameters, when present, set the vertical
JScrollPane(Component) and horizontal scroll bar policies (respectively).
JScrollPane(int, int)
JScrollPane(Component,
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 parameter
specifies which corner and must be one of the
Component getCorner(String) 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.
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.
Constructor Description
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-null,
dataModel) model.
Methods Description
ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.
JTree
The JTree class is used to display the 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.
Constructor Description
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the root
root) node.
JTable
The JTable class is used to display data in tabular form. It is composed of rows and
columns.
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
JavaBean
A JavaBean is a Java class that should follow the following conventions:
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object.
The feature can be of any Java data type, containing the classes that you define.
1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
Advantages of JavaBean
The following are the advantages of JavaBean:/p>
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
Introspection
At the core of Java Beans is introspection. This is the process of analyzing a Bean
to determine its capabilities. This is an essential feature of the Java Beans API
because it allows another application, such as a design tool, to obtain information
about a component. Without introspection, the Java Beans technology could not
operate.
There are two ways in which the developer of a Bean can indicate which of its
properties, events, and methods should be exposed. With the first method, simple
naming conventions are used. These allow the introspection mechanisms to infer
information about a Bean. In the second way, an additional class that extends
the BeanInfo interface is provided that explicitly supplies this information. Both
approaches are examined here.
Simple Properties
A simple property has a single value. It can be identified by the following design
patterns, where N is the name of the property and T is its type:
A read/write property has both of these methods to access its values. A read-only
property has only a get method. A write-only property has only a set method.
Indexed Properties
An indexed property consists of multiple values. It can be identified by the
following design patterns, where N is the name of the property and T is its type:
Here is an indexed property called data along with its getter and setter methods:
Unit=3
Servlets | Servlet Tutorial
There are many interfaces and classes in the Servlet API such as Servlet,
Servlet
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
The web container maintains the life cycle of a servlet instance. Let's see the
life cycle of the servlet:
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.
Servlet API
1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. Classes in javax.servlet.http package
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.
208
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
If the instance definition does not contain an initialization parameter with the name provided,
the getInitParameter() function returns an empty string.
HTTP Requests
The request sent by the computer to a web server, contains all sorts of
potentially interesting information; it is known as HTTP requests.
The HTTP client sends the request to the server in the form of request
message which includes following information:
o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header
The HTTP request method indicates the method to be performed on the
resource identified by the Requested URI (Uniform Resource Identifier).
This method is case-sensitive and should be used in uppercase.
HTTP Description
Request
POST Asks the server to accept the body info attached. It is like GET
request with extra info sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just
like GET but with no body.
TRACE Asks for the loopback of the request message, for testing or
troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request
URL can respond
The HTML source code for ColorPost.html is shown in the following listing. It is
identical to ColorGet.html 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.
JSP Tutorial
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to Servlet because it provides more
functionality than servlet such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development. It
provides some additional features such as Expression Language, Custom Tags,
etc.
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the
features of the Servlet in JSP. In addition to, we can use implicit objects,
predefined tags, expression language and Custom tags in JSP, that makes JSP
development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic
with presentation logic. In Servlet technology, we mix our business logic with
the presentation logic.
If JSP page is modified, we don't need to recompile and redeploy the project.
The Servlet code needs to be updated and recompiled if we have to change
the look and feel of the application.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page
The JSP pages follow these phases:
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the
help of JSP translator. The JSP translator is a part of the web server which is
responsible for translating the JSP page into Servlet. After that, Servlet page is
compiled by the compiler and gets converted into the class file. Moreover, all
the processes that happen in Servlet are performed on JSP later like
initialization, committing response to the browser and destroy.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put
Java code in the JSP page. We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
Problem with servlet
JSP is slower than Servlet because the first step in JSP lifecycle is the
translation of JSP to java code and then compile. Servlet can accept all
protocol requests. JSP only accepts HTTP requests. In Servlet, we can
override the service() method.
Advantages of JSP
Here are the advantages of using JSP:
Disadvantages of JSP
Here are the disadvantages for using JSP:
When a JSP page request is processed, the template text and the
dynamic content generated by the JSP elements are merged, and the
result is sent as the response to the browser.
JSP Elements
There are three types of elements with JavaServer
Pages: directive, action, and scripting elements.
The directive elements, shown in Table 3.1, are used to specify
information about the page itself that remains the same between
page requests, for example, the scripting language used in the page,
whether session tracking is required, and the name of a page that
should be used to report errors, if any.
Jsp aschitecture
The web server needs a JSP engine, i.e, a container to process JSP pages.
The JSP container is responsible for intercepting requests for JSP pages. This
tutorial makes use of Apache which has built-in JSP container to support JSP
pages development.
A JSP container works with the Web server to provide the runtime
environment and other services a JSP needs. It knows how to understand the
special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web
application.
JSP Processing
The following steps explain how the web server creates the Webpage using
JSP −
As with a normal page, your browser sends an HTTP request to the web
server.
The web server recognizes that the HTTP request is for a JSP page and
forwards it to a JSP engine. This is done by using the URL or JSP page
which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a
servlet content. This conversion is very simple in which all template text
is converted to println( ) statements and all JSP elements are converted
to Java code. This code implements the corresponding dynamic
behavior of the page.
The JSP engine compiles the servlet into an executable class and
forwards the original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class
and executes it. During execution, the servlet produces an output in
HTML format. The output is furthur passed on to the web server by the
servlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms
of static HTML content.
Finally, the web browser handles the dynamically-generated HTML
page inside the HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file
already exists and whether the modification date on the JSP is older than the
servlet. If the JSP is older than its generated servlet, the JSP container
assumes that the JSP hasn't changed and that the generated servlet still
matches the JSP's contents. This makes the process more efficient than with
the other scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without
having to be a Java programming wiz. Except for the translation phase, a JSP
page is handled exactly like a regular servlet.
What is MVC?
MVC stands for Model-View-Controller. It is a design pattern used for developing
web applications. It is a layout pattern used to isolate the information, presentation
logic, business logic. Web application Logic is divided into three logics:
1. Presentation Logic
2. Business Logic
3. Persistent Logic
Each one is called Model or Tier. MVC is popular because it isolates the appliance
logic from the interface layer and supports the separation of concerns. Here the
Controller receives all requests for the appliance then works with the Model to
organize any data needed by the View. The View then uses the information
prepared by the Controller to get a final presentable response. The MVC abstraction
is often graphically represented as follows.
Jsp setup
This is probably the first thing you must do to work under Java supported
tools and technologies. The steps are as follows:
What is Tomcat?
It is an open-source Java servlet container that implements many Java
Enterprise Specs such as the Websites API, Java-Server Pages and last but not
least, the Java Servlet. The complete name of Tomcat is "Apache Tomcat" it
was developed in an open, participatory environment and released in 1998 for
the very first time. It began as the reference implementation for the very first
Java-Server Pages and the Java Servlet API.
A web- server is a kind of server designed to serve files using a local system
such as Apache.
We can say that, at the center, the Tomcat is JSP (Java Server Pages) and
Servlet. The JSP is one of the server-side programming technologies that
enables the developers to create platform-independent dynamic content and
also known as the server-side view rendering technology. A servlet is a java-
based software component that helps in extending the capabilities of a server.
However, it can also respond to several kinds of requests and generally
implemented web server containers to host the web-applications on the
webservers. As the developer's point of view, we just have to write the java
server pages (or JSP) or the servlet and not required to worry about routing;
the Tomcat will handle the routing.
Advantages of Tomcat:
Some significant advantages of Tomcat are as follows:
o It is open-source
It means anyone from anywhere can download, install, and use it free of
cost, which makes it the first choice among the new developers and new
users.
o Incredibly Lightweight
It is actually a very light application, even with the JavaEE's certification.
However, it provides all necessary and standard functionalities required
to operate a server, which means it gives very fast load and redeploys as
compared to its various alternatives.
Yes, it is right that it does not offer so many features in case you want a
number of features, it might be good for you, but if you want to have an
easy and fast means in order to run your application, it is the best
option for you.
o Highly flexible
Due to its built-in customization options, extensive and lightweight
nature, it offers high flexibility, a user can run it in any fashion he wants,
and it will still work as fine without any issues. Since it is open-source,
anyone who has knowledge can tweak it according to his requirements.
o Stability
It is one of the most stable platforms available today to build on and
using it to run our applications. It is incredibly stable because it runs
independently of our Apache installation. In case if there is a big failure
in Tomcat due to which it to stop working, the rest of our server would
run just well.
o It provides us an extra level of security
As the several organizations usually like to position their Tomcat's
installation behind the protection of an extra firewall which can be
accessible only from the Apache installation.
o It is well documented
It has several excellent documentation available, including a vast range
of freely available online tutorials that can be downloaded or viewed
directly online by the user, which makes it one of the best choices to fill
the requirement of an application server in mostly every java web-
application.Whether a user is looking for the installation instructions,
startup settings, server configuration notes, all kind of information about
the Tomcat is already available on the internet.
o It is one of the most widely used application servers
According to an estimation, it holds almost 60 percent of the market
share almost all java application server deployments, which makes it one
of the most popular application servers used for java web-based
applications. However, we cannot say that it implements all of the
features required for a JavaEE application server; instead, it enables us to
run Java EE application.
Tomcat acts as a "webserver" or "servlet container." However, there is a
plethora of terminology for anything.
o It's mature
We take a look back in the past; we will find that it has existed for
almost 20 years, which is quite a significant time, in which it gets mature
over time passage. Since the Tomcat is open-source software, it's
updated, and new releases come out nearly on a regular basis, and the
open-source community maintains it. The maturity makes it one of the
most extremely stable application servers for the development of
software, applications, and deploying java applications. Since now, it is
extremely a stable option that becomes more powerful with excellent
community support.
finish
Unit-4 Javascript
Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based applications.
JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases. This tutorial will teach you how to use Java Server Pages to
develop your web applications in simple and easy steps.
Applications of JSP
As mentioned before, JSP is one of the most widely used language over the web. I'm
going to list few of them here:
JSP vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.
JSP vs. Pure Servlets
It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
JSP vs. Server-Side Includes (SSI)
SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.
JSP vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.
JSP vs. Static HTML
Regular HTML, of course, cannot contain dynamic information.
You can access a variety of objects, including enterprise beans and JavaBeans components,
within a JSP page. JSP technology automatically makes some objects available, and you can also
create and access application-specific objects.
Implicit Objects
Implicit objects are created by the Web container and contain information related to a particular
request, page, or application. Many of the objects are defined by the Java Servlet technology
underlying JSP technology and are discussed at length in . Table 13-2 summarizes the implicit
objects.
Application-Specific Objects
Instance and class variables of the JSP page's servlet class are
created in declarations and accessed
in scriptlets and expressions.
Local variables of the JSP page's servlet class are created and
used in scriptlets and expressions.
Attributes of scope objects (see Using Scope Objects) are created
and used in scriptlets and expressions.
JavaBeans components can be created and accessed using
streamlined JSP elements. These elements are discussed in the
chapter JavaBeans Components in JSP Pages. You can also create
a JavaBeans component in a declaration or scriptlet and invoke
the methods of a JavaBeans component in a scriptlet or
expression.
Shared Objects
When isThreadSafe is set to true, the Web container may choose to dispatch multiple
concurrent client requests to the JSP page. This is the default setting. If using true,
you must ensure that you properly synchronize access to any shared objects defined at
the page level. This includes objects created within declarations, JavaBeans
components with page scope, and attributes of the page scope object.
If isThreadSafe is set to false, requests are dispatched one at a time, in the order they
were received, and access to page level objects does not have to be controlled.
However, you still must ensure that access to attributes of
the application or session scope objects and to JavaBeans components with
application or session scope is properly synchronized.
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the
scripting elements first.
o scriptlet tag
o expression tag
o declaration tag
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files index.html and welcome.jsp. The index.html
file gets the username from the user and the welcome.jsp file prints the username with
the welcome message.
File: index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
For writing any data to the buffer, JSP provides an implicit object named out. It is the
object of JspWriter. In case of servlet you need to write:
1. PrintWriter out=response.getWriter();
index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Output
Conditional Processing
In most web applications, you produce different output based on runtime
conditions, such as the state of a bean or the value of a request header such
as UserAgent (containing information about the type of client that is accessing
the page).
If the differences are not too great, you can use JSP scripting elements to
control which parts of the JSP page are sent to the browser, generating
alternative outputs from the same JSP page. However, if the outputs are
completely different, I recommend using a separate JSP page for each
alternative and passing control from one page to another. This chapter
contains a number of examples in which one page is used. In the remainder of
this book you’ll see plenty of examples where multiple pages are used
instead.
...
This bean has a property named entryTime that holds a timestamp for a log
entry, while other properties hold the information to be logged. To set the
timestamp to the time when the JSP page is requested,
a <jsp:setProperty> action with a request-time attribute value is used.
The exception is normally an object that is thrown at runtime. Exception Handling is the
process to handle the runtime errors. There may occur exception any time in your web
application. So handling exceptions is a safer side for the web developer. In JSP, there
are two ways to perform exception handling:
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
You can use the debugger to detect and diagnose errors in your application. You can control the
execution of your program by setting breakpoints, suspending threads, stepping through the code, and
examining the contents of the variables. You can debug a JavaServer Page (JSP) without losing the
state of your application.
Procedure
1. In the Project Explorer view, open your JSP file. In a Web project, JSP files are located in the
Web Content folder. Double-click the JSP file, the file opens in an editor.
2.
a. Verify that you are using the Source page of the editor. If multiple pages are available
for the editor, such as Design, Source, or Preview page, select the Source page on the
bottom of the editor. If multiple pages are not available, the editor defaults to a source
editor.
b. Select a line of code in the editor and double-click where you want to add the
breakpoint in blue area of the marker bar directly to the left of the line of code.
3. From the JSP file's context menu in the Project Explorer view, click Debug As> Debug on
Server. The workbench switches to the Debug perspective and the server is launched in debug
mode.
4. In the Debug view, step through the code and make the necessary changes to the JSP file. For
detailed information on debugging, refer to the Debugging Java™ applications documentation.
5. Save the JSP file.
6. Click the Refresh icon in the Web Browser to update the changes. The state of your application
is not lost and the server recognizes your changes.
In this section we look at how to separate the different aspects in a pure JSP
application, using a modified version of the User Info example from Chapter
8 as a concrete example. In this application, the business logic piece is trivial.
However, it sets the stage for a more advanced application example in the
next section and the remaining chapters in this part of the book; all of them
use the pattern introduced here.
The different aspects of the User Info example can be categorized like this:
Imagine a travel agency application. It’s important to remember the dates and
destination entered to book the flight so that the customer doesn’t have to
reenter the information when it’s time to make hotel and rental car
reservations. This type of information, available only to requests from the
same user, can be shared through the session scope.
Figure 10-4 shows how the server provides access to the two scopes for
different clients.
Introduction and Working of Struts Web Framework
Last Updated : 28 Jan, 2020
Struts is used to create a web applications based on servlet and JSP. Struts depend on the
MVC (Model View Controller) framework. Struts application is a genuine web
application. Struts are thoroughly useful in building J2EE (Java 2 Platform, Enterprise
Edition) applications because struts takes advantage of J2EE design patterns. Struts
follows these J2EE design patterns including MVC.
In struts, the composite view manages the layout of its sub-views and can implement a
template, making persistent look and feel easier to achieve and customize across the
entire application. A composite view is made up by using other reusable sub views such
that a small change happens in a sub-view is automatically updated in every composite
view.
Struts consists of a set of own custom tag libraries. Struts are based on MVC framework
which is pattern oriented and includes JSP custom tag libraries. Struts also supports
utility classes.
Features of Struts: Struts has the following features:
Struts encourages good design practices and modeling because the framework is
designed with “time-proven” design patterns.
Struts is almost simple, so easy to learn and use.
It supports many convenient features such as input validation and internationalization.
It takes much of the complexity out as instead of building your own MVC framework,
you can use struts.
Struts is very well integrated with J2EE.
Struts has large user community.
It is flexible and extensible, it is easy for the existing web applications to adapt the
struts framework.
Struts provide good tag libraries.
It allows capturing input form data into javabean objects called Action forms.
It also hand over standard error handling both programmatically and declaratively.