Java UNIT 4
Java 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.
// 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>
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.
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.
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
Eg.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet {
response.setContentType("text/html");
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);
}}
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
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
Content- This header is applicable only for POST requests and gives the size
Length of the POST data
Host This specifies host and port which are given in the original URL
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.
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.
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.
hello.html
<html> <body> <h1>Hello, World!</h1> </body> </html>
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 {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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
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
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 %>.
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:
<%!
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.
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:
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: