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

Java UNIT 4

Java Servlets are server-side Java programs that handle client requests and generate dynamic responses, making them essential for server-side applications. The document also covers CGI programming, explaining how it interfaces with web servers and processes requests. Additionally, it details the structure, lifecycle, and key components of Java Servlets, including methods for reading client data and sending HTTP responses.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Java UNIT 4

Java Servlets are server-side Java programs that handle client requests and generate dynamic responses, making them essential for server-side applications. The document also covers CGI programming, explaining how it interfaces with web servers and processes requests. Additionally, it details the structure, lifecycle, and key components of Java Servlets, including methods for reading client data and sending HTTP responses.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT 4

JAVA SERVLETS
Java Servlet is a Java program that runs on a Java-enabled web server or
application server. It handles client requests, processes them, and generates
responses dynamically. Servlets are the backbone of many server-side Java
applications due to their efficiency and scalability.
1. Servlets work on the server side.
2. Servlets are capable of handling complex requests obtained from the
web server.
3. Generate dynamic responses efficiently.

CGI Programming

The Common Gateway Interface is the standard interface between the WWW consortium
and the external program.

The CGI(Common Gateway Interface) is an executable program that is specified on the URL
and passes a parameter to CGI program. The program is processed by HTTP Server and
passes standard input to access environment variables. The output such as HTML elements is
passed back to the HTTP server Thus it is the process of the CGI program.

When a user browses the web with a request using a URL to the server, the server parses the
URL. The filename is searched which is kept in a pre-configured directory called CGI
Directory and displays the file or error message back to the user.

The CGI program can be accessed by command line argument. From the server side invokes a
program according to CGI specifications called CGI Script. CGI programs are written in C,
PERL, Visual basic, shell script, C++, etc. The server receives user requests in the form of
URLs and recognizes them as CGI scripts. The script is processed and passed back to the user
output as a web client. The environment variables play a crucial role in writing the CGI
program.

A Simple Java Servlet

 Creating a Basic Servlet

// Basic servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello, World!</h1></body></html>");
}
}

 Configuring a Servlet

To deploy a servlet, you need to configure it in the web.xml file. This file maps
URLs to servlets. For example:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

Anotomy of a java servlet

The anatomy of a Java Servlet involves understanding its structure, lifecycle, and key
components. Servlets are Java classes that extend the capabilities of servers, primarily
used for web applications, handling client requests and generating dynamic responses.

1. Servlet Structure
Class Definition:
A servlet is defined as a Java class that typically
extends javax.servlet.http.HttpServlet.
Annotations/Deployment Descriptor:
Servlets are configured either using annotations like @WebServlet or through
the web.xml deployment descriptor.
Methods:
Servlets override methods from the HttpServlet class to handle different types of
HTTP requests (e.g., doGet(), doPost()).
2. Servlet Lifecycle

Initialization:
When a servlet is first loaded, the init() method is called. This is where setup
operations are performed.
Service:
For each client request, the service() method (or one of its derivatives
like doGet() or doPost()) is invoked. It handles the request and generates a response.
Destruction:
When the servlet is being unloaded, the destroy() method is called, allowing for
cleanup tasks.

3. Key Components
ServletRequest and ServletResponse:
These interfaces provide methods for accessing request information and sending
responses. HttpServletRequest and HttpServletResponse are
HTTP-specific implementations.
ServletConfig and ServletContext:
ServletConfig provides configuration information for a specific servlet,
while ServletContext provides information about the entire web application.
Request Dispatcher:
This interface allows servlets to forward requests to other resources (e.g., other
servlets, JSPs) or include their output in the response.
Filters:
Filters are components that can intercept requests and responses, allowing for pre-
and post-processing.
Listeners:
Listeners are classes that respond to events in the servlet lifecycle or application
context, such as session creation or attribute changes.
Reading data from a client
getParameter() − You call request.getParameter() method to get the
value of a form parameter.

getParameterValues() − Call this method if the parameter appears


more than once and returns multiple values, for example checkbox.

getParameterNames() − Call this method if you want a complete list of


all parameters in the current request.

GET Method

The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? (question mark) symbol
as follows −

The GET method if you have password or other sensitive information to pass to the
server. The GET method has size limitation: only 1024 characters can be used in a
request string.

This information is passed using QUERY_STRING header and will be accessible


through QUERY_STRING environment variable and Servlet handles this type of
requests using doGet() method.

Eg.

<html>
<body>
<form action = "HelloForm" 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>

POST Method

A generally more reliable method of passing information to a backend program is the


POST method. This packages the information in exactly the same way as GET
method, but instead of sending it as a text string after a ? (question mark) in the URL
it sends it as a separate message. This message comes to the backend program in the
form of the standard input which you can parse and use for your processing. Servlet
handles this type of requests using doPost() method.

Eg.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter 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>"
);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}}

Reading http request from header

When the user wants some information, he/she will request the information through
the browser. Then the browser will put a request for a web page to the webserver. It
sends the request information to the webserver which cannot be read directly
because this information will be part of the header of the HTTP request.
Header Name Description

Accept Specifies the MIME types (also called Internet Media types or
Content types which describe the media type of content served by
Header Name Description

web servers or applications) that the browser or other clients can


handle.

Accept- Specifies the character sets that the browser can use to display the
Charset information

Accept-
Specifies the types of encodings that the browser supports.
Encoding

Accept- Specifies the client’s preferred languages in case the servlet can
Language produce results in more than one language

This is used by clients to identify themselves when accessing


Authorization
password-protected web pages

This indicates whether the client can handle HTTP connections or


Connection
not.

Content- This header is applicable only for POST requests and gives the size
Length of the POST data

This returns cookies to servers that are previously sent to the


Cookie
browser

Host This specifies host and port which are given in the original URL

Methods which are used to read HTTP Header

 Cookie[] getCookies(): Returns all the cookie objects that the client has sent
with the request
 Enumeration getAttributeNames(): Returns an Enumeration containing the
names of the attributes available to this request.
 Enumeration getHeaderNames(): Returns an Enumeration of all the header
names this request contains.
 Enumeration getParameterNames(): Returns an Enumeration of String
Objects which contains the names of the parameters of the current request.
 HTTPSession getSession(): Returns the session which is associated with this
request, if the request does not have a session, then it creates a session for that
request.
 Object getAttribute(String name): returns the value of the named attribute as
an object, or null if no attribute with the given name exists.
 String getContentType(): returns the MIME type of the request, or null if the
type is not known.
 String getMethod(): returns the name of the HTTP method with which the
request has been made. The HTTP methods that are used are GET, POST.

package com.headers;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletresponse;
// servlet implementation;
@WebServlet("/Headers")
public class Headers extends HttpServlet {
private static final long serialVersionUID = 1L;
public Headers() { super(); }
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String str = "Display Header Request";
out.println(
"<BODY BGCOLOR=\"#FF5732\">\n"
+ "<H1 ALIGN=CENTER>" + str + "</H1>\n"
+ "<B><center>Request Method: <center></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");
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
Sting headerName
= (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println("<TD>"
+ request.getHeader(headerName));
}
out.println("<TABLE>\n</BODY></HTML>");
}
}
Sending data to a client and writing the http response header

HTTP Response
HTTP Response sent by a server to the client. The response is used to provide the client
with the resource it requested. It is also used to inform the client that the action requested
has been carried out. It can also inform the client that an error occurred in processing its
request.

An HTTP response contains the following things:

1. Status Line
2. Response Header Fields or a series of HTTP headers
3. Message Body

In the request message, each HTTP header is followed by a carriage returns line feed
(CRLF). After the last of the HTTP headers, an additional CRLF is used and then begins
the message body.

HTTP Response Components


An HTTP response message has following four components mentioned below:
 A Status-line: <HTTP-Version> <Status-Code> <Reason-Phrase>
 Zero or more header (General|Response|Entity) fields
 An empty line (i.e., a line with nothing preceding the CRLF) indicating the
end of the header fields
 Optionally a message-body
The following sections explain each of the entities used in an HTTP response
message.
Message Status-Line
A Status-Line consists of the protocol version followed by a numeric status code and
its associated textual phrase. The elements are separated by space SP characters.
<HTTP-Version> <Status-Code> <Reason-Phrase>
HTTP Version
A server supporting HTTP version 1.1 will return the following version information:
HTTP-Version = HTTP/1.1
Status Code
The Status-Code element is a 3-digit integer where first digit of the Status-Code
defines the class of response and the last two digits do not have any categorization
role. There are 5 values for the first digit:
Status Code Description

1xx: Informational It means the request was received and the process is continuing.

2xx: Success It means the action was successfully received, understood, and accepted.

3xx: Redirection It means further action must be taken in order to complete the request.

4xx: Client Error It means the request contains incorrect syntax or cannot be fulfilled.

5xx: Server Error It means the server failed to fulfill an apparently valid request.
HTTP status codes are extensible and HTTP applications are not required to
understand the meaning of all registered status codes. A list of all the status codes has
been given in a separate chapter for your reference.

Response Header Fields


We will study General-header and Entity-header in a separate chapter when we will
learn HTTP header fields. For now, let's check what Response header fields are.
The response-header fields allow the server to pass additional information about the
response which cannot be placed in the Status- Line. These header fields give
information about the server and about further access to the resource identified by the
Request-URI.
 Accept-Ranges
 Age
 ETag
 Location
 Proxy-Authenticate
 Retry-After
 Server
 Vary
 WWW-Authenticate
You can introduce your custom fields in case you are going to write your own custom
Web Client and Server.

Examples of Response Message


Now let's put it all together to form an HTTP response for a request to fetch
the hello.htm page from the web server running on tutorialspoint.com
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed

hello.html
<html> <body> <h1>Hello, World!</h1> </body> </html>

Working with cookies java server pages


Cookies are the textual information that is stored in key-value pair format to the
client’s browser during multiple requests. It is one of the state management
techniques in session tracking. Basically, the server treats every client request as a
new one so to avoid this situation cookies are used. When the client generates a
request, the server gives the response with cookies having an id which are then
stored in the client’s browser. Thus if the client generates a second request, a cookie
with the matched id is also sent to the server. The server will fetch the cookie id, if
found it will treat it as an old request otherwise the request is considered new.

Using Cookies in Java

 In order to use cookies in java, use a Cookie class that is present


in javax.servlet.http package.
 To make a cookie, create an object of Cookie class and pass a name and its
value.
 To add cookie in response, use addCookie(Cookie) method of
HttpServletResponse interface.
 To fetch the cookie, getCookies() method of Request Interface is used.

Methods in Cookies
 clone(): Overrides the standard java.lang.Object.clone method to return a copy
of this Cookie.
 getComment(): Returns the comment describing the purpose of this cookie, or
null if the cookie has no comment.
 getDomain(): Gets the domain name of this Cookie.
 getMaxAge(): Gets the maximum age in seconds of this Cookie.
 getName(): Returns the name of the cookie.
 getPath(): Returns the path on the server to which the browser returns this
cookie.
 getSecure(): Returns true if the browser is sending cookies only over a secure
protocol, or false if the browser can send cookies using any protocol.
 getValue(): Gets the current value of this Cookie.
 getVersion(): Returns the version of the protocol this cookie complies with.
 setValue(String newValue): Assigns a new value to this Cookie.
 setVersion(int v): Sets the version of the cookie protocol that this Cookie
complies with.

Example

index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java
import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


response.addCookie(ck);//adding cookie in the response

//creating submit button


out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}
}
}

SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}
}
}

Installation
The environment setup for JSP mainly consists of 3 steps:
1. Setting up the JDK.
2. Setting up the webserver (Tomcat).
3. Starting tomcat server.
All the steps are discussed in details below:
Setting up Java Development Kit :
Step 1: This step involves downloading JDK from Download JDK.
Step 2: Setting up the PATH environment variable appropriately. For windows:
1. right-click on My Computer->
2. select Properties->
3. Click on Advanced System setting ->
4. Click on Environment Variables ->
5. Then, update the PATH value5 and press the OK button.
On LINUX system if the SDK is installed in /usr/local/jdk-9.0.4 and you use the
C shell, you will put the following into your .cshrc file.
setenv PATH /usr/local/jdk-9.0.4/bin:$PATH
setenv JAVA_HOME /usr/local/jdk-9.0.4

Setting up Web Server: Tomcat


Apache Tomcat is an open source software implementation of the JavaServer Pages
and Servlet technologies and can act as a server for testing JSP, and can be
integrated with the Apache Web Server.
Here are the steps to set up Tomcat on your machine.
Step 1: Download latest version of Tomcat from here.
Step 2: After downloading, unpack the binary distribution into a suitable location.
Step 3: After unpacking create CATALINA_HOME environment variable pointing
to the same locations.

Start tomcat Server


Starting on Windows Machine by using following command :
%CATALINA_HOME%\bin\startup.bat
Starting on Linux Machine by using the following command :
$CATALINA_HOME/bin/startup.sh
After successful installation and successfully setup the paths for the server. We
can see the home page of tomcat web server by using http://localhost:8080/ on
your browser.

JSP Overview
JavaServer Pages (JSP) is a Sun Microsystems specification for combining Java
with HTML to provide dynamic content for Web pages. When you create
dynamic content, JSPs are more convenient to write than HTTP servlets
because they allow you to embed Java code directly into your HTML pages, in
contrast with HTTP servlets, in which you embed HTML inside Java code. JSP
is part of the Java 2 Enterprise Edition (J2EE).
JSP enables you to separate the dynamic content of a Web page from its
presentation. It caters to two different types of developers: HTML developers,
who are responsible for the graphical design of the page, and Java developers,
who handle the development of software to create the dynamic content.
Because JSP is part of the J2EE standard, you can deploy JSPs on a variety of
platforms, including WebLogic Server. In addition, third-party vendors and
application developers can provide JavaBean components and define custom
JSP tags that can be referenced from a JSP page to provide dynamic content.

JSP Tags
JSP scripting language include several tags or scripting elements that performs
various tasks such as declaring variables and methods, writing expressions, and
calling other JSP pages. These are known as JSP scripting elements. The different
types of scripting elements are summarized in the Table 1:
Table 1. JSP Tags
JSP Tag Brief Description Tag Syntax

Specifies translation time instructions to the JSP


engine.
Directive <%@ directives %>

Declaration Declares and defines methods and


variables. <%! variable dceclaration & method
Declaration definition %>

Allows the developer to write free-form Java


code in a JSP page.
Scriptlet <% some Java code %>

Used as a shortcut to print values in the output


HTML of a JSP page.
Expression <%= an Expression %>

Provides request-time instructions to the JSP


engine.
Action <jsp:actionName />

Used for documentation and for commenting


out parts of JSP code.
Comment <%– any Text –%>

Example code showing different types of JSP Tags:


<%-- Counter.jsp --%> <%-- Comment Tag --%>

<%@ page language="java" %> <%-- Directive Tag --%>


<%! int count = 0; %> <%-- Declaration Tag --%>
<% count++; %> <%-- Scriptlet Tag --%>
Welcome! You are visitor number
<%= count %> <%-- Expression Tag --%>
Note: Here, by using comment tag, example of five JSP tags are shown.

Discussions about the JSP Tags


Different types of JSP Tags are discussed below one-by-one.

1. Directive Tag:
Directive tags provide general information about the JSP page to the JSP engine. A
directive tag always starts with <%@ and ends with %>.

There are 3 types of directives: page, include, and taglib.


The general syntax for the 3 directives is:

<%@ page attribute-list %>


<%@ include attribute-list %>
<%@ taglib attribute-list %>

In the above shown syntax, the attribute-list represents one or more attribute value-
pairs that are specific to the directive. Some important points that are needed to be
remembered about the syntax of the directive are as follows:

 The tag names, their attributes, and their values are all case sensitive.
 The value must be enclosed within a pair of single or double quotes.
 A pair of single quotes is equivalent to a pair of double quotes.
 There must be no space between the equals sign (=) and the value.
A page directive informs the JSP engine about the overall properties of a JSP page.
For example, the following page directives inform the JSP engine that Java will be
used as scripting language in our JSP page:

<%@ page language=”java” %>


An include directive tells the JSP engine to include the contents of another file
(HTML, JSP, etc) into the current file. For example:
<%@ include file=”test.html” %>
or

<%@ include file=”test.jsp” %>


A taglib directive is used to associate a prefix with a tag library. For example:
<%@ taglib prefix=”test” uri=”taglib.tld” %>
2. Declaration Tag:
Declarations declare and define variables and methods that can be used in the JSP
page (a JSP declaration can contain any valid Java declaration including inner
classes and static code blocks. However, such declarations are rarely used). A
declaration always starts with <%! and ends with %>.
For e.g.: <%! int i = 0; %>
This declares an integer variable i and initializes to 0. The variable is initialized only
once when the page is first loaded by the JSP engine, and retains its value in
subsequent client requests i.e. the value of i is not reset to 0 each time we access the
page. It can contain any number of valid Java declaration statements. For example, the
following tag declares a variable and a method in a single tag:

<%!
String name[] = {“biswa”, “amit”, “sreejan”};

String getName(int i) {
return name[i];
}
%>

The above declaration can also be written using two separate JSP declaration tags.

3. Scriptlet Tag:

Scriptlets are used to embed any Java code fragments in the JSP page.

For example: <% i++; %>


Here the scriptlet tag is executed and the value of i is incremented each time the page
is requested. We can use scriptlets for printing HTML statements also. For e.g.:

<%@ page language="java" %>


<%! int i = 0; %>
<%
out.print("");
i++;
out.print("The value of i is now: " + i);
out.print("");
%>

4. Expression Tag:

Expression tags are used as a shortcut to print values in the output HTML in a JSP
page. Syntax of Expression tag is:

<%= variable %>


The variable denotes the variable value that is needed to be printed in the output
HTML page. For e.g.: <%= i %>

The expression is evaluated each time the page is accessed, and its value is then
embedded in the output HTML. Unlike variable declarations, expressions must not be
terminated with a semicolon. Thus, the following is not valid: <%= i; %>

The below tables denotes some valid and invalid JSP expressions:

Valid JSP Expressions:


Expression Explanation

<%= 500 %> An integral literal

<%= anInt*3.5/100-500 %> An arithmetic expression

<%= aBool %> A Boolean variable

<%= false %> A Boolean literal

<%= !false %> A Boolean expression

<%= getChar() %> A method returning a char

<%= Math.random() %> A method returning a double

<%= aVector %> A variable referring to a Vector object

<%= aFloatObj %> A method returning a float

<%= aFloatObj.floatValue() %> A method returning a float


<%= aFloatObj.toString() %> A method that returns a String object

You might also like