Final1x - More from yimg.com...

soilkinkajouInternet and Web Development

Feb 2, 2013 (4 years and 9 months ago)

163 views



HTML



It’s nothing but a designing or layout language.



HTML stands for Hyper Text Markup Language



HTML is not a programming language, it is a markup language



HTML uses markup tags to describe web pages.



It is a type of computer language that is primarily used for files that are posted on the internet and
viewed by web browsers.



Browser can understand only one language that one is HTML.



We can create static
pages with extension either .HTML or .HTM.



The HTML contains TAGS and attributes of that tags.



With the help of HTML language we can develop static pages.


HTTP


Hypertext Transfer Protocol is the set of rules for transferring files (text, graphic images, sound, video,
and other multimedia files) on the World Wide Web.


Server and clients can talk with each other using HTTP.


HTTP defines how messages are formatte
d and transmitted, and what actions Web servers and
browsers should take in response to various commands.



When WebServer sends data on the browser it sends using HTTP.































What

is Web server?



A web server is a program running on

the server that listens for incoming requests and services
those requests as they come in.



A web server is a computer that responds to requests from a client Typical requests: provide a web
page, upload or download a file, send email
.



A web server is
also the software that responds to these requests; a client could be the browser or
other software making these requests Typically, your little computer is the client, and someone
else’s big computer is the server. However, any computer can be a server It
is not unusual to have
server software

and client
software running on the same computer



By default the role of a web server is to serve static pages using the http protocol



Web servers can be made dynamic by adding additional processing capability to the

server






What

is Apache?


The Apache HTTP Server, commonly referred to as Apache is
web server

software notable for
playing a key role in the initial growth of the
World Wide Web
.






What is Apache Tomcat Jakarta Tomcat or simply Tomcat
?


A Web container is essentially the component of a Web server that interacts with
the servlets.



The Web container is
responsible for managing the lifecycle of servlets,
mapping a URL to a particular servlet and ensuring that the URL
requester has the correct access rights.



When your web server application gets request for a servlet the server
hands the request not to th
e servlet itself, but to the Container in
which the servlet is deployed.



It gives the response to the HTTP request.



Apache Tomcat is open source software that implements Java Servlet and JavaServer Pages,
enabl
ing sites to run Java servlets
and Java
-
base
d dynamic content.


Basic task of WebContainer are:



Creates HTTP Request and Response for the Servlet, calls the appropriate servlet service method
(doGet or doPost) to service the client request.



Container also gives: Communication support(socket
creation), Servlet life cycle management
(Init(), Service() and Destroy()), Multithreading support, Declarative security(thru deployment
descriptor) and JSP support.


Basic of JSP and Servlet


The Servlet and JSP are web tier components that are running within a web
-
tier container.


The roles that web components play are basically


1.

receiving client requests that are coming in the form of HTTP requests and then

2.

perform dynamic contents generat
ion or performing

business logic by themselves

3.

Or
delegating it to the EJB tier components return responses to the clients.





The main difference between servlets and JSPs is that servlets are Java classes and JSPs are not (they are
embedded in HTML pages
).


This difference also specifies where you want to use servlets and where you want to use JSPs:


If you generate all of your html pages dynamically and will have complex logic, you will probably use
servlets.


If dynamic content is very low compared t
o the static content in your web page, then you will probably
use JSPs.


What is JSP?



The interesting thing is that, despite the huge apparent difference, behind the scenes they are the
same.



In fact, a JSP document is just another way of writing a
servlet. JSP pages get translated into
servlets, the servlets get compiled, and it is the servlets that run at request time.



JSP is focused on simplifying the creation and maintenance of the HTML.



Servlets are best at invoking the business logic and per
forming complicated operations.



A quick rule of thumb is that servlets are best for tasks oriented toward processing, whereas JSP is
best for tasks oriented toward presentation.



J
SP is a webpage scripting language that can generate dynamic content while

Servlets are Java
programs that are already compiled which also creates dynamic web content
.



Servlets run faster compared to JSP
.



JSP can be compiled into Java Servlets
.



It’s easie
r to code in JSP than in Java.



JSP and Java Servlets are usually used i
n conjunction nowadays
.





What is Servlet?


The complete servlet specification was created by Sun Microsystems, with version 1.0 finalized in
June 1997 right now 3.0 is going on in the market.


A servlet is a Java programming language class used to extend the capabilities of servers that host
applications accessed via a request
-
response programming model.


A technical description of Servlet is it is a Java object that is based on Servlet framewor
k and
extends the functionality of a web server

basically being responsible for creating dynamic contents.


Servlets are server side components that provide a powerful mechanism for developing server side
programs.


Servlets are Java technology's answer to C
GI programming.


They are programs that run on a Web server and build Web pages.


Servlet can be thought of as server
-
side applet.


Servlets are loaded and
executed by

a web server in the same manner that

applets are loaded and
executed by a web browser.


Servlets accepts request s from a client (via web server) performs some task and return the
results.


Servlets are Java programs that run on Web or application servers, acting as a middle layer
between requests coming from Web browsers or other HTTP clients

and databases or applications
on the HTTP
server.






Using servlets web developers can create fast and efficient server side application which can run on
any servlet enabled web server.


Servlets run entirely inside the Java Virtual Machine.


Servlets c
an access the entire family of Java APIs, including the JDBC API to access enterprise
databases


Although servlets can respond to any type of request, they are commonly used to extend the
applications hosted by Web servers.


For such applications, Java Serv
let technology defines HTTP
-
specific servlet classes.


The
javax.servlet and javax.servlet.http

packages provide interfaces and classes for writing
servlets.


All servlets must implement the
Servlet interface,

which defines life
-
cycle methods.


When implementing a generic service, you can use or extend the GenericServlet class provided
with the Java Servlet API.


The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP
-
specific
services.





Facts

It is regular Java code.


There are new APIs, but no new syntax.


It has unfamiliar import statements.


The servlet and JSP APIs are not part of the Java 2 Platform, Standard Edition (J2SE); they are a
separate specification


It extends a standard class (
HttpServlet).


Servlets provide a rich infrastructure for dealing with HTTP.


It overrides the doGet method.


Servlets have different methods to respond to different types of HTTP commands


Roles of Servlet

Read the explicit data sent by the client.



Data entered by end user in the HTML form or from applet or a customHTTP client program.


Read the implicit HTTP request data sent by the browser.



Above figure shows a single arrow going from the client to the Web server, but there are really two
varieti
es of data: the explicit data that the end user enters in a form and the behind
-
the
-
scenes
HTTP information.



The HTTP information includes cookies, information aboutmedia types and compression schemes
the browser understands, and so forth.


Generate the
results.



This process may require talking to a database, executing an RMI or EJB call, invoking a Web
service, or computing the response directly.



Your real data may be in a relational database.



Fine. But your database probably doesn’t speak HTTP or return results in HTML, so the Web
browser can’t talk directly to the database.



Even if it could, for security reasons, you probably would not want it to.



The same argument applies to most other ap
plications.



You need the Web middle layer to extract the incoming data from the HTTP stream, talk to the
application, and embed the results inside a document.


4. Send the explicit data (i.e., the document) to the client.



This document can be sent in a
variety of formats, including text (HTML or XML), binary (GIF
images), or even a compressed format like .zip that is layered on top of some other underlying
format.





But, HTML is by far the most common format, so an important servlet/JSP task is to wrap th
e
results inside of HTML.


5. Send the implicit HTTP response data.



Single arrow going from the Web middle layer (the servlet or JSP page) to the client.


But, there are really two varieties of data sent: the document itself and the behind
-
the
-
scenes
HTTP

information.



Again, both varieties are critical to effective development.



Sending HTTP response data involves telling the browser or other client what type of document is
being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.


Why Build Web Pages Dynamically?


There are a number of reasons wh
y Web pages need to be built on
-
the
-
fly:


The Web page is based on data sent by the client.



For instance, the results page from search engines and order confirmation pages at online stores
are specific to particular user requests.



You don’t know what to

display until you read the data that the user submits.



Just remember that the user submits two kinds of data: explicit (i.e., HTML form data) and implicit
(i.e., HTTP request headers).



Either kind of input can be used to build the output page.


The
Web page is derived from data that changes frequently.



If the page changes for every request, then you certainly need to build the response at request
time. If it changes only periodically, however, you could do it two ways: you could periodically
build
a new Web page on the server , or you could wait and only build the page when the user
requests it.



The right approach depends on the situation, but sometimes it is more convenient to do the latter:
wait for the user request.



For example, a weather rep
ort or news headlines site might build the pages dynamically, perhaps
returning a previously built page if that page is still up to date.


The Web page uses information from corporate databases or other server
-
side sources.



If the information is in a data
base, you need server
-
side processing even if the client is using
dynamic Web content such as an applet.



Imagine using an applet by itself for a search engine site use only.



Going from the client to the Web tier to the database (a three
-
tier approach) in
stead of from an
applet directly to a database (a two
-
tier approach) provides increased flexibility and security with
little or no performance penalty.





After all, the database call is usually the rate
-
limiting step, so going through the Web server does
n
ot slow things down.



In fact, a three
-
tier approach is often faster because the middle tier can perform caching and
connection pooling.



In principle, servlets are not restricted to Web or application servers that handle HTTP requests but
can be used for

other types of servers as well. For example, servlets could be embedded in FTP or
mail servers to extend their functionality.


CGI VS Servlet



Common Gateway Interface



CGI are usually executables that are native to the server’s operating system, though
servlets can
also be compiled to the native OS it can be compiled to Java bytecode which is then run on a JVM



CGI programs are platform dependent while servlets are platform independent



CGI programs run as separate processes on the computer while servlet
s run on the JVM



CGI can directly process scripts while it needs to be translated and compiled to before it can be run
as a servlet



CGI is a process based(Heavy weight) and Servlet is a Thread based (Light weight).



Incense

CGI creates a process for ever
y
execution
.

So, this

is a time taking process whereas
servlet executes by using
threading.



Servlets have an extensive infrastructure for automatically parsing and decoding HTML form data,
reading and setting HTTP headers, handling cookies, tracking sessi
ons, and many other such high
-
level utilities. In CGI, you have to do much of this yourself



Servlets can talk directly to the Web server, whereas regular CGI programs cannot, at least not
without using a server
-
specific API.






Basic servlet structure



Basic servlet that handles GET requests.



A browser generates this request when the user enters a URL on the address line, follows a link
from a Web page, or submits an HTML form that either does not specify a METHOD or specifies
METHOD="GET".



Servlets ca
n also easily handle
POST

requests, which are generated when someone submits an
HTML form that specifies
METHOD="POST"
.


GET

POST

Data is part of the URL in get method.

Post method data is sent as request
message body.


Choosing GET as the "method" will
append all
of the data to the URL and it will show up in
the URL bar of your browser.

A POST on the other hand will
(typically) send the information through
a socket back to the webserver and it
won't show up in the URL bar


Data is cached in the browsers

URL history if
you use get method

post method Data cannot be cached.


In get method you can send only text

post method you can send text as well
as possible to send files and even
binary data such as serialized Java
objects.


The amount of information

you can send back
using a GET is restricted as URLs can only be
1024 characters.

Larger data can be send in the post
method as compared to the GET


Example:

http://www.test.com/hello?key1=value1&k
ey2=value2


T
his message comes to the backend
program in
the form of the standard
input which you can parse and use for
your processing.

doGet() method

doPost() method














Basic servlet


import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;


public class HelloWorld extends
HttpServlet {


public void doGet(HttpServletRequest request,


HttpServletResponse response)


throws ServletException, IOException {


PrintWriter out = response.getWriter();


out.println("Hello World");


}

}


Example#
Steps
to First basic HTML program of Servlet

Step 1: Write down below coding in simple editor

1.

import java.io.*;

2.

import javax.servlet.*;

3.

import javax.servlet.http.*;


4.

public class HelloWorld extends HttpServlet {


5.

public void doGet(HttpServletRequest request,

6.


HttpServletResponse response)

7.

throws IOException, ServletException

8.

{

1.

response.setContentType("text/html");

2.

PrintWriter out = response.getWriter();

3.

out.println("<html>");

4.

out.println("<head>");

5.

out.println("<title>Hello World!</title>");

6.

o
ut.println("</head>");

7.

out.println("<body>");

8.

out.println("<h1>Hello World!</h1>");

9.

out.println("</body>");

10.

out.println("</html>");

9.

}

10.

}


Step 2: Complie it




Step 3: Class file is generated


Step 4: Start TomCAT






Step 5:


Step 6: Create
directory structure as given below in WebApps


Step 7: Cut D:
\
Helloworld.java


Step 8: Past it in Classes folder of Webapps






Step 9:

We need to change in
deployment descriptor (web.xml) file.


open it and add tags.

There could be various entries in this table already available, but never
mind
.


Step 10: Now write down port no in WebBrowser open it and click on Tomcat manager






Step 11: Enter username and password


Step 12: Go to our folder


Step 13:
Write down program name








Explanation of Basic Structure of Servlet


Let's have a look at how the Servlet works.


Lines 1 to 3 import some packages which contain many classes which are used by the Servlet (almost
every Servlet needs classes from
these packages).



1: import java.io.*;


2: import javax.servlet.*;


3: import javax.servlet.http.*;


The javax.servlet package and javax.servlet.http package contains a number of classes and interfaces that
describe and define the con
tracts between a servlet class running under the HTTP protocol and the
runtime environment provided for an instance of such a class by a conforming servlet container.


The Servlet class is declared in line
4
.


Our Servlet extends javax.servlet.http.HttpS
ervlet, the standard base class for HTTP Servlets.



4: public class HelloWorld extends HttpServlet


In lines 5 through 9 HttpServlet's doGet method is getting overridden.



5: public void doGet(HttpServletRequest request,


6:


HttpS
ervletResponse response)


7:

throws IOException, ServletException


8:

{



...


9: }


In line 6 we use a method of the HttpServletResponse object to set the content type of the response that
we are going to send.


In line 7
ServletException

d
efines a general exception a servlet can thro
w when it encounters difficulty and
IOException

define a general exception

InputOuput field not found


All response headers must be set before a PrintWriter or ServletOutputStream is requested to write body
data

to the response.



Sub part


1: res
ponse
.setContentType("text/html");


In line 2 we request a PrintWriter object to write text to the response message.



2: PrintWriter out = res
ponse
.getWriter();


In lines 3 to 10 we use the PrintWriter to
write the text of type text/html (as specified through the content
type).



To display the output on the browser we use the println() method of the PrintWriter class.





3:

out.println("<html>");

4: ....

10:

out.println("</html>");





How Servlet
runs?





























You write a servlet and compile it, and then place it in the appropriate directory.


When the Servlet Container starts, it will preload your servlet in memory if specified in the web.xml
configuration file.


If your servlet is not already loaded (not listed in the web.xml configuration file), its instance will be
created as soon as a request for it is received by the Servlet Container.


The first time it is loaded, the container calls your servlet's init() me
thod.


Now that your servlet is ready, it waits for requests.


The container will call your service() method each time a request is received for your servlet.




The HttpServlet class
already has this method, so you don't have to write one, but you can ov
erride it.


The service() method then passes the request on to the appropriate method such as the doGet() method
if it is a GET request, or the doPost() method if it is a POST request.


The doXXX() methods are the ones you need to override and where you
will spend most of your effort.


Both
doGet

and
doPost

take two arguments: an
HttpServletRequest

and an
HttpServletResponse
.


The
HttpServletRequest

lets you get at all of the incoming data; the class has methods by which you can
find out about information such as form (query) data, HTTP request headers, and the client's hostname.


The
HttpServletResponse

lets you specify outgoing information such as

HTTP status codes (200, 404,
etc.) and response headers (
Content
-
Type
,
Set
-
Cookie
, etc.).


Most importantly,
HttpServletResponse

lets you obtain a
PrintWriter

that you use to send document
content back to the client.


The servlet processes the request (c
ode you write in doGet()), returning a response to the container.


The container sends the text of the response back to the browser.






Servlet Life Cycle









The life cycle of a servlet is controlled by servlet
-
container in which the servlet has
been deployed. When a
HTTP request is mapped to a servlet,

the container performs the following steps.


If an instance of the servlet does not exist, the Web container


Loads the servlet class.


Creates an instance of the servlet class.


Initializes the servle
t instance by calling the init() method .


Invokes the service method, passing HttpServletRequest and

HttpServletResponse objects
as parameters.


When shutting down, calls each servlet’s
destroy( )

method


Servlets Container


1.

A servlet is managed by a
servlet container

(referred to as
Servlet Engine
).

2.

The servlet container is a compiled, executable program. The container is the
intermediater
between the Web server and the servlets
in the container. The container loads, initializes, and
executes the serv
lets. When a request arrives, the container maps the request to a servlet

3.

The container is designed to perform well while serving large numbers of requests. A container can
hold any number of active servlets. The container creates and manages threads as ne
cessary to
handle incoming requests.
The container handles multiple requests concurrently
, and more
than one thread may enter an object at a time.

4.

Servlet containers are also referred to as
web containers

or
web engines
.


Architecture Diagram:


The following figure depicts a typical servlet life
-
cycle scenario.



First the HTTP requests coming to the server are delegated to the servlet container.



The servlet container loads the servlet before invoking the
service()

method.



Then the servlet contain
er handles multiple requests by spawning multiple threads, each thread
executing the service() method of a single instance of the servlet.


























Each request runs in a separate thread.


The container runs multiple threads to process
multiple requests to a single result.


And every client request generates a new pair of request and response objects.














A servlet life cycle can be defined as the entire process from its creation till the destruction.

The
following are the paths followed by a servlet






















1.

The servlet is initialized by calling the
init ()

method. init is where you put one
-
time setup code.
By this init() method the servlet get to know that it has been placed into service.


2.

The servlet calls
service()

method to process a client's request. Each user request results in a
thread that calls the service method of the previously created instance. Multiple concurrent
requests normally result in multiple threads calling service sim
ultaneously, although your servlet
can implement a special interface (SingleThreadModel) that stipulates that
only a single thread is permitted to run at any one time. The service method
then calls doGet, doPost, or another doXxx method, depending on the t
ype
of HTTP request it received.

3.

Finally, if the server decides to unload a servlet, it first calls the servlet's
destroy method.

The servlet is terminated by calling the
destroy()

method.

4.

Finally, servlet is garbage collected by the garbage collector of
the JVM.


Now let us discuss the life cycle methods in details.




The init() method :



The init method is designed to be called only once.



It is called when the servlet is first created, and
not called again for each
user request.

So, it is used for one
-
time initializations.



The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the servlet be
loaded when the server is first started.



When a user invokes a servle
t, a single instance of each servlet gets created,
with each user request resulting in a new thread that is handed off to doGet
or doPost as appropriate.



The init() method simply creates or loads some data that will be used
throughout the life of the ser
vlet.


The init method definition looks like this:


public void init() throws ServletException

{


// Initialization code...



}




The service() method :



The service() method is the main method to perform the actual task.



The servlet container (i.e. web

server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.



The servlet services the client's request with the help of two objects. These two objects
javax.servlet.ServletRequest

and


javax.servlet.ServletResponse

are passed by the servlet
container.




Each time the server receives a request for a servlet, the server spawns a new thread
and calls service.



The service() method checks the HTTP request
type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods as appropriate.


Here is the signature of this method:


public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOExcep
tion{

}



The service () method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate.



So you have nothing to do with service() method but you override either doGet() or doPost()
depending on
what type of request you receive from the client.



Servlets generally extend the HttpServlet class and override the doGet or the doPost methods



The doGet() and doPost() are most frequently used methods within each service request.



Here are the signature

of these two methods.


The doGet() Method



A GET request results from a normal request for a URL or from an HTML form that has no METHOD
specified and it should be handled by doGet() method.


public void doGet(HttpServletRequest request,
HttpServletResponse response)


throws ServletException, IOException {


// Servlet code

}


The doPost() Method





A POST request results from an HTML form that specifically lists POST as the METHOD and it should
be handled by doPost() method.


public
void doPost(HttpServletRequest request,


HttpServletResponse response)


throws ServletException, IOException {


// Servlet code

}


The destroy() method :



The destroy() method is called only once at the end of the life cycle of a servlet.



This
method gives your servlet a chance to close database connections, halt background threads,
write cookie lists or hit counts to disk, and perform other such cleanup activities.



After the destroy() method is called, the servlet object is marked for garbage collection.


The destroy method definition looks like this:



public void destroy() {


// Finalization code...


}







Example#
Life Cycle Example ,

To appreciate the
execution of the servlet life cycle methods,
keep refreshing the browser (F5 in Windows).

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;


public class LifeC extends HttpServlet {


int i;


public void init() throws ServletException

{

i=0;

}



public void doGet(HttpServletRequest request,


HttpServletResponse response)


throws ServletException, IOException


{




response.setContentType("text/html");




PrintWriter out = response.getWriter();



if(i==0)


{


out.println("<h1>in i =0 </h1>");


}



i++;



if(i==10)


{


out.println("<h1>in i =10 </h1>");


destroy();


}



if(i<10)


{


out.println("<h1>in i <" + i + "</h1>
");


}


}


public void destroy()

{

i=0;

}


}





Example#
Display Date

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;


public class DispDt extends HttpServlet {




public void doGet(HttpServletRequest request,


HttpServletResponse response)


throws ServletException, IOException


{




response.setContentType("text/html");




PrintWriter out = response.getWriter();



Date today = new Date();


out.println("<html>"+"<body><h1>Today Date is</h1>");


out.println("<b>"+ today+"</b></body>"+ "</html>");


}


}

Example#
Parameterized Servlet

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;


public class Hello2 extends HttpServlet {




public void doGet(HttpServletRequest request,


HttpServletResponse response)


throws ServletException, IOException


{


response.setContentType("text/html");



PrintWrite
r out = response.getWriter();



String title = "Using GET Method to Read Form Data";


String docType =


"<!doctype html public
\
"
-
//w3c//dtd html 4.0 " +


"transitional//en
\
">
\
n";


out.println(docType +


"<html>
\
n" +



"<head><title>" + title + "</title></head>
\
n" +


"<body bgcolor=
\
"#f0f0f0
\
">
\
n" +


"<h1 align=
\
"center
\
">" + title + "</h1>
\
n" +


"<ul>
\
n" +


" <li><b>First Name</b>: "



+ request.getParameter("first_name") + "
\
n" +


" <li><b>Last Name</b>: "


+ request.getParameter("last_name") + "
\
n" +


"</ul>
\
n" +


"</body></html>");


}

}




HTML file

<html>

<form
action="http://localhost:8081/shyamsir/Hello2" method="get">

First Name: <input type="text" name="first_name">

<br />

Last Name: <input type="text" name="last_name" />

<input type="submit" value="Submit" />

</form>

</body>

</html>




Example#
Print the
Header Information

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;


public class Hello4 extends HttpServlet



{



public void doGet(HttpServletRequest request,HttpServletResponse response)




throws Servlet
Exception, IOException



{




response.setContentType("text/html");




PrintWriter out = response.getWriter();





String title = "Servlet Example: Showing Request Headers";





out.println(




"<BODY BGCOLOR=
\
"#FDF5E6
\
">
\
n" +



"<H1 ALIGN=CENTER>" + title + "</H1>
\
n" +



"<B>Request Method: </B>" +




request.getMethod() + "<BR>
\
n" +



"<B>Request URI: </B>" +



request.getRequestURI() + "<BR>
\
n" +




"<B>Request Protocol: </B>" +




request.getProtocol() + "<BR><BR>
\
n" +



"<TABLE BORDER=1 ALIGN=CENTER>
\
n" +



"<TR BGCOLOR=
\
"#FFAD00
\
">
\
n" +




"<TH>Header Name<TH>Header Value");





E
numeration headerNames = request.getHeaderNames();




while(headerNames.hasMoreElements())



{




String headerName = (String)headerNames.nextElement();



out.println("<TR><TD>" + headerName);



out.println(" <TD>" + request.getHeader
(headerName));





}



out.println("</TABLE>
\
n</BODY></HTML>");


}


}