0% found this document useful (0 votes)
115 views

Unit 4 Web Programming

This document provides an overview of key topics in web programming including HTML, JavaScript, MVC architecture, JSP, JDBC with MongoDB, Ajax, and Ajax frameworks. It covers HTML elements, tags, and attributes. It also discusses JavaScript programming, embedding scripts in HTML, and using the MVC pattern to separate application logic from presentation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Unit 4 Web Programming

This document provides an overview of key topics in web programming including HTML, JavaScript, MVC architecture, JSP, JDBC with MongoDB, Ajax, and Ajax frameworks. It covers HTML elements, tags, and attributes. It also discusses JavaScript programming, embedding scripts in HTML, and using the MVC pattern to separate application logic from presentation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 184

Unit No: 4 Web Programming

Pavan R Jaiswal
 HTML
 JavaScript programming
 MVC architecture models
 JSP, JSP over servlet
 JDBC process with MongoDB
 Ajax
 Ajax frameworks

Web Programming 10/12/2015 2


Web Programming 10/12/2015 3
 Web pages are text files containing HTML
 HTML – Hyper Text Markup Language
◦ A notation for describing
 document structure (semantic markup)
 formatting (presentation markup)
◦ Looks (looked?) like:
 A Microsoft Word document
 The markup tags provide information about
the page content structure

Web Programming 10/12/2015


4
 An HTML file must have an .htm or .html file
extension
 HTML files can be created with text editors:
◦ NotePad, NotePad ++, PSPad
 Or HTML editors (WYSIWYG Editors):
◦ Microsoft FrontPage
◦ Macromedia Dreamweaver
◦ Netscape Composer
◦ Microsoft Word
◦ Visual Studio

Web Programming 10/12/2015


5
 HTML is comprised of “elements” and “tags”
◦ Begins with <html> and ends with </html>
 Elements (tags) are nested one inside another:

 Tags have attributes:


<html> <head></head> <body></body> </html>
 HTML describes structure using two main
sections: <head> and <body>
<img src="logo.jpg" alt="logo" />

Web Programming 6
10/12/2015
 The HTML source code should be formatted
to increase readability and facilitate
debugging.
◦ Every block element should start on a new
line.
◦ Every nested (block) element should be
indented.
◦ Browsers ignore multiple whitespaces in the
page source, so formatting is harmless.
 For performance reasons, formatting can be
sacrificed

Web Programming 10/12/2015


7
test.html
<!DOCTYPE HTML>
<html>
<head>
<title>My First HTML Page</title>
</head>
<body>
<p>This is some text...</p>
</body>
</html>

Web Programming 8
10/12/2015
<!DOCTYPE HTML>
<html> Opening
<head>
tag
<title>My First HTML Page</title>
</head>
<body> Closing
<p>This is some text...</p> tag
</body>
</html>

An HTML element consists of an opening tag, a closing tag and the content
inside.

Web Programming 9
10/12/2015
<!DOCTYPE HTML>
HTML
<html>
header
<head>
<title>My First HTML Page</title>
</head>
<body>
<p>This is some text...</p>
</body>
</html>

Web Programming 10
10/12/2015
<!DOCTYPE HTML>
<html>
<head>
<title>My First HTML Page</title>
</head>
<body>
<p>This is some text...</p>
</body>
</html>
HTML body

Web Programming 11
10/12/2015
 Hyperlink tags
<a href="http://www.pavanjaiswal.com/"
title=“Blog">Link to personal web site</a>
 Image tags
<img src="logo.gif" alt="logo" />
 Text formatting tags
This text is <em>emphasized.</em>
<br />new line<br />
This one is <strong>more emphasized.</strong>

Web Programming 12
10/12/2015
some-tags.html
<!DOCTYPE HTML>
<html>
<head>
<title>Simple Tags Demo</title>
</head>
<body>
<a href="http://www.pavanjaiswal.com/" title=
“Blog">This is a link.</a>
<br />
<img src="logo.gif" alt="logo" />
<br />
<strong>Bold</strong> and <em>italic</em> text.
</body>
</html>

Web Programming 13
10/12/2015
some-tags.html
<!DOCTYPE HTML>
<html>
<head>
<title>Simple Tags Demo</title>
</head>
<body>
<a href="http://www.pavanjaiswal.com/" title=
“Blog">This is a link.</a>
<br />
<img src="logo.gif" alt="logo" />
<br />
<strong>Bold</strong> and <em>italic</em> text.
</body>
</html>

Web Programming 14
10/12/2015
 Tags can have attributes
◦ Attributes specify properties and behavior
◦ Example:
◦ Few attributes can apply to every element:
 id, style, class, title
 The id is unique in the document
 Content of title attribute is displayed as hint when the
element is hovered with the mouse
 Some elements have obligatory attributes
Attribute alt with value
"logo"

<img src="logo.gif" alt="logo" />

Web Programming 15
10/12/2015
 Heading Tags (h1 – h6)
<h1>Heading 1</h1>
<h2>Sub heading 2</h2>
<h3>Sub heading 3</h3>
 Paragraph Tags
<p>This is my first paragraph</p>
<p>This is my second paragraph</p>
 Sections: div and span
<div style="background: skyblue;">
This is a div</div>

Web Programming 16
10/12/2015
headings.html
<!DOCTYPE HTML>
<html>
<head><title>Headings and paragraphs</title></head>
<body>
<h1>Heading 1</h1>
<h2>Sub heading 2</h2>
<h3>Sub heading 3</h3>

<p>This is my first paragraph</p>


<p>This is my second paragraph</p>

<div style="background:skyblue">
This is a div</div>
</body>
</html>

Web Programming 17
10/12/2015
headings.html
<!DOCTYPE HTML>
<html>
<head><title>Headings and paragraphs</title></head>
<body>
<h1>Heading 1</h1>
<h2>Sub heading 2</h2>
<h3>Sub heading 3</h3>

<p>This is my first paragraph</p>


<p>This is my second paragraph</p>

<div style="background:skyblue">
This is a div</div>
</body>
</html>

Web Programming 18
10/12/2015
 It is important to have the correct vision and
attitude towards HTML
◦ HTML is only about structure, not appearance
◦ Browsers tolerate invalid HTML code and parse
errors – you should not.

Web Programming 10/12/2015


19
 HTML documents must start with a
document type definition (DTD)
◦ It tells web browsers what type is the served
code
◦ Possible versions: HTML 4.01, XHTML 1.0
(Transitional or Strict), XHTML 1.1, HTML 5
 Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

Web Programming 20
10/12/2015
 XHTML is more strict than HTML
◦ Tags and attribute names must be in lowercase
◦ All tags must be closed (<br/>, <img/>) while HTML
allows <br> and <img> and implies missing closing tags
(<p>par1 <p>par2)
◦ XHTML allows only one root <html> element (HTML
allows more than one)

Web Programming 10/12/2015


21
 Many element attributes are deprecated in
XHTML, most are moved to CSS
 Attribute minimization is forbidden, e.g.
<input type="checkbox" checked>

<input type="checkbox" checked="checked" />


 Note: Web browsers load XHTML faster than
HTML and valid code faster than invalid!

Web Programming 22
10/12/2015
 Contains information that doesn’t show directly
on the viewable page
 Starts after the <!doctype> declaration
 Begins with <head> and ends with </head>
 Contains mandatory single <title> tag
 Can contain some other tags, e.g.
◦ <meta>
◦ <script>
◦ <style>
◦ <!–- comments -->

Web Programming 10/12/2015


23
 Meta tags additionally describe the content
contained within the page
<meta name="description" content="HTML
tutorial" />

<meta name="keywords" content="html, web


design, styles" />

<meta name="author" content=“XYZ" />

<meta http-equiv="refresh" content="5;


url=http://www.pavanjaiswal.com" />

Web Programming 24
10/12/2015
 The <script> element is used to embed
scripts into an HTML document
◦ Script are executed in the client's Web browser
◦ Scripts can live in the <head> and in the <body>
sections
 Supported client-side scripting languages:
◦ JavaScript (it is not Java!)
◦ VBScript
◦ JScript

Web Programming 10/12/2015


25
<!DOCTYPE HTML> scripts-example.html
<html>
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function sayHello() {
document.write("<p>Hello World!<\/p>");
}
</script>
</head>
<body>
<script type=
"text/javascript">
sayHello();
</script>
</body>
</html>
Web Programming 26
10/12/2015
 The <style> element embeds formatting
information (CSS styles) into an HTML
page
<html> style-example.html
<head>
<style type="text/css">
p { font-size: 12pt; line-height: 12pt; }
p:first-letter { font-size: 200%; }
span { text-transform: uppercase; }
</style>
</head>
<body>
<p>Styles demo.<br />
<span>Test uppercase</span>.
</p>
</body>
</html>
Web Programming 27
10/12/2015
 Comments can exist anywhere between the
<html></html> tags
 Comments start with <!-- and end with -->

<!–- Logo (a JPG file) -->


<img src="logo.jpg" alt=“Logo">
<!–- Hyperlink to the web site -->
<a
href=http://www.pavanjaiswal.com/>Website</a>
<!–- Show the news table -->
<table class="newstable">
...

Web Programming 28
10/12/2015
 The <body> section describes the viewable
portion of the page
 Starts after the <head> </head> section
 Begins with <body> and ends with </body>

<html>
<head><title>Test page</title></head>
<body>
<!-- This is the Web page body -->
</body>
</html>

Web Programming 29
10/12/2015
 Text formatting tags modify the text between
the opening tag and the closing tag
◦ Ex. <b>Hello</b> makes “Hello” bold
<b></b> bold
<i></i> italicized
<u></u> underlined
<sup></sup> Samplesuperscript
<sub></sub> Samplesubscript
<strong></strong> strong
<em></em> emphasized
<pre></pre> Preformatted text
<blockquote></blockquote> Quoted text block
<del></del> Deleted text – strike through

30
Web Programming 10/12/2015 31
 Browsers have limited functionality
◦ Text, images, tables, frames
 JavaScript allows for interactivity
 Browser/page manipulation
◦ Reacting to user actions
 A type of programming language
◦ Easy to learn
◦ Developed by Netscape
◦ Now a standard exists –
www.ecma-international.org/publications/
standards/ECMA-262.HTM

Web Programming 10/12/2015 33


 JavaScript was designed to add interactivity
to HTML pages
 JavaScript is a scripting language
◦ A scripting language is a lightweight programming
language
 JavaScript is an interpreted language (means
that scripts execute without preliminary
compilation)
 Everyone can use JavaScript without
purchasing a license

Web Programming 10/12/2015 34


 JavaScript gives HTML designers a
programming tool
 JavaScript can read and write HTML elements
 JavaScript can react to events
 JavaScript can change HTML content
 JavaScript can change HTML images
 JavaScript can change HTML styles
 JavaScript can be used to validate data

Web Programming 10/12/2015 35


Web Programming 10/12/2015 36
 Improve appearance
◦ Especially graphics
◦ Visual feedback
 Site navigation
 Perform calculations
 Validation of input
 Other technologies
javascript.internet.com

Web Programming 10/12/2015 37


 Embedded within HTML page
◦ View source
 Executes on client
◦ Fast, no connection needed once loaded
 Simple programming statements combined
with HTML tags
 Interpreted (not compiled)
◦ No special tools required

Web Programming 10/12/2015 38


 Totally different
 A full programming language
 Much harder!
 A compiled language
 Independent of the web
 Sometimes used together

Web Programming 10/12/2015 39


 Special syntax to learn
 Learn the basics
 Write it in a text editor, view results in
browser
 You need to revise your HTML
 You need patience and good eyesight!

Web Programming 10/12/2015 40


 JavaScript can be put in the <body> and in
the <head> sections of an HTML page.
 JavaScript can be embedded in the HTML
code.
 JavaScript can also be placed in external
files.

Web Programming 10/12/2015 41


<html>
<head><title>My Page</title></head>
<body>
<script language="JavaScript">

document.write('This is my first JavaScript


Page');

</script>
</body>
</html>

Web Programming 10/12/2015 42


<html>
<head><title>My Page</title></head>
<body>
<script language=“JavaScript">

document.write('<h1>This is my first
JavaScript Page</h1>');

</script>
</body> HTML written
</html> inside JavaScript

Web Programming 10/12/2015 43


<html>
<head><title>My Page</title></head>
<body>
<p>
<a href="myfile.html">My Page</a>
<br />
<a href="myfile.html"
onMouseOver="window.alert('Hello');">
My Page</A>
</p>
</body> An Event JavaScript written
</html> inside HTML

Web Programming 10/12/2015 44


<script language="JavaScript">
window.prompt('Enter your name:','');
</script> Another event

<form>
<input type="button" Value="Press"
onClick="window.alert('Hello');">
</form>
Note quotes: " and '

Web Programming 10/12/2015 45


 JavaScript is very good at processing user
input in the web browser
 HTML <form> elements receive input
 Forms and form elements have unique names
◦ Each unique element can be identified
◦ Uses JavaScript Document Object Model (DOM)

Web Programming 10/12/2015 46


<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>

Web Programming 10/12/2015 47


document.formname.elementname.value
Thus:

document.addressform.yourname.value
document.addressform.phone.value
document.addressform.email.value

Web Programming 10/12/2015 48


Personalising an alert box

<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
onClick="window.alert('Hello ' + 
document.alertform.yourname.value);">
</form>

Web Programming 10/12/2015 49


 Commenting your code is an important
programming practice

// comment text for a single line

/* comment text for multiple lines


*/

Web Programming 10/12/2015 50


 As with algebra, JavaScript variables are used
to hold values or expressions.
 A variable can have a short name, like x, or
a more descriptive name, like carname.
 Rules for JavaScript variable names:
◦ Variable names are case sensitive (y and Y are two
different variables)
◦ Variable names must begin with a letter, the $
character, or the underscore character

Web Programming 10/12/2015 51


 Declaring a variable tells the JavaScript to
reserve memory space for the variable.
 To declare a JavaScript variable, use the
statement
var variable;
where variable is the name assigned to the
variable.
 To declare a JavaScript variable and set its
initial value, use
var variable = value;
where value is the initial value of the variable.

Web Programming 10/12/2015 52


 JavaScript data types:
◦ Numeric values
◦ Text strings
◦ Boolean values
◦ Null values
 You must declare a variable before using it.

Web Programming 10/12/2015 53


 Numeric value is any number, such as 13,
22.5,
-3.14159 etc.
 Text string is any group of text characters,
such as “Hello” or “Happy Holidays!”
◦ Must be enclosed within either double or single
quotations (but not both)
 Boolean values accept only true and false
values
 Null value has no value at all

Web Programming 10/12/2015 54


 Use { } for grouping; not a separate scope
js> var x=3;
js> x
3
js> {var x=4; x}
4
js> x
4
 Not blocks in the sense of other languages
◦ Only function calls and the with statement cause a
change of scope

Web Programming 10/12/2015 55


 Boolean
◦ Two values: true and false
 Number
◦ 64-bit floating point, similar to Java double and Double
◦ No integer type
◦ Special values NaN (not a number) and Infinity
 String
◦ Sequence of zero or more Unicode characters
◦ No separate character type (just strings of length 1)
◦ Literal strings using ' or " characters (must match)
 Special values
◦ null and undefined
◦ typeof(null) = object; typeof(undefined)=undefined

Web Programming 10/12/2015 56


 An object is a collection of named properties
◦ Simple view: hash table or associative array
◦ Can define by set of name:value pairs
 objBob = {name: “Bob", grade: 'A', level: 3};
◦ New members can be added at any time
 objBob.fullname = 'Robert';
◦ Can have methods, can refer to this
 Arrays, functions regarded as objects
◦ A property of an object may be a function (=method)
◦ A function defines an object with method called “( )”
function max(x,y) { if (x>y) return x; else return y;};
max.description = “return the maximum of two arguments”;

Web Programming 10/12/2015 57


 Declarations can appear in function body
◦ Local variables, “inner” functions
 Parameter passing
◦ Basic types passed by value, objects by reference
 Call can supply any number of arguments
◦ functionname.length : # of arguments in definition
◦ functionname.arguments.length : # args in call
 “Anonymous” functions (expressions for functions)
◦ (function (x,y) {return x+y}) (2,3);
 Closures and Curried functions
◦ function CurAdd(x){ return function(y){return x+y} };

More explanation on next slide


Web Programming 10/12/2015 58
 Anonymous functions make great callbacks
setTimeout(function() { alert("done"); }, 10000)
 Curried function
function CurriedAdd(x){ return function(y){ return x+y} };
g = CurriedAdd(2);
g(3)
 Variable number of arguments
function sumAll() {
var total=0;
for (var i=0; i< sumAll.arguments.length; i++)
total+=sumAll.arguments[i];
return(total); }
sumAll(3,5,3,5,3,2,6)

Web Programming 10/12/2015 59


 Anonymous functions very useful for callbacks
setTimeout(function() { alert("done"); }, 10000)
// putting alert("done") in function delays evaluation until call
 Simulate blocks by function definition and call
var u = { a:1, b:2 }
var v = { a:3, b:4 }
(function (x,y) {
var tempA = x.a; var tempB =x.b; //local variables
x.a=y.a; x.b=y.b;
y.a=tempA; y.b=tempB
}) (u,v)
// This works because objects are passed by reference

Web Programming 10/12/2015 60


 Check your statements are on one line
 Check your " and ' quotes match
 Take care with capitalisation
 Lay it out neatly - use tabs
 Be patient

Web Programming 10/12/2015 61


Web Programming 10/12/2015 62
 In the MVC paradigm, the user input, the
modeling of the external world, and the
visual feedback to the user are explicitly
separated and handled by three types of
objects, each specialized for its task.
◦ The view manages the graphical and/or textual
output to the portion of the bitmapped display
that is allocated to its application.
◦ The controller interprets the mouse and keyboard
inputs from the user, commanding the model
and/or the view to change as appropriate.
◦ The model manages the behavior and data of the
application domain, responds to requests for
information about its state (usually from the view),
and responds to instructions to change state
(usually from the controller).

Web Programming 10/12/2015 63


 The formal separation of these three tasks
is an important notion that is particularly
suited to Smalltalk-80 where the basic
behavior can be embodied in abstract
objects: View, Controller, Model and Object.

Web Programming 10/12/2015 64


 Model-View-Controller ("MVC") is the
recommended architectural design pattern
for interactive applications
 MVC organizes an interactive application
into three separate modules:
◦ one for the application model with its data
representation and business logic,
◦ the second for views that provide data
presentation and user input, and
◦ the third for a controller to dispatch requests and
control flow.

Web Programming 10/12/2015 65


 Most Web-tier application frameworks use
some variation of the MVC design pattern
 The MVC (architectual) design pattern
provides a host of design benefits

Web Programming 10/12/2015 66


 Model 2 Architecture to serve dynamic content
◦ Model: Enterprise Beans with data in the DBMS
 JavaBean: a class that encapsulates objects and can be displayed
graphically
◦ Controller: Servlets create beans, decide which JSP to
return, do the bulk of the processing
◦ View: The JSPs generated in the presentation layer (the
browser)

Web Programming 10/12/2015 67


 The MVC paradigm is a way of breaking an
application, or even just a piece of an
application's interface, into three parts: the
model, the view, and the controller.
 MVC was originally developed to map the
traditional input, processing, output roles
into the GUI realm:
◦ Input --> Processing --> Output
◦ Controller --> Model --> View

Web Programming 10/12/2015 68


 Model-View-Controller (MVC) is a software
architecture that separates an application's
data model, user interface, and control
logic into three distinct components so that
modifications to one component can be
made with minimal impact to the others.
 MVC is often thought of as a software
design pattern. However, MVC encompasses
more of the architecture of an application
than is typical for a design pattern. Hence
the term architectural pattern may be useful
(Buschmann, et al 1996), or perhaps an
aggregate design pattern.

Web Programming 10/12/2015 69


 Clarity of design
◦ easier to implement and maintain
 Modularity
◦ changes to one don't affect the others
◦ can develop in parallel once you have the interfaces
 Multiple views
◦ games, spreadsheets, powerpoint, Eclipse, UML
reverse engineering, ….

Web Programming 10/12/2015 70


 The intent of MVC is to keep neatly
separate objects into one of tree categories
◦ Model
 The data, the business logic, rules, strategies, and so on
◦ View
 Displays the model and usually has components that
allows user to edit change the model
◦ Controller
 Allows data to flow between the view and the model
 The controller mediates between the view and model

Web Programming 10/12/2015 71


 The Model's responsibilities
◦ Provide access to the state of the system
◦ Provide access to the system's functionality
◦ Can notify the view(s) that its state has changed

Web Programming 10/12/2015 72


 The view's responsibilities
◦ Display the state of the model to the user
 At some point, the model (a.k.a. the
observable) must registers the views (a.k.a.
observers) so the model can notify the
observers that its state has changed

Web Programming 10/12/2015 73


 The controller's responsibilities
◦ Accept user input
 Button clicks, key presses, mouse movements, slider
bar changes
◦ Send messages to the model, which may in turn
notify it observers
◦ Send appropriate messages to the view
 In Java, listeners are controllers

Web Programming 10/12/2015 74


Web Programming 10/12/2015 75
Model? ________ View? _________ Controller? ________

16
-
Web Programming 10/12/2015 76
 MVC is understood by different people in
different ways
 It is often misunderstood, but most software
developers will say it is important; powerful
 Lets start it right: MVC is a few patterns put
together

Web Programming 10/12/2015 77


Web Programming 10/12/2015 78
 A servlet is a java class that extends an
application hosted on a web server.
 Handles the HTTP request-response
process (for our purposes)
 Often thought of as an applet that runs on a
server.
 Provides a component based architecture
for web development, using the Java
Platform
 The foundation for Java Server Pages (JSP).
 Alternative to CGI scripting and platform
specific server side applications.

Web Programming 10/12/2015 79


 Processing and/or storing data submitted
by an HTML form.
 Providing dynamic content, e.g. returning
the results of a database query to the client.
 Managing state information on top of the
stateless HTTP, e.g. for an online shopping
cart system which manages shopping carts
for many concurrent customers and maps
every request to the right customer.

Web Programming 10/12/2015 80


 Servlets provide the middle tier in a three or
multi-tier system.
 Servlets provide logic and/or traffic control
for requests/response to the server.
 Servlets allow web developers to remove
code from the client and place the logic on
the server.

Web Programming 10/12/2015 81


 Connection management
 Business rule enforcement
 Transaction management
 Mapping clients to a redundant set of
servers
 Supporting different types of clients such as
pure HTML, WML clients, other Java based
clients

Web Programming 10/12/2015 82


 Servlets are not run in the same sense as
applets and applications.
 Since they extend a web server, they require
a servlet container to function.
 A servlet container is a part of a web server
or application server that provides the
network services over which request and
response are sent.
 Contains and manages the servlets through
there lifecycle.
 The container provides other services as
well.

Web Programming 10/12/2015 83


Java Classes Servlets
Browser Web Server

J2EE Container
Deployment Descriptor is used to
configure web applications that are
hosted in the App Server.

Deployment Descriptor

web.xml

Web Programming 10/12/2015 84


 Application Root (htdocs/wwwroot)
 WEB-INF/web.xml
 WEB-INF/classes
◦ Compiled servlet classes and other utility classes
 WEB-INF/lib
◦ Any required third party jars

 All J2EE compliant App Servers require this directory structure

Web Programming 10/12/2015 85


 Apache’s Tomcat @ Jakarta
◦ http://jakarta.apache.org/tomcat/index.html
 BEA’s WebLogic
 ATG Dynamo
 Allaire/MacroMedia’s JRun
 IONA iPortal
 Sun’s Java Web Server * available with the J2EE
SDK
◦ http://java.sun.com/docs/books/tutorial/servletrunne
r/index.html

Web Programming 10/12/2015 86


 All servlets implement the Servlet interface.
 The API provides two classes that implement
this interface, GenericServlet and
HttpServlet
 Servlet API is specified in two packages,
javax.servlet and javax.servlet.http

Web Programming 10/12/2015 87


 This is a contract between the servlet and
the web container.
 Guarantees that all containers can
communicate with a servlet.

 public void init(ServletConfig)


 public void service(request, response)
 public void destroy()
 public ServletConfig getServletConfig()
 public String getServletInfo()

Web Programming 10/12/2015 88


 Abstract class that extends GenericServlet
 Provides additional methods that are called by
the service() method automatically.
 Both methods throw ServletException and
IOException
 Methods of most concern:

◦ protected void doGet(HttpServletRequest,


HttpServletResponse)
◦ protected void doPost(HttpServletRequest,
HttpServletResponse)

Web Programming 10/12/2015 89


Web Programming 10/12/2015 90
 Instantiation – web container creates an
instance.
 Initialization – container calls the instance’s
init().
 Service – if container has request, then it
calls the service() method
 Destroy – before reclaiming the memory
(destroying the servlet), the container calls
the destroy() method.
 Unavailable – instance is destroyed and
marked for GC.

Web Programming 10/12/2015 91


 How do we get it to work?
◦ Use appropriate Tomcat version
◦ Create the appropriate web directory structure
 In “Web-Apps” directory add the following:
 cis228/
 cis228/WEB-INF
 cis228/WEB-INF/classes
 cis223/WEB-INF/lib
◦ Create Servlet (ResourceExampleServlet) which
extends HttpServlet and saved in the classes
directory
◦ Create web.xml and save it in the WEB-INF
directory

Web Programming 10/12/2015 92


<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD
Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<servlet>
<servlet-name>resourceExample</servlet-name>
<servlet-class>ResourceExampleServlet</servlet-
class>
<init-param>
<param-name>dbUser</param-name>
<param-value>testUser</param-value>
</init-param>
[ Repeat above for each parameter – init-param ]
</servlet>
</web-app>
Web Programming 10/12/2015 93
 Define the following methods:
◦ init() – initialize all member variables – safe?
◦ doGet(HttpServletRequest,
HttpServletResponse)
 Note: You should define the doPost() method as well,
even if it just calls doGet()
◦ destroy()

Web Programming 10/12/2015 94


public void init() throws ServletException {
dbUser = getServletConfig().getInitParameter(
"dbUser" );
driver = getServletConfig().getInitParameter(
"driver" );
dbUrl = getServletConfig().getInitParameter(
"dbUrl" );
exampleMsg = getServletConfig().getInitParameter(
"exampleMsg" );
}

Web Programming 10/12/2015 95


response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<html>");
out.println("<head><title>Resource Example Servlet</title></head>");
out.println("<body>");
out.println("<H3>Resource Example Servlet</H3>");
out.println("<p>I could really do some damage if I only knew how to
use those" +
" JDBC libraries!<br>I mean I have:<br>" );
out.println("<ul>");
out.println("<li>User: " + dbUser );
out.println("<li>URL: " + dbUrl );
out.println("<li>Driver: " + driver );
out.println("</ul>");
out.println("<p>" + exampleMsg + "</p>");
out.println("</body>");
out.println("</html>");

Web Programming 10/12/2015 96


public void destroy() {
dbUser = null;
driver = null;
dbUrl = null;
}

Web Programming 10/12/2015 97


 Interfaces used for accessing request
parameters and constructing client
responses.
 The web container has concrete objects
which implement these interfaces and passes
into the servlet.

Web Programming 10/12/2015 98


 Since http protocol is stateless, Java API provides
the following techniques for session tracking:
◦ URL rewriting
◦ Cookies
◦ Hidden form fields

Response with a Token

Client Server

Request with a Token


Web Programming 10/12/2015 99
 URL Write – Facilitated through methods in
the response interface
◦ http://bradsmachine.com?jsessionid=00988988
 Hidden fields - <input type=“hidden”
name=“jsessionid” value=“00988988”>
 Cookies
◦ Cookie c = new Cookie(“uid”, “brad”);
◦ c.setMaxAge(60);
◦ c.setDomain(“bradsmachine”);
◦ c.setPath(“/”);
◦ response.addCookie(c);
 Servlet API requires that web containers implement session
tracking using cookies.

10
Web Programming 10/12/2015 0
 Web containers provide an implementation of
this interface to provide session tracking.
 Session objects can be retrieved from the
HttpRequest object also provided by the
container.
HttpSession session = request.getSession();

 If a session object does not exist for the


client, one will be created.
 The duration of this session object can be
configured in the web.xml file or in a servlet,
setMaxInactiveInterval( int interval );

10
Web Programming 10/12/2015 1
 Servlet API provides an interface for storing
information that is relevant to all servlets
being hosted in a web application.
 Common for facilities like application
logging, access to other resources
(Database Connection Pools), and request
dispatching.
 There is one context per web application
per JVM.
 Parameter information is configured in the
web.xml file in name/value pairs.

10
Web Programming 10/12/2015 2
Presentation Layer (JSP, HTML, WML)

Logic Layer
(Servlets, JavaBeans, EJBS, etc)

Data Store Layer


(MySQL, SQL Server, File System)

10
Web Programming 10/12/2015 3
 High cost of maintenance
 HTML and Java exist in the same file.
 Web Designers don’t understand java code,
don’t like the java code…
 Programmers don’t particularly like the
messing with <HTML> code!!!!
 Better to separate JAVA code from the HTML
code.
if( developer == javaProgrammer)
System.out.println(“Stick to Java code!”);
else if( developer == webDesigner )
System.out.println(“Stick to html code!”);

10
Web Programming 10/12/2015 4
 Java Server Pages (JSPs) provide a way to
separate the generation of dynamic content
(java) from its presentation (html)
 JSP specification builds on the functionality
provided by the servlet specification.

10
Web Programming 10/12/2015 5
index.jsp

Servlet/JSP
checks
Server

converts
Browser Forwards
to
Generated compiles
Servlet index.java

10
Web Programming 10/12/2015 6
10
Web Programming 10/12/2015 7
10
Web Programming 10/12/2015 8
10
Web Programming 10/12/2015 9
 Contains html code like static html pages
with the JSP tags and scripting included in
the page.
 Three basic types of jsp tags
◦ Scripting elements
◦ Directive elements
◦ Action elements

11
Web Programming 10/12/2015 0
 Allow java code – variable or method
declarations, scriptlet, and expressions.
 Declaration tag <%! … %>
 Scriptlet tag <% … %>
 Expression tag <%= … %>

11
Web Programming 10/12/2015 1
 <%! … %>
 Allows you to declare page wide variables
and methods.
 <%! int counter = 0; %>
 <%! Vector beanList = new Vector(); %>
 Methods and variables have class scope
 Note, code must end with ; like any java code

11
Web Programming 10/12/2015 2
 <% … %>
 Used to include small pieces of Java code

 <% for(Enumeration e = beanList.elements();


e.hasMoreElements(); ) {
 UserBean uBean = (UserBean)
e.nextElement();
 out.println( uBean.getUserName() );
 }
 %>

11
Web Programming 10/12/2015 3
 <%= … %>
 Accepts any Java expression, evaluates the
expression, converts to a String, and
displays.
 <%= counter %>
 <%= uBean.getUserName() %>
 Short hand for:
 <% out.println( uBean.getUserName() ); %>

11
Web Programming 10/12/2015 4
 Directives provide global information to the
JSP engine
 For example, a directive can be used to
import java classes.
 Directive elements have a syntax of the form
 <%@ directive … %>

11
Web Programming 10/12/2015 5
The page directive defines a number of
page dependent attributes
<%@ page language=“Java”
[ extends=“className” ]
[ import=“importList” ]
[ session= “true|false” ]
[ buffer=“none|sizekb” ]
[ autoFlush=“true|false” ]
[ isThreadSafe=“true|false” ]
… %>

11
Web Programming 10/12/2015 6
 If language attribute is set, must be = “Java”
 Default import list is java.lang.*,
javax.servlet.*, javax.servlet.jsp.* and
javax.servlet.http.*.
 If session = “true” then default session
variable of type
javax.servlet.http.HttpSession references
the current/new session for the page.

11
Web Programming 10/12/2015 7
 The include directive is used to inline text
and/or code at JSP page translation-time.
 <%@ page include file=“relativeURL”
%>
 <%@ page include=“/navbar.html”%>

11
Web Programming 10/12/2015 8
 The syntax for action elements is based on
XML(i.e. they have a start tag, a body, and an
end tag).
 The JSP specification includes some action
types that are standard.
 New action types are added using the taglib
directive.

11
Web Programming 10/12/2015 9
 Web container implements these actions
 <jsp:useBean>
 <jsp:setProperty>
 <jsp:getProperty>
 <jsp:include>
 <jsp:forward>
 <jsp:plugin>
 <jsp:param>

12
Web Programming 10/12/2015 0
 <jsp:useBean>
 Associates an instance of a bean to a
variable to use with in the jsp page
 <jsp:useBean id=“name”
scope=“page|request|session|application”
class=“className” type=“typeName”>
 …
 </jsp:useBean>

12
Web Programming 10/12/2015 1
 id – variable name to reference instance of
class
 scope
◦ page – javax.servlet.jsp.PageContext
 Objects only accessible from within the page
◦ request ServletRequest
 Objects accessible in pages processing request where bean is
created
◦ session – HttpSession
 Objects accessible from user session
◦ application – ServletContext
 Objects accessible in pages belonging to same application

12
Web Programming 10/12/2015 2
 Type (optional)
◦ Allows scripting variable to be cast to another type
from implementation class, java casting rules apply.
 Class
◦ Fully qualified class name that defines the
implementation of the object

12
Web Programming 10/12/2015 3
 <jsp:setProperty>
 Sets the value of properties in a bean
 <jsp:setProperty name=“beanName”
property=“propertyName”|(param=“paramete
rname”|value=“propertyValue”)/>
 Use property=“*” to set all properties from
the request

12
Web Programming 10/12/2015 4
 Name
◦ Variable name as defined in useBean
 Property
◦ Name of the bean property
 Request
◦ Name of the request parameter (if omitted same
name as bean property name)
 Value
◦ Value assign property (Performs necessary
conversions)

12
Web Programming 10/12/2015 5
 Gets the value of properties in a bean
 <jsp:getProperty name=“beanName”
property=“propertyName”/>
 Name
◦ Variable name as defined in useBean
 Property
◦ Name of the bean property to retrieve

12
Web Programming 10/12/2015 6
<html>
<title>Random JSP Test</title>
<body bgcolor=“white”>
<jsp:useBean id=“rnd” scope=“page”
class=“random.NumberGenerator”/>
<ul>
<li>Next number is: <jsp:getProperty
name=“rnd” property=“nextInt”/>
</ul>
</body>
</html>
12
Web Programming 10/12/2015 7
package random;
import java.util.*;
public class NumberGenerator {
Random rnd = new Random();

public int getNextInt() {


return rnd.nextInt();
}
}

12
Web Programming 10/12/2015 8
 <jsp:include>
 Allows you to include resources in the same
context as the current page
 <jsp:include page=“url” flush=“true”/>
 page:
◦ Relative url
 flush:
◦ If true, buffer is flushed

12
Web Programming 10/12/2015 9
 <jsp:forward>
 Allows you to dispatch the request to a
different page
 <jsp:forward page=“url”/>
 page:
◦ Relative url

13
Web Programming 10/12/2015 0
 Creates HTML that contains OBJECT or
EMBED constructs that result in Java Plugin
download and execution of Applet
 <jsp:plugin type=“applet”
code=“applet.class” codebase=“/html”>
 <jsp:fallback>
 <p>Can’t display applet</p>
 </jsp:fallback>
 </jsp:plugin>
 Fallback is used if the plugin cannot be
started

13
Web Programming 10/12/2015 1
 <jsp:param>
 Used to provide key/value information for
<jsp:include>, <jsp:forward>, and
<jsp:plugin>
 <jsp:param name=“name” value=“value”/>
 Name and value are mandatory

13
Web Programming 10/12/2015 2
 Two approaches to build application with
JSPs
 Model 1: JSP page processes all input
 Model 2: Servlet acts as a controller and
directs http traffic to appropriate responses

13
Web Programming 10/12/2015 3
 JSP is responsible for processing incoming
requests and replying to clients
 All data access is through beans

browser JSP BEAN


Database

13
Web Programming 10/12/2015 4
 Suitable for simple applications
 Easier to understand
 May lead to lots of Java code embedded
within JSP pages for complex applications

13
Web Programming 10/12/2015 5
 Combine use of servlets and JSP
 Servlet acts as controller, JSP as presentation
layer

servlet

Database
browser Beans

JSP

13
Web Programming 10/12/2015 6
 JSP aren’t total separation of logic from the
presentation. Although it’s a good start.
 Look into Custom tags to encapsulate your
application logic and move it outside of the
jsps. Creation of your own custom tag
libraries help to eliminate java code from
being embedded in the jsp.
 Frameworks like WebMacro, Struts, and
Velocity provide additional features to

13
Web Programming 10/12/2015 7
13
Web Programming 10/12/2015 8
 Intrinsic support for agile development

 Super low latency access to your data


◦ Very little CPU overhead

 No Additional caching layer required

 Built in Replication and Horizontal Scaling


support

13
Web Programming 10/12/2015 9
 Document Oriented Database
◦ Data is stored in documents, not tables / relations

 MongoDB is Implemented in C++ for best


performance
 Platforms 32/64 bit Windows Linux, Mac OS-X,
FreeBSD, Solaris

 Language drivers for:


◦ Ruby / Ruby-on-Rails
◦ Java
◦ C#
◦ JavaScript
◦ C / C++
◦ Erlang Python, Perl others..... and much more ! ..

14
Web Programming 10/12/2015 0
 Key-value

 Graph database

 Document-
oriented

 Column family

Web Programming 141


10/12/2015
RDBMS MongoDB
Database Database
Table, View Collection

Row Document (JSON, BSON)

Column Field
Index Index
Join Embedded Document

Foreign Key Reference

Partition Shard

Web Programming 142


10/12/2015
RDBMS MongoDB
Database Database > db.user.findOne({age:39})
Table, Collection {
View "_id" :
Row Document (JSON, ObjectId("5114e0bd42…"),
BSON) "first" : "John",
"last" : "Doe",
Column Field
"age" : 39,
Index Index "interests" : [
Join Embedded "Reading",
Document "Mountain Biking ]
Foreign Reference "favorites": {
Key "color": "Blue",
Partition Shard "sport": "Soccer"}
}

Web Programming 143


10/12/2015
 Create
◦ db.collection.insert( <document> )
◦ db.collection.save( <document> )
◦ db.collection.update( <query>, <update>, { upsert: true
})
 Read
◦ db.collection.find( <query>, <projection> )
◦ db.collection.findOne( <query>, <projection> )
 Update
◦ db.collection.update( <query>, <update>, <options> )
 Delete
◦ db.collection.remove( <query>, <justOne> )

Web Programming 144


10/12/2015
> db.user.find ()
> db.user.insert({ {
first: "John", "_id" : ObjectId("51…"),
last : "Doe", "first" : "John",
age: 39 "last" : "Doe",
}) "age" : 39
}

> db.user.update(
{"_id" : ObjectId("51…")},
{ > db.user.remove({
$set: {
age: 40,
"first": /^J/
salary: 7000} })
}
)
Web Programming 145
10/12/2015
• Basically
• Atomicity Available (CP)
• Consistency • Soft-state
• Isolation • Eventually
• Durability consistent (AP)

Pritchett, D.: BASE: An Acid Alternative (queue.acm.org/detail.cfm?id=1394128)


Web Programming 10/12/2015
146
 Document-Oriented
storege
 Full Index Support Agile
 Replication & High
Availability
 Auto-Sharding
 Querying Scalable
 Fast In-Place Updates
 Map/Reduce

Web Programming 147


10/12/2015
 Important steps
1. MongoDB Java driver download
2. Creating MongoDB connection
3. Connection to MongoDB database
4. MongoDB and collections
5. MongoDB Java CRUD example

14
Web Programming 10/12/2015 8
 If you have maven project, just add below
dependency to include MongoDB java driver into
your application
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>

Otherwise use below link to download


http://search.maven.org/remotecontent?filepath=
org/mongodb/mongo-java-
driver/2.12.3/mongo-java-driver-2.12.3.jar

14
Web Programming 10/12/2015 9
 MongoDB client is an interface between our
Java program and MongoDB server
 It is used to
◦ Create connection
◦ Connect to database
◦ Retrieve collection names
◦ Create/read/update/delete database, collection,
document, etc.

15
Web Programming 10/12/2015 0
 Below are few common methods to connect to MongoDB server

MongoClient mongoClient = new MongoClient(); //connects to default


host and port i.e 127.0.0.1:27017
// or
MongoClient mongoClient = new MongoClient( "localhost" ); //connects to
default port i.e 27017
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); //
should use this always

// or, to connect to a replica set, with auto-discovery of the primary


MongoClient mongoClient = new MongoClient(Arrays.asList(new
ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));

15
Web Programming 10/12/2015 1
 Once you get connection to MongoDB server,
next step is to create connection to database
as shown below. Note: if database does not
exists then MongoDB will create it for you.

MongoClient mongo = new MongoClient("localhost",


27017);
DB db = mongo.getDB("journaldev");

15
Web Programming 10/12/2015 2
 MongoDB client provide useful method to get
all database names as shown below

MongoClient mongo = new MongoClient("localhost",


27017);
List<String> dbs = mongo.getDatabaseNames();
System.out.println(dbs); // [journaldev, local, admin]

 We can have authentication to database. In


that case authorization details are expected
to provide as shown on next slide

15
Web Programming 10/12/2015 3
MongoCredential journaldevAuth =
MongoCredential.createPlainCredential("pankaj", "journaldev",
"pankaj123".toCharArray());
MongoCredential testAuth =
MongoCredential.createPlainCredential("pankaj", "test",
"pankaj123".toCharArray());
List<MongoCredential> auths = new ArrayList<MongoCredential>();
auths.add(journaldevAuth);
auths.add(testAuth);

ServerAddress serverAddress = new ServerAddress("localhost",


27017);
MongoClient mongo = new MongoClient(serverAddress, auths);

15
Web Programming 10/12/2015 4
 We can get collection name as below
MongoClient mongo = new MongoClient("localhost",
27017);
DB db = mongo.getDB("journaldev");
Set<String> collections = db.getCollectionNames();
System.out.println(collections); // [datas, names,
system.indexes, users]
 We can get specific collection by providing its
name as below
DB db = mongo.getDB("journaldev");
DBCollection col = db.getCollection("users");

15
Web Programming 10/12/2015 5
User.java
package mongopackage;

public class User {


private int id;
private String name;
private String role;
private boolean isEmployee;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}

15
Web Programming 10/12/2015 6
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public boolean isEmployee() {
return isEmployee;
}
public void setEmployee(boolean isEmployee) {
this.isEmployee = isEmployee;
}
}

15
Web Programming 10/12/2015 7
MongoDBExample.java
package mongopackage;

import java.net.UnknownHostException;
import com.journaldev.mongodb.model.User;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteResult;

public class MongoDBExample {

public static void main(String[] args) throws UnknownHostException {

User user = createUser();


DBObject doc = createDBObject(user);

15
Web Programming 10/12/2015 8
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("journaldev");

DBCollection col = db.getCollection("users");

//create user
WriteResult result = col.insert(doc);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());

//read example
DBObject query = BasicDBObjectBuilder.start().add("_id", user.getId()).get();
DBCursor cursor = col.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}

15
Web Programming 10/12/2015 9
//update example
user.setName("Pankaj Kumar");
doc = createDBObject(user);
result = col.update(query, doc);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());

//delete example
result = col.remove(query);
System.out.println(result.getUpsertedId());
System.out.println(result.getN());
System.out.println(result.isUpdateOfExisting());
System.out.println(result.getLastConcern());

//close resources
mongo.close();
}

16
Web Programming 10/12/2015 0
private static DBObject createDBObject(User user) {
BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();

docBuilder.append("_id", user.getId());
docBuilder.append("name", user.getName());
docBuilder.append("role", user.getRole());
docBuilder.append("isEmployee", user.isEmployee());
return docBuilder.get();
}

private static User createUser() {


User u = new User();
u.setId(2);
u.setName("Pankaj");
u.setEmployee(true);
u.setRole("CEO");
return u;
}}

16
Web Programming 10/12/2015 1
Sample execution results in below output
null
0
false
WriteConcern { "getlasterror" : 1} / (Continue on error? false)
{ "_id" : 2 , "name" : "Pankaj" , "role" : "CEO" , "isEmployee" : true}
null
1
true
WriteConcern { "getlasterror" : 1} / (Continue on error? false)
null
1
false
WriteConcern { "getlasterror" : 1} / (Continue on error? false)

16
Web Programming 10/12/2015 2
16
Web Programming 10/12/2015 3
• "Asynchronous JavaScript and XML"
• New name for an old technique:
– JavaScript + DHTML + XMLHttpRequest
– In use since at least 1997
– I've used it since 2000
– Finally someone gave it a name
– Already enabled in your Web server and browser
• Use JavaScript asynchronously behind the
scenes to load additional data (typically
XML) without discarding and reloading the
entire Web page.

16
Web Programming 10/12/2015 4
• Your users will soon demand it
– Not just another cool (geeky) technology
– Very user-visible effect
– Rich UI experience in a Web page
• Portable across browsers
• Plus, all advantages of zero-install Web
app
– No install done for this demo
– No "DLL Hell"

16
Web Programming 10/12/2015 5
• Client/Server Apps:
– Dynamic data
– Static forms, controls, code, etc.
– Efficient, but not flexible
• Traditional Web Apps:
– Dynamic data
– Dynamic forms, controls, code, etc.
– Flexible, but inefficient, and noticeably slow
• Ajax Apps:
– Dynamic data
– Static or dynamic forms, controls, code, etc.
– Best of both worlds

16
Web Programming 10/12/2015 6
• Geeky reasons:
– Multithreaded data retrieval from Web servers
• Pre-fetch data before needed
• Progress indicators
• Appearance of speed
• Avoids need for setTimeout()
– Less bandwidth required; less server load
• Reload partial page, not entire page
• Load data only, not even partial page

16
Web Programming 10/12/2015 7
16
Web Programming 10/12/2015 8
• As little or as much as you like
• No need to abandon what you already do
• One more item in your "bag of tricks"
• Start by jazzing up your existing UI

16
Web Programming 10/12/2015 9
• open (“method”, “URL”, [async, username,
password])
– Assigns destination URL, method, etc.
• send (params)
– Sends request including postable string or DOM object data
• abort ()
– Terminates current request
• getAllResponseHeaders ()
– Returns headers (name/value pairs) as a string
• getResponseHeader (“header”)
– Returns value of a given header
• setRequestHeader (“label”,”value”)
– Sets Request Headers before sending

17
Web Programming 10/12/2015 0
• onreadystatechange
– Event handler (your code) that fires at each state change
• readyState
0 = uninitialized 3 = interactive (some data has been returned)
1 = loading (broken in IE 6.0)
2 = loaded 4 = complete
• status
– HTTP Status returned from server: 200-299 = OK
• responseText
– String version of data returned from server
• responseXML
– XML DOM document of data returned
• statusText
– Status text returned from server

17
Web Programming 10/12/2015 1
var req = new XMLHttpRequest();
req.onreadystatechange = myHandler;
req.open("GET", "servlet", true);
req.send("p1=abc");

...

function myHandler() {
if (req.readyState == 4) {
doSomethingWith(req.responseXML);
}
else if (req.readyState == 3) {
showProgressIndicator();
}
}

17
Web Programming 10/12/2015 2
 Windows Live Local
 Windows Live Mail (Hotmail Beta)
 Google Maps
 Google Suggest

17
Web Programming 10/12/2015 3
 Ajax frameworks are categorized into four
types
1. Direct Ajax framework
2. Indirect Ajax framework
3. Component Ajax framework
4. Server drive Ajax framework

17
Web Programming 10/12/2015 4
 This type requires CSS, Ajax and HTML
expertise
 This type consists of web pages which are
authored in HTML
 One can use cross browser API of this type
 XAP, DWR and prototype are the categories of
this type

17
Web Programming 10/12/2015 5
 This type is dependent on compiler
technology
 Thus coding is done in high level language
so that compiler will run the code in
JavaScript
 This type will guide you on programming
concepts front

17
Web Programming 10/12/2015 6
 It has in built components to generate and
handle own HTML code
 You can enjoy customized APIs, extensibility,
programmatic control, skinning facility with
this type
 Example: YUI, Dojo, Open Rico, TIBCO

17
Web Programming 10/12/2015 7
 In this type, components will be crated with
the use of server side scripting language
 With the use of various Ajax techniques, one
can communicate all the user actions to the
server
 Example: jBossRich Faces, jMaki, Google Web
Toolkit, Thin Wire, etc

17
Web Programming 10/12/2015 8
Important questions
1. What are some of the common lists that can be
used when designing a webpage?
2. How do you create links to sections within the
same webpage?
3. Write a HTML table tag sequence that outputs
the following:
50 pcs 100 500
10 pcs 5 50
4. What does DOCTYPE mean?
5. How many HTML tags are should be used for
the most simple of web pages? Which are they?

17
Web Programming 10/12/2015 9
Important questions
6. How to set a default parameter value for a
JavaScript function?
7. How to open URL in new tab in javascript?
8. How do I declare a namespace in
JavaScript?
9. Difference between JavaScript and Jscript?
10.What is JavaScript? Validate login form
using JavaScript.
11.What is difference between include action
and include directive in JSP?
18
Web Programming 10/12/2015 0
Important questions
12.How do you define application wide error
page in JSP?
13.How do you get ServletContext reference inside
Servlet? Explain with example.
14.What does load-on-start-up element in
web.xml do?
15.Define JSP and servlet.
16.Explain JDBC process with MongoDB. Consider
suitable example.
17.What is MVC architecture?

18
Web Programming 10/12/2015 1
Reference
1.http://www.w3schools.com/html/
2.Elisabeth Freeman, Eric Freeman, “Head
First JavaScript Programming” by O’Reilly
Media
3.scom.hud.ac.uk/scomsjw/Web%20Authori
ng%20Module/Lecture%20Slides/introjs.pp
t
4.Kathy Sierra, “Head First Servlets and JSP”
by O’Reilly Media
5.http://java.sun.com/products/servlet
6.http://java.sun.com/products/jsp
18
Web Programming 10/12/2015 2
Reference
7. http://www.theserverside.com
8. http://www.pavanjaiswal.com/2015/07/run-
jsp-servlet-in-apache-tomcat-no.html
9. http://www.webdeveloperjuice.com/2013/0
9/18/top-seven-ajax-frameworks-for-
building-rich-web-based-applications/
10.https://www.elance.com/q/blog/2011/11/u
nderstanding-4-types-of-ajax-
frameworks.html
11.http://www.journaldev.com/3963/mongodb
-java-crud-example-tutorial

18
Web Programming 10/12/2015 3
Thank You
http://www.pavanjaiswal.com

18
Web Programming 10/12/2015 4

You might also like