Java Programming Chapter-8 Servlet-1
Java Programming Chapter-8 Servlet-1
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
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.
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”>
Attributes:
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
<!-- 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.
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
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.
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
Forms use several different INPUT tags to specify the type of information you
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.
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
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.
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>
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
The client requests that some action be performed and the server performs the
provides:-
Secure access to a Web site
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.
37
Servlet packages
The servlet packages define two abstract classes that implement
methods.
Most servlets extend either GenericServlet or HttpServlet and
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
42
Some methods of interface HttpServletResponse
ServletOutputStream getOutputStream()
client.
PrintWriter getWriter()
client.
void setContentType( String type )
requests.
When the user clicks the Get HTML Document button a get request
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…
To obtain information that was passed to the servlet as part of the client
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
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-
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
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
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