Java Programming Chapter-8 Servlet-1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 54

Chapter Eight

Servlets

1
HTML
 HTML stands for Hyper Text Markup Language
 HTML is not a programming language, it is a markup
language
 A markup language is a set of markup tags that tell the Web
browser how to display the page.
 HTML tags describe how a web page is formatted.
 Each tag appears inside bracket(<>)
e.g. <b> some text here </b>
 The end tag is written like the start tag, with a forward slash
before the tag name .
 Start and end tags are also called opening tags and closing tags.
 HTML tags are not case-sensitive.
<b> is the same as <B>

2
HTML…
 An HTML file must have an htm or html file extension.
 An HTML file can be created using a simple text editor like notepad.
You can also easily edit your file using tools like Dreamweaver, MS-
frontpage ,adobe pagemill, etc…
 The purpose of a web browser is to read HTML documents and display them
as web pages.
The browser does not display the HTML tags, but uses the tags to
interpret the content of the page:
Example
<html>
<body>
<h1>
My
First
Headin
g</h1>
3 <p>M
y first
The structure of an HTML element

<html> - The main container for HTML pages


<head> - The container for page header information
<title> - The title of the page
<body> - The main body of the page

4
The structure of an HTML element…

5
HTML Elements
The <html> Element: Contains the whole page
The Head <head> </head>
 Contains information about the page which is not displayed

 Each <head> element can contain a <title> element indicating the title of the

document
 It may also contain any combination of the following elements, in any

order:
<link>, <script>, <style> and likes
The <title> Element:
 You should specify a title for every page inside the <title> element.

The <body> Element:


The <body> element contains the part of the Web page that you actually see in the main
browser
6 window.
Simple page
<html>
<head>
<title> Information </title>
</head>
<body>
<h1>Information</h1>
<p>
Information is the data that is organized,
meaningful and Useful for making a decision or
to take an action.
Information is a processed and
organized data.
</p>
</body>
</html>

7
HTML Attributes
 HTML elements can have attributes
 Attributes provide additional information about the element
 Attributes are always specified in the start tag
 Attributes come in name/value pairs like: name="value"
Example
<body bgcolor= “green”>

 Attribute values should always be enclosed in quotes.


 The attributes value may only contain letters, digits,

hyphens,periods, underscores and colons.


 Attribute names and attribute values are case-insensitive.
8
How text inside paragraphs is displayed
Paragraph <P> Tag
 The Paragraph Tag will allow you to separate text blocks.
 When a browser displays a paragraph it usually inserts a
new line before the next paragraph and

adds a little bit of extra vertical space

 Attributes:

 ALIGN= allows you to specify how your paragraph should be


aligned on the page.
 Possible values are: LEFT, RIGHT and CENTER.
e.g: <P ALIGN="center">

9
How text inside paragraphs is displayed…

Example
<html>
<body>
<p>Here is a paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
<p>Here is a third paragraph of text.</p>
</body>
</html>

10
HTML text formatting tags
Line Break <BR>
 The Line Break Tag tells a line of text to stop displaying on the current
line and drops the cursor to the beginning of the next line.
 It doesn’t need closing tag.
e.g: text on one line <BR> text on the next line

 Heading <H#> </H#>


 The Heading Tag allows you to define the font size of a block of text
and Bold it in one step.
 Possible values are H1, H2, H3, H4, H5, H6, H7.
 H1 is the largest and H7 is the smallest.
e.g: <H1> header text here </H1>
11
HTML text formatting tags…
Example:
<html>
<body>
<h1> Heading 1 </h1>
<p> The content under heading one goes here. </p>
<h2> Heading 2 </h2>
<p> The content under heading two goes here. </p>
<h3> Heading 3 </h3>
<p> the content under heading three goes here. </p>
<h4> Heading 4 </h4>
<p> The content under heading four goes here. </p>
<h5> Heading 5 </h5>
<p> The content under heading five goes here. </p>
<h6> Heading 6 </h6>
<p> The content under heading six goes here. </p>
</body>
</html>12
Comments in the HTML source
Comment <!-- --> tag
 The Comment Tag allows you to add comments to your source code
that is NOT visible on the page.
 This is useful if you have a complicated set of coding and need to keep
notes within the code.
 Using the Comment Tag: Example
<!-- This is a comment -->

 <!-- This is a
multiple-line comment that ends here. -->

13
HTML Lists
Unordered list
 An unordered list is a list of items where the list items are marked with
bullets.
 An unordered list starts with the <ul> tag.
 Each list item starts with the <li> tag.
 An unordered list example
<html>
<body>
<h4>An Unordered List:</h4>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</body>
</html>
14
HTML Lists…
An ordered list
 An ordered list is a list of items where items are marked with numbers.

 An ordered list starts with the <ol> tag.

 Each list item starts with the <li> tag.

An ordered list example


<html>
<body>
<h4>An Ordered List:</h4>
<ol >
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
</body>
</html>
15
HTML Form
 Html forms is a section of a document containing controls such as checkbox, text

box, radio buttons and likes


 While almost all other elements in HTML are for controlling the display and

presentation, HTML FORM and INPUT tags add interactivity to the web site.
 They are used to pass data to the server.

 The HTML forms handle very important operations for the website like taking

orders and user registration.

There are two parts to a working form.

1.The first part is the form , which are made up of buttons, text fields, and pull-

down menus
Forms are added to web pages using the <form> element.

2.The
16 other component of a web form is a program or script on the server that
HTML Form …
HTML form attributes
 action=This Attribute specifies the page which handles the input from the user.

 Usually, this will be a script that processes the data supplied by the user.

e.g: <form action="http://w ww.server.com/servlet">


 method ="get"|"post" ( is either GET or POST.)

 If you use GET method, the input values are passed as part of the URL.

 If it is POST, the information is sent to the server as part of the data body and

will not be visible in the URL box in the user's browser.


 If you don't specify the method, GET is taken by default.

 e.g: <form method="post" or "get">

 Forms use several different INPUT tags to specify the type of information you

17 and the way it is displayed


want,
GET vs POST
GET POST
1) In case of Get request, only limited In case of Post request, large amount of
amount of data can be sent because data data can be sent because data is sent in
is sent in header. body.

2) Get request is not secured because Post request is secured because data is
data is exposed in URL bar. not exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent. It means


second request will be ignored until Post request is non-idempotent.
response of first request is delivered

5) Get request is more efficient and used Post request is less efficient and used
more than Post. less than get.
18
Single-line text field
 Used for entering a single word or line of text
 syntax : <input type="text" />
Attributes:
 name= allows you to specify a name for the form.
e.g: <input type="text" name="name here">
 maxlength= set a maximum character limit.
e.g: <input type="text" maxlength="80">
 size= by default, browsers display a text-entry box that is 20 characters
wide, but you can change the number of characters using the size
attribute.
e.g: <input type="text" size="25">
 value= the value attribute specifies default text that appears in the field
and send to the server for processing.
19
e. g: <input type="text" value="value here">
Single-line text field …
<html>
<body>
<form action=“www.server.com/servlet" method="get">
<h4>Enter The Following Data </h4>
First Name :<input type="text" size="20"> </input><br>
Middle name :<input type="text" maxlength="5“><br>
Departement:<input type="text" value="Computer Science" >
</form>
</body>
</html>

20
HTML Form …
Form Input Submit <INPUT TYPE="SUBMIT">
 Submit button immediately sends the collected form data to the

server for processing.


<input type="submit" />

Attributes:
 name= allows you to specify a name for the form.
e.g: <input type="submit" name="name here">
 value= allows to specify the text that appears on the button that is
created.
e.g: <input type="submit" value="submit your info now">

21
HTML Form …
Example

<html>
<body>
<form action=“www.server.com/script.php" method="get">
<h3>Enter The Following Data </h3>
First Name :<input type="text"><br><br>
Middle name :<input type="text"
maxlength="5"><br>
<h5>click Send to submit your data </h5><br>
<INPUT TYPE="SUBMIT" VALUE="Send">
</form>
</body>
</html>
22
HTML Form …
Form Input Reset <INPUT TYPE="RESET">
 The Input Reset Tag allows you to create a button that users can click to clear all
the fields in the form and reset the form controls to the initial state.
e.g: <input type="reset">
Example
<html>
<body>
<form action=“www.server.com/servlet" method="get">
click reset to enter your data again:<br>
<input type="reset">
</form>
</body>
</html>

23
Radio Button
Form Input Radio Button <INPUT TYPE="RADIO">
 The Radio Button allows you to ask visitors to choose ONE option of several.
 You cannot select more than one radio button.
 Use the Check Box if you have more than one possible option for visitors to
choose.
Attributes:
 CHECKED allows you to set a radio button as a pre-selected default choice.
 Only one button should ever have this option
<input type="radio" checked>
 NAME= allows you to specify the name
 It is required for the radio button .
<input type="radio" name="name here">
 VALUE= allows you to specify what the value for the radio button is.
<input type="radio" value="yes">

24
Radio Button Example
<html>
<body>
<FORM ACTION=http://www.server.com/script.pl
METHOD="get"> Please select your Nationality: <br>
<ul>
<li>Ethiopian <input type="radio" value="1"
name="Nationality"><br>
<li>American<input type="radio" value="2"
name="Nationality"><br>
<li>Japanese <input type="radio" value="3"
name="Nationality"><br>
</ul>
</form></body>
</html>

25
Check box
Form check box <input type="checkbox">
 The check box allows you to place a small box in your form that can be
checked on or off.
 Check boxes allow you to specify several possible answers to a question.

Syntax:<input type="checkbox" />


attributes:
Checked allows you to specify a box which are pre-checked by
default.
<input type="checkbox" checked>
NAME= allows you to specify the name of the form.
<input type="checkbox" name="my form">
Value= allows you to specify which value is returned if the box
is checked.
26
<input type="checkbox" value="yes">
Check box Example
Example
<html><body><b> select your color choices</b><br>
<form action=“welcomeServelet" method="post">
<ol>
<li>Red:<input type="checkbox" checked name="my form“ value="yes"><br>
<li>Green:<input type="checkbox" name="my form"> <br>
<li>Blue:<input type="checkbox" name="my form"><br>
<li>Yellow:<input type="checkbox" name="my form">
</ol>
</form></body></html>

27
Form example
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

The example HTML page above contains two input fields

and a submit button.


When the user fills in this form and click on the submit
28
button, the form data is sent to the java servlet program.
Java on the Web: J2EE
Thin clients (minimize download)
Java all “server side”

Servlets

Client
Server

A servlet is like an applet, but on the server side Client sends a request to
server
Server starts a servlet
Servlet computes a result for server and does not quit
Server returns response to client
Another
29 client sends a request
Introduction to Servlet
 A servlet is a Java technology-based Web component, managed by a container,
that generates dynamic content.
 Servlets are platform-independent Java classes that are compiled to platform-
independent byte code that can be loaded dynamically and run by a Java
technology-enabled Web server.
The server that executes a servlet often is referred to as the servlet container or
servlet engine
 Servlet containers are Web server extensions that provide servlet functionality.
 The servlet container is a part of a Web server or application server that
provides the network services over which requests and responses are sent
between client and server.
30
 Servlets interact with Web clients via a request/response model implemented
Introduction to Servlet…
 A common implementation of the request-response model is between World
WideWeb browsers and World Wide Web servers.
 When a user selects a Web site to browse through their browser (the client
application), a request is sent to the appropriate Web server (the server
application).
 The server normally responds to the client by sending the appropriate HTML
Web page.
 The servlets communication between clients and servers is via the HTTP
protocol.
 A client sends an HTTP request to the server or servlet container.

 The server or servlet container receives the request and directs it to be processed

31 the appropriate servlet.


by
Introduction to Servlet…
 Servlet uses request-response model of communication

 The client requests that some action be performed and the server performs the

action and responds to the client.

 A servlet extends the functionality of a server.

 Packages javax.servlet and javax.servlet.http

 provide the classes and interfaces to define servlets.

 Servlets are effective for developing Web-based solutions that

provides:-
 Secure access to a Web site

 Interact with databases on behalf of a client


32
Introduction to Servlet…
 Servlets have become so popular that they are supported directly or with
third-party plug-ins by most major Web servers and application servers,
such as:-
The Netscape iPlanet Application Server
Microsoft’s Internet Information Server (IIS)
The Apache HTTP Server
BEA’s WebLogic application server
IBM’s Web- Sphere application server
The World Wide Web Consortium’s Jigsaw Web server, and many
more.
33
Servlet Interface
 All servlets must implement the Servlet interface of package
javax.servlet
 The methods of Servlet interface are invoked automatically by the
server on which the servlet is installed, also known as the servlet
container.
 This interface defines five methods:-

1. void init( ServletConfig config )


This method is automatically called once during a servlet’s

execution cycle to initialize the servlet.


The ServletConfig argument is supplied by the servlet

container that executes the servlet.


2. String getServletInfo()
This
34 method is defined by a servlet programmer to return a String
Servlet Interface…
3. ServletConfig getServletConfig()
 This object provides access to the servlet’s configuration information

such as servlet initialization parameters and the ServletContext


 Provides the servlet with access to its environment

4.void service( ServletRequest request, ServletResponse response )


The servlet container calls this method to respond to a client request to the

servlet.
 These objects provide access to input and output streams that allow the

servlet to read data from the client and send data to the client.
 These streams can be either byte based or character based.

5. void destroy()
 This “cleanup” method is called when a servlet is terminated by its servlet

container.
35
Servlet’s life cycle
 A servlet’s life cycle begins when the servlet container loads the servlet into
memory - normally, in response to the first request that the servlet receives.
 Then the servlet container invokes the servlet’s init method to initialize the
servlet. New thread created for each client
 After init completes execution, the servlet can respond to its first request.
 All requests are handled by a servlet’s service method, which receives the
request, processes the request and sends a response to the client.
 During a servlet’s life cycle, method service is called once per request.
 Each new request typically results in a new thread of execution (created by the
servlet container) in which method service executes.
 When the servlet container terminates the servlet,
 the servlet’s destroy method is called to release servlet resources.
Methods
public void init(): Called only once when servlet is being created.
 Good place for set up, open Database, etc.

public void service(): Called once for each request.


 In HttpServlet, it delegates requests to doGet, doPost, etc.
36public void destroy(): Called when server decides to terminate the servlet. Release resources.
Servlet’s life cycle…

37
Servlet packages
 The servlet packages define two abstract classes that implement

the interface Servlet


class GenericServlet (from the package javax.servlet)

class HttpServlet (from the package javax.servlet.http)

 These classes provide default implementations of all the Servlet

methods.
 Most servlets extend either GenericServlet or HttpServlet and

override some or all of their methods.


 If problems occur during the execution of a servlet, either

ServletExceptions or IOExceptions are thrown to indicate the


38
HttpServlet Class
 Web-based servlets typically extend class HttpServlet.

 Class HttpServlet overrides method service to distinguish between the

typical requests received from a client Web browser.


 The two most common HTTP request types (also known as request

methods) are get and post.


 A get request - retrieves information from a server.

Common uses of get requests are to retrieve an HTML document or

image from the server.


 A post request - send server data from HTML form
Common uses of post requests typically send information, such
as authentication information or data from a form that obtains user
input
39 to a server.
HttpServlet Class…
 Class HttpServlet defines methods doGet and doPost to respond to
get and post requests from a client, respectively.
 These methods are called by the service method, which is called
when request arrives at the server.
Method service first determines the request type,

Then calls the appropriate method for handling such a request.

 Methods doGet and doPost receive as an arguments

HttpServletRequest object and an HttpServletResponse object that


enable interaction between the client and the server.
 The methods of HttpServletRequest make it easy to access the data
supplied as part of the request.
 The HttpServletResponse methods make it easy to return the
servlet’s results to the Web client.
40
HttpServletRequest Interface
 Every call to doGet or doPost for an HttpServlet receives an object that

implements interface HttpServletRequest.


 The Web server that executes the servlet creates an HttpServletRequest
object and passes this to the servlet’s service method (which, in turn,
passes it to doGet or doPost).
 This object contains the request from the client.
 A variety of methods are provided to enable the servlet to process the
client’s request.
1.String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or pos
request.
The name argument represents the parameter name.
2.Enumeration getParameterNames()

 Returns the names of all the parameters sent to the servlet as part of a

post request.
3.String[]
41 getParameterValues( String name )
HttpServletResponse Interface

Every call to doGet or doPost for an HttpServlet receives an

object that implements interface HttpServletResponse.


The Web server that executes the servlet creates an

HttpServletResponse object and passes it to the servlet’s service


method (which, in turn, passes it to doGet or doPost).
This object provides a variety of methods

That enable the servlet to formulate the response to the client.

42
Some methods of interface HttpServletResponse
 ServletOutputStream getOutputStream()

Obtains a byte-based output stream for sending binary data to the

client.
 PrintWriter getWriter()

Obtains a character-based output stream for sending text data to the

client.
 void setContentType( String type )

Specifies the MIME (Multipurpose Internet Mail Extension) type of the

response to the browser. (indicate the content type)


The MIME type helps the browser determine how to display the data (or

possibly what other application to execute to process the data).


43

Example 1 - Handling HTTP get Requests
 The following figures demonstrate HTML document with the form’s
action that invokes WelcomeServlet

<!-- WelcomeServlet.html -->


<html >
<head>
<title>Handling an HTTP Get Request</title>
</head>
<body>
<form action = "/advjhtp1/welcome1" method = "get">
<p>Click the button to invoke the servlet
<br><br>
<input type = "submit" value = "Get HTML Document" />
</p>
</form>
</body>
</html>
44
Example 1 - Handling HTTP get Requests…

 The following figures demonstrate a servlet that handles HTTP get

requests.
 When the user clicks the Get HTML Document button a get request

is sent to the servlet WelcomeServlet.


 The servlet responds to the request by generating dynamically an

HTML document for the client that displays “Welcome to


Servlets!”.

45
Example 1 - Handling HTTP get Requests…
import javax.servlet.*; import
javax.servlet.http.*; import
java.io.*;
public class WelcomeServlet
extends HttpServlet {
protected void
doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException,
IOException{
response.setContentType( "text/html");
PrintWriter out = response.getWriter();
out.println( "<html>" );
out.println( "<head>" );
out.println( "<title>A Simple
Servlet Example</title>" );
out.println( "</head>" );
out.println( "<body>" );
out.println( "<h1>Welcome to
Servlets!</h1>"
46 );
Example 2 - Handling HTTP get Requests Containing Data
import javax.servlet.*;
import
javax.servlet.http.*;
import java.io.*;
public class
WelcomeServlet2 extends
HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse
response ) throws ServletException, IOException
{
String firstName = request.getParameter( "firstname" );
response.setContentType(
"text/html" ); PrintWriter out =
response.getWriter();
out.println( "<html>" );
out.println( "<head>" );
out.println( "<title>Processing get requests with
data</title>" ); out.println( "</head>" );
out.println( "<body>" );
out.println( "<h1>Hello " + firstName +
",<br
} />" ); out.println( "Welcome to Servlets!
47 ); out.println( "</body>" );
</h1>"
Example 2 - Handling HTTP get Requests Containing Data…

 The servlet (WelcomeServlet2 ) responds to an HTTP get request that

contains a name supplied by the user.


 The servlet uses the name as part of the response to the client.

 Parameters are passed as name/value pairs in a get request.

 To obtain information that was passed to the servlet as part of the client

request you can use request object getParameter method


 The request object’s getParameter method receives the parameter

name as an argument and returns the corresponding String value, or


null if the parameter is not part of the request.
String firstName = request.getParameter( "firstname" );
48
Example 2 - Handling HTTP get Requests Containing Data…
<!-- WelcomeServlet2.html -->
<html >
<head>
<title>Processing get requests with data</title>
</head>
<body>
<form action = "/advjhtp1/welcome2" method = "get">
<p>
Type your first name and press the Submit button
<br /><input type = "text" name = "firstname" />
<input type = "submit" value = "Submit" />
</p>
</form>
</body>
</html>
49
Example 2 - Handling HTTP get Requests Containing Data…

 The html (WelcomeServlet2.html) document provides a form in which the user can

input a name in the text input element firstname and click the Submit button to
invoke WelcomeServlet2.
 When the user presses the Submit button, the values of the input elements are

placed in name/value pairs as part of the request to the server.


 In the browser address bar you can observe that the browser appended ?

firstname=Paul to the end of the action URL.


 The question mark (?) separates the query string (i.e., the data passed as part of

the get request) from the rest of the URL in a get request.
 The name/value pairs are passed with the name and the value separated by equal

sign( =)
 If there is more than one name/value pair, each name/value pair is separated
50
Example 3 - Handling HTTP post Requests
 An HTTP post request is often used to post data from an HTML form to a server-

side form handler that processes the data.


 For example the (WelcomeServlet3) servlet program on the next slide is identical to

the servlet program we discussed previously except that it defines a doPost method
to respond to post requests rather than a doGet method.
 We override doPost method to provide custom post request processing.

 Method doPost receives the same two arguments as doGet - an object that

implements interface HttpServletRequest to represent the client’s request and an


object that implements interface HttpServletResponse to represent the servlet’s
response.
 As with doGet, method doPost throws a ServletException if it is unable to

handle a client’s request and throws an IOException if a problem occurs


51 stream processing.
during
Example 3 - Handling HTTP post Requests…
import javax.servlet.*; import
javax.servlet.http.*; import
java.io.*;
public class WelcomeServlet3
extends HttpServlet {
protected void doPost( HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException{
String firstName = request.getParameter("firstname" );
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html>" );
out.println( "<head>" );
out.println("<title>Processing post requests with
data</title>" ); out.println( "</head>" );
out.println( "<body>" );
out.println( "<h1>Hello " + firstName + ",<br />" );
out.println( "Welcome to Servlets!</h1>" );
out.println( "</body>" );
out.println( "</html>" );
out.close();
52
Example 3 - Handling HTTP post Requests…

 Html document (WelcomeServlet3.html) provides a form in which

the user can input a name in the text input element firstname then
click the Submit button to invoke WelcomeServlet3.
 When the user presses the Submit button, the values of the input

elements are sent to the server as part of the request.


 However, note that the values are not appended to the request URL

because the form’s method in this example is post.

53
Example 3 - Handling HTTP post Requests…
<!-- WelcomeServlet3.html -->
<html>
<head>
<title>Handling an HTTP Post Request with Data</title>
</head>
<body>
<form action = "/advjhtp1/welcome3" method = "post">
<p>
Type your first name and press the Submit button
<br /><input type = "text" name = "firstname" />
<input type = "submit" value = "Submit" />
</p>
</form>
</body>
</html>

54

You might also like