Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 101

J2EE

Presented By
Ardent Computech Pvt Ltd
HTML OVERVIEW
Introduction to HTML
The Problem

 Universally computer Understandable language to publish information


for global distribution.

The Solution:

 HTML - Stands for Hyper Text Markup Language.


 Special text documents used by web browsers to present text and
graphics.
Features of HTML
HTML helps to:
 Publish online documents with headings, text, tables,
lists, photos, etc.
 Retrieve online information via hypertext links, at the
click of a button.
 Design forms for conducting transactions with remote
services, for use in searching for information, making
reservations, ordering products, etc.
 Include spread-sheets, video clips, sound clips, and
other applications directly in their documents.
HTML Tag
HTML tag is a markup and identifies a page element's
type, format, and
appearance.

All HTML tags are enclosed in brackets (i.e. <table> ).

Some tags require closing tags.


Types of HTML tag
1. Layout Tags 3. Application Tags
 Basic Tags – Forms
 Structural Tags – Tables
– Frames

2. Semantic Tags
 Presentation Tags 4. Logical Tags
 Links & Graphics – Emphasized Tag
 List – Strong Tag
 Dividers – Code Tag
 Backgrounds and Colors
 Special Characters
Layout Tag
Layout tags define the layout of the WEB Page and define what text
goes where and is displayed where.

BASIC Tags:
<HTML></HTML> Defines Start and end of Web page
<HEAD></HEAD> Defines the Header section of the Web Page

<TITLE></TITLE> Defines the Title of the web page displayed on the title bar

<BODY></BODY> Defines the body / content of the page.

STRUCTURAL Tags:
<H?></H?> Heading tags. ‘?’ Ranges from 1 to 6, defines heading

<PRE></PRE>Preformatted Text
Semantic Tag
1. Presentation Tags
2. Links & Graphics
3. Lists
4. Dividers
5. Backgrounds and Colors
6. Special Characters
Semantic Tag: Presentation Tags
Bold <B>Text</B> Superscript <SUP></SUP>

Italic <I>Text</I> Subscript <SUB></SUB>

Underline <U>Text</U> Typewriter <TT></TT>

FONT SETTINGS:
<FONT
SIZE=“12 / + / - ” Attribute set
COLOR=“#FFOO00”
FACE=“Times” >
</FONT>
Semantic Tag: Links and Graphics
Anchor: <A>
An anchor can be used to create a link to another
document (with the href attribute) or to create a
bookmark inside a document (with the name
attribute).
Syntax:
<A HREF=“URL”>Display Text</A>
Links and Graphics (Contd..)
Image:
<IMG SRC=“URL” ALT=“Alternate Text”>

Example:
<IMG SRC=“\images\wipro.jpg”
ALT=“Alternate Text”>
Semantic Tag: List
Semantic tags provide the Author with feature of
displaying text in
hierarchical or tree structure format.

Three types of List are available:


Glossary List
Unordered List
Ordered List
List: Glossary List
Glossary list is used to display a list of alternating term
with definition
paragraphs.
DL  Definition List, DT  Term, DD  Data
Example:
<DL>
<DT>Coffee</DT>
<DD>Black hot drink</DD>
</DL>
Output:
Coffee
Black hot drink
List: Ordered List
An ordered list is a list of items. The list items are marked with
numbers.
Example:
<OL TYPE=“A”>
<LI>Country</LI>
<OL TYPE=“1”>
<LI>India</LI>
</OL>
</OL>

Output:
A. Country
1. India
List: Un-Ordered List
An unordered list is a list of items. The list items are marked with
bullets.

Example:
<UL TYPE=“Square / Circle / Disc”>
<LI>Country</LI>
<UL TYPE=“”>
<LI>India</LI>
</UL>
</UL>
Semantic Tag: Dividers
Paragraph:
<p align=“Left/center/right/justify”>Text</p>

LineBreak:

<BR/> gives a single carriage return.

Horizontal Rule:

<HR ALIGN=“left/center/right” SIZE=“” WIDTH=“”


color=“”/>
Semantic Tag: Background and
Color
To change background Image
<BODY BACKGROUND=“URL”>

To change background color


<BODY BGCOLOR= “COLOR” >
Semantic Tag: Special characters
Syntax:
&#char code; or &code;

Example:
< &lt;
> &gt;
& &amp;
“ &quot;
Registered Trade mark &#174; or &reg;
Copyright &#169; or &copy;
Non-Breaking space &nbsp;
Application Tags
1. Table
2. Form
3. Frames
Application Tags: Tables
Tags Purpose

<TABLE> Begins the table definition


<TR> Defines a new row
<TD> Defines a single cell

<TH> Defines header cell


Tables: Tables Attribute
ALIGNMENT Left / center / right

BORDER Defines the border

WIDTH Defines the width of the table

CELLSPACING Space between the cells

CELLPADDING Space between the text and cell


border

 EXAMPLE:

 <TABLE ALIGNMENT=“center” BORDER=“0”


WIDTH=“100%” CELLSPACING=“2”
CELLPADDING=“4”>
Tables: Merging cells
1. ROWSPAN
Used to merge cells in rows
<TD ROWSPAN=“2”> two cells in consecutive
columns are merged

2. COLSPAN
Used to merge cells in Columns
<TD COLSPAN=“2”> two cells in consecutive
rows are merged
Application tags: Forms
Mode of accepting input from user

Container: Form
<FORM NAME=“” ACTION=“” METHOD=“”></FORM>

Components: Form Elements


 These are the data fields in the form, such as text fields and checkboxes.
 The <INPUT> tag can be used to create:
 Text boxes - Radio buttons
 Check boxes- Submit buttons
 Reset buttons - Password
 Generic buttons

 There are other tags like TEXTAREA and SELECT for other purposes.
Forms: Input tags
Input tag is a single tag option for gathering information

Input tag contains all of the other options for acquiring information,
including simple text fields, password fields, radio buttons, check
boxes, and the buttons to submit and reset the form.
<INPUT TYPE = “ * ” > * can take the following values:

Text TextField

Radio Radio Button

Checkbox Checkbox

Password Password TextField


Input Tags: Text Area
<TEXTAREA NAME=“” ROWS=“” COLS=“”>

Text to be displayed in the Text Area


</TEXTAREA>

EXAMPLE:

<TEXTAREA NAME="addressbox" ROWS="5" COLS="20 “align="center">

This is an example for multilined text box (TEXTAREA)

</TEXTAREA>
select
Select is used to display list box.
<SELECT NAME=“” MULTIPLE>
<OPTION VALUE=“taken value”>Display text</OPTION>
</SELECT>

EXAMPLE:
<select name="locations" align="center">
<option value="EC1">EC1</option>
<option value="EC2">EC2</option>
<option value="EC3">EC3</option>
<option value="EC4">EC4</option>
</select>
Application Tags: Frames
<FRAMESET COLS="25%,*">
<FRAME SRC=“left.htm“ NAME=“left”>
<FRAME SRC=“right.htm“
NAME=“right”>
</FRAMESET>
Frames (Contd..)
<FRAMESET COLS="25%,*">
<FRAME SRC=“top.htm“
NAME=“header”>
<FRAME SRC=“body.htm“
NAME=“body”>
</FRAMESET>
Nested Frames
<FRAMESET ROWS="25%,75%">
<FRAME SRC="top.htm" NAME="left"/>
<FRAMESET COLS="25%,75%">
<FRAME SRC="left.htm"
NAME="left"/>
<FRAME SRC="right.htm"
NAME="right"/>
</FRAMESET>
</FRAMESET>
SERVLET
Introduction to Servlet

31
Introduction to Servlet: Static Web Site

HTTP Server
HTML HTTP

<HTML>
Aruba
Bermuda
Bahamas
</HTML>

Source: http://www.myvacation.com/ListDest.htm
32
Dynamic Page Generation Using CGI

ODBC / Native
HTTP Server
HTML HTTP CGI
Application

<HTML>
Aruba
Bermuda
Bahamas
</HTML>

Source: http://www.myvacation.com/cgi/ListDest.exe
33
Dynamic Page Generation Using
Servlets

HTTP Server
Servlet

JDBC
HTML HTTP
Container

<HTML>
Aruba
Bermuda
Bahamas
</HTML>

Source: http://www.myvacation.com/servlet/ListDest.htm
34
What is a Servlet?
Server side Java program that extends the functionality
of a Web Server
Used to dynamically generate HTML documents
Comparable to:
 CGI
 Netscape NSAPI
 Microsoft ISAPI
 Apache Modules

35
Servlet: Benefits
Written in pure Java
 Platform independent
 Can take advantage of JDBC, EJB, JMS, JavaMail, JavaIDL, RMI, ...

Server independent
Scalability
 Don’t start new process for each request
 Can run in same server process as HTTP server
 Multi-threaded

36
Servlet: Advantages over CGI
A Servlet does not run in a seperate process

A Servlet stays in memory between requests

There is only a single instance which answers all


requests concurrently

37
Servlet Life Cycle
Servlets Container

Thread
HTTP Server init( )
doGet( )
Thread

Servlet

Thread
38
Servlet Life Cycle (Contd.).
Servlets Container

Thread
HTTP Server init( )
doGet( )

Servlet

Thread
39
Servlet Life Cycle (Contd.).
Servlets Container

HTTP Server init( )


doGet( )

Servlet

Thread
40
Servlet Life Cycle (Contd.).
Servlets Container

HTTP Server init( )


doGet( )
destroy( )

Servlet

41
Servlet Life Cycle (Contd.).
Servlets Container

HTTP Server

42
Class Hierarchy
Uses of HTTP Servlets
Processing and/or storing data submitted by an HTML
form

Providing dynamic content

Managing state information

45
The init() Method
public void init(ServletConfig) throws ServletException

This method is for initialization of the servlet

One can establish database connection in this method


which could be shared by every client

This method is called only once during the life of a


servlet

46
The service() Method
public void Service(ServletRequest,
ServletResponse) throws
ServletException, IOException

This method is called once per client.

47
The destroy() Method
public void destroy()

Called to destroy the servlet and release the resources

Usually called by the Servlet Container

Called once during the life of a servlet

48
Handling HTTP GET requests
Override the doGet method.

Takes two arguments:


 An HttpServletRequest object, which encapsulates the data from the client
 An HttpServletResponse object, which encapsulates the response to the
client

49
Reading Servlet Parameters
The ServletRequest class includes methods that allow
you to read the names and values of parameters that
are included in a client request.
Methods used are
 getParameterNames()
 getParameter(String pname)
 getParameterValues(String pname)

50
The servlet Interface
A servlet is Java class that implements the
javax.servlet.Servlet interface

 This interface defines only five methods:


 service()
 init()
 getServletConfig()
 destroy()
 getServletInfo()

51
ServletConfig Interface
Is implemented by Servlet container in order to pass
configuration information

Interface defines following methods


 getServletContext()
 getInitParameter ()
 getInitParameterNames ()
 getServletName()

52
ServletContext Interface
 Gives servlets access to information about their
environment

 Allows them to log significant events

 Servlet authors decide what data to log

 Methods:
 getServerInfo()
 getAttribute(String name)
 getAttributeNames()
 setAttribute(String name, Object obj)
 log(String)

53
Servlet Chaining: RequestDispatcher
Interface
In order to FORWARD or INCLUDE a request from one
servlet to another Servlet/JSP the RequestDispatcher
interface provides two methods.

1. RequestDispatcher.forward(request,response)
2. RequestDispatcher.include(request,response)

Both these methods takes ServletRequest and


ServletResponse object as an argument.

54
Servlet Chaining:
forward(request,response)

ServletContext ctx=getServletContext();
RequestDispatcher
dis=ctx.getRequestDispatcher(“/servlet/AnotherServlet”);
dis.forward(request,response);

55
Servlet Chaining: forward (request ,
response);
Client Request Request passing

Client Servlet1 Servlet2

Response Generation

56
Servlet Chaining: include(request,
response)

ServletContext ctx=getServletContext();
RequestDispatcher
dis=ctx.getRequestDispatcher(“/servlet/AnotherServlet
”);
dis.include(request,response);
57
Servlet Chaining: include (request ,
response);

Client Request Request Passing

Client Servlet1 Servlet2

Response Generation Output back to the


Requester

58
Servlet Chaining: sendRedirect(url);

WEB CONTAINER

REQUE
ST ST
UE
REQ Http Servlet 1

RESPONSE

REQ
UE
ST

RESP
ONSE
Http Servlet 2
RESPONSE
The Cookie Class
 Cookie is a small amount of information sent by the server to the web
browser, saved by the web browser and later send back to the server. A
cookies value can uniquely identify a client, so cookies are commonly
used for session management.
 A cookie has a name, a single value and an optional attribute such as a
comment, a maximum age etc.
 The servlet sends cookies to the browser by using the
HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which
adds fields to HTTP response headers to send cookies to the browser,
one at a time.
 The browser is expected to support 20 cookies for each Web server,
300 cookies total, and may limit cookie size to 4 KB each.
SESSION TRACKING
What is Session Tracking
 HTTP is a “stateless” protocol: each time a client
retrieves a Web page, it opens a separate connection
to the Web server, and the server does not
automatically maintain contextual information about
a client.
 Session tracking is a mechanism that servlet use to
maintain state about a series of request from the same
user (i.e. requests originating from the same browser)
across some period of time.
Session Tracking API
Sessions are represented by an HttpSession object

We access session by calling the getSession().- that


returns the current session associted with this request
or, if the request does not have a session, it creates
one.
Methods available in HttpSession
Class
 public Object getAttribute(String name):- extracts
a previously stored value from a session object.
 public void setAttribute(String name, object
value):- associates a value with the name
 public void removeAttribute(String name):-
removes any value associated with the designated
name
 public void invalidate():- invalidates the session and
unbinds all objects associated with it
Ways of Session Tracking
Get the session (an HttpSession object) for a user
Looking up information associated with a session
Store or get data from the HttpSession object
Discarding the session
Folder Architecture for Web-Application

WebApplicationName

WEB-INF HTML and JSP files

web.xml lib classes

jar files java classes


Java Server Page
Introduction
JSP stands for Java Server Page which is an
extension/wrapper over the servlet technology.
JSP are text based documents enables us to mix
regular, static HTML with dynamically generated
content.
The Architecture
Flow of JSP request
Methods of generated Servlet class
Generated Servlet equivalent Class has following Methods:
jspInit() :
The container calls the jspInit() to initialize the servlet instance. It is
called before any other method, and is called only once for a servlet
instance.

_jspservice():
The container calls this method for each request, passing it the request
and response object.

jspDestroy() :
The container calls this when it decides and take the instance out of
service. It is the last method called in the servlet instance.
Various JSP Contents
HTML code: for user interface lay out
JSP tags: declarations, actions, directives,
expressions, scriplets
JSP implicit objects: a request object, response
object, session object, config object
Javabeans: for logic that can be taken care of at the
JSP level.
JSP Tags
JSP Comment
Developer comment that is not sent to the client
 Example:
 <%-- Start of JSP --%>

JSP Expression
Expression that is evaluated and sent to the client each
time the page is requested
 Example:
 <%= Java Value %>
 <%= Java Expression %>
JSP Tags (Contd..)
JSP Scriptlet
Statement or statements that are executed each time the
page is requested
 Example:
 <% Java Statement %>

JSP Declaration
Field or method that becomes part of class definition
when page is translated into a servlet
 Examples:
 <%! Field Definition %>
 <%! Method Definition %>
JSP Tags (Contd..)
JSP Directive
Directives are JSP elements that provide global information
about an entire JSP page. Declarative do not produce any
visible output when the page is requested, but change the way
the jsp engine process the request.
 Example:
 <%@ directive att="val" %>
 <%@ page language=“java”%>

JSP Action
Action that takes place when the page is requested
 Example:
 <jsp:action_name>...</jsp:action_name>
JSP Tags (Contd..)
Some commonly used tag actions types are:
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:include>
<jsp:forward>
Predefined Variables
request, the HttpServletRequest.
response, the HttpServletResponse.
session, the HttpSession associated with the
request
out, this is a PrintWriter used to send output to the
client.
Exception, exception represents the uncaught
Throwable that resulted from a call to the error page.
The errorPage and isErrorPage attribute
The errorPage attribute specifies a JSP page that
should process any exceptions thrown but not
caught in the current page. It is used as follows:

<%@ page errorPage="Relative URL" %>

The exception thrown will automatically be


available to the designated error page by means of
the exception variable.
The errorPage and isErrorPage attribute
The isErrorPage attribute indicates whether or not the
current page can act as the error page for another JSP
page. Use of isErrorPage takes one of the following
two forms:

<%@ page isErrorPage="true" %>


<%@ page isErrorPage="false" %>
JSP file inclusion
The jsp:include action. The jsp:include action include
the output of a page at request time.

The include directive. This construct insert JSP code


into the main page before that main page is translated
into a servlet.
Java Beans
Beans are simply Java classes that are
written in a standard format.
Why beans?
 No Java syntax
 By using beans, page authors can manipulate Java objects using
only XML-compatible syntax: no parentheses, semicolons, or curly
braces.
 Simpler object sharing
 When you use the JSP bean constructs, you can much more easily
share objects among multiple pages or between requests than if you
use the equivalent explicit Java code.
 Convenient correspondence between request
parameters and object properties
 The JSP bean constructs greatly simplify the process of reading
request parameters, converting from strings, and putting the results
inside objects.
Contents of a bean
A bean class must have a zero-argument (default)
constructor.
A bean class should have no public instance variables
(fields).
Persistent values should be accessed through methods
called getXxx() and setXxx().
Using beans
jsp:useBean - In the simplest case, this element builds
a new bean. It is normally used as follows:
<jsp:useBean id="beanName“ class="package.Class" />
Using beans (Contd..)
jsp:getProperty - This element reads and outputs the
value of a bean property. Reading a property is a
shorthand notation for calling a method of the form
getXxx. This element is used as follows:
<jsp:getProperty name="beanName“
property="propertyName" />
Using beans (Contd..)
jsp:setProperty - This element modifies a bean
property (i.e., calls a method of the form setXxx). It is
normally used as follows:
<jsp:setProperty name="beanName“
property="propertyName“ value="propertyValue" />
Sharing beans
Although the beans are indeed bound to local variables
they are also stored in one of four different locations,
depending on the value of the optional scope attribute
of jsp:useBean.
When we use scope, the system first looks for an
existing bean of the specified name in the designated
location. Only when the system fails to find a
preexisting bean does it create a new one.
scope Attribute
scope attribute has four possible values:
page (the default)
 <jsp:useBean ... scope="page" />
request
 <jsp:useBean ... scope="request" />
session
 <jsp:useBean ... scope="session" />
application
 <jsp:useBean ... scope="application" />
MVC
Model View Controller pattern overview
Splits up responsibilities for handling user interactions
in an application into three layers:
 Model, View, Controller
MVC Controller pattern details
Model
 holds application data and business logic
 is absolutely independent from the UIs
View
 presentation of parts of the Model to the user
 independent from the internal implementation of the Model
 there can be different Views presenting the same Model data
Controller
 “bridge” between Model and View
 controls the flow of the application
 receives/interprets user input
 performs operations on the Model
 triggers View update
Benefits of MVC
better maintainability and testability of applications
ability to easily develop different kinds of UIs (e.g.
console, GUI, …)
separation of different tasks in development
code reusability
MVC Steps
1. Define beans to represent the data
 The first step is to define beans to represent the results
that will be presented to the user.
2. Use a servlet to handle requests
 In most cases, the servlet reads request parameters
3. Populate the beans
 The servlet invokes business logic (application
specific code) or data-access code to obtain the
results. The results are placed in the beans that were
defined in step 1.
MVC Steps
4. Store the bean in the request, session, or
servlet context.
 The servlet calls setAttribute on the request, session,
or servlet context objects to store a reference to the
beans that represent the results of the request.
5. Forward the request to a JSP page.
 The servlet determines which JSP page is appropriate
to the situation and uses the forward method of
RequestDispatcher to transfer control to that page.
MVC Steps
6. Extract the data from the beans.
 The JSP page accesses beans with jsp:useBean and a
scope matching the location of step 4. The page then
uses jsp:getProperty to output the bean properties.
The JSP page does not create or modify the bean; it
merely extracts and displays data that the servlet
created.
Define bean
public class MyBean
{
private int no;
public MyBean()
{}

public int getNo() {


return no;
}

public void setNo(int no) {


this.no = no;
}
}
Servlet to handle request
public class MVCServ extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException,
IOException
{
int x =
Integer.parseInt(req.getParameter("t1"))
;
....
Populate bean
public class MVCServ extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException,
IOException
{
....
MyBean mb=new MyBean();
mb.setNo(x);
....
Storing bean in some context
public class MVCServ extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException,
IOException
{
....
HttpSession
hs=req.getSession(true);
hs.setAttribute(“obj”,mb);
....
Forward request to a JSP
public class MVCServ extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse res)throws ServletException,
IOException
{
....
RequestDispatcher rd =
req.getRequestDispatcher("MyView.jsp");
rd.forward(req, res);
....
Extract data from bean in JSP
<jsp:useBean id="obj" class="MyBean"
scope="session"/>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<h2>
Entered Number: <jsp:getProperty
name=“obj”
property=“no”/>
</h2>
</body>
</html>

You might also like