JAVA_UNIT_IV
JAVA_UNIT_IV
SERVLETS
JAVA SERVLETS
JAVA SERVLETS AND CGI PROGRAMMING
EXPLAIN ABOUT JAVA SERVLETS.
WHAT IS CGI? EXPLAI IT.
INTRODUCTION:
Java Servlets are Java classes used to extend the capabilities of servers that host applications accessed
through a request-response programming model.
They provide a way to develop web applications that generate dynamic and interactive content, by
responding to requests from clients and producing responses accordingly.
Servlets are often used in conjunction with the JavaServer Pages (JSP) technology to create web
applications.
They run on a web server and can handle HTTP requests from web clients, processing forms, generating
dynamic content, and managing sessions.
What is Java Servlet?
Java Servlets are the Java programs that run on the Java-enabled web server or application server. They
are used to handle the request obtained from the web server, process the request, produce the response,
and then send a response back to the web server.
Properties of Java Servlet
The properties of Servlets are as follows:
Servlets work on the server side.
Servlets are capable of handling complex requests obtained from the web server.
Java Servlets Architecture
Servlet Architecture can be depicted from the image itself as provided below as follows:
Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.
2
Servlet CGI (Common Gateway Interface)
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
Servlets APIs
Servlets are built from two packages:
javax.servlet(Basic)
javax.servlet.http(Advance)
Various classes and interfaces present in these packages are:
Component Type Package
2. Create a Servlet
There are three ways to create the servlet.
By implementing the Servlet interface
By inheriting the GenericServlet class
By inheriting the HttpServlet class
The HttpServlet class is widely used to create the servlet because it provides methods to handle http
requests such as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are
inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get
request is the default request.
Here is an example of a simple Java servlet that just prints "Hello, World!" when accessed:
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
response.getWriter().println("<html><body><h1>Hello, World!</h1></body></html>");
} }
3. Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:
4
Jar file Server
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
Two ways to load the jar file
set classpath
paste the jar file in JRE/lib/ext folder
4. Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the information about the
servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are many xml
parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the simple
servlet program.
ANOTOMY OF A JAVA SERVLET
EXPLAIN IN DETAIL ABOUT ANATOMY OF A JAVA SERVLETS.
A Java Servlet is a Java programming language class that is used to extend the capabilities of servers that
host applications accessed through a web browser.
Servlets are server-side programs and behave like a middle layer between a request coming from a web
browser and a server that processes the request. They generate dynamic web content and handle HTTP
requests and responses.
Servlets are the foundation of Java web application development. They are usually packaged as WAR
(Web Application Archive) files and deployed on a web server.
Servlets can receive and respond to requests from clients, such as web browsers, by implementing the
javax.servlet.Servlet interface. They can handle various types of requests, including GET, POST, PUT,
and DELETE requests, by overriding methods such as doGet(), doPost(), doPut(), and doDelete().
Servlets can interact with databases, handle user authentication, and perform other server-side activities.
They are commonly used in conjunction with JavaServer Pages (JSP) to create dynamic web applications.
Overall, Java Servlets play a crucial role in the development of robust and interactive web applications
using Java technology.
They provide a scalable and platform-independent way to handle web requests and generate dynamic web
content.
The Anatomy of a Servlet
As you just saw in the HelloWorldServlet, a servlet is a Java class that implements a few important
methods. You can choose to implement these methods yourself or create a subclass of an existing servlet
class that already implements them. The Servlet interface defines the methods that are required for a Java
class to become a servlet. The interface definition is shown in Listing 3.2.
The Definition of the Servlet Interface
package javax.servlet;
public interface Servlet
{
public void destroy();
public ServletConfig getServletConfig();
public String getServletInfo();
public void init(ServletConfig config)
throws ServletException;
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, java.io.IOException;
5
}
Most of the time, you will create a servlet by subclassing either GenericServlet or HttpServlet. Both of
these classes implement the Servlet interface, but they provide a few handy features that make them
preferable to implementing the Servlet interface yourself.
The service Method
The heart of any servlet is the service method.
The servlet engine calls the service method to handle each request from a browser, passing in an object
containing both information about the request that invoked the servlet and information about sending
back a response.
The service method is the only method that a servlet is actually required to implement. The service
method is declared this way:
public void service(ServletRequest request,
ServletResponse response)
throws java.io.IOException
The init Method
Many times, a servlet needs to perform some initialization one time before it begins to handle requests.
The init method in a servlet is called just after the servlet is first loaded, but before it begins to handle
requests.
A simple init method that initializes a database connection.
init Method from JDBCServlet.java
protected Connection conn;
public void init()
{
try
{
// Make sure the JdbcOdbcDriver class is loaded
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
6
}
}
catch (SQLException exc)
{
// If there's an error, use the servlet logging API
getServletContext().log(
"Error closing JDBC connection: ", exc);
}
}
The getServletInfo and getServletConfig Methods
If you are subclassing GenericServlet or HttpServlet, you probably won't need to override the
getServletInfo or getServletConfig methods.
The Servlet API documentation recommends that you return information such as the author, version, and
copyright from the getServletInfo method. Although there is no specific format for the string returned by
the method, you should return only plain text, without any HTML or XML tags embedded within it.
The getServletConfig method returns the ServletConfig object that was passed to the servlet in the init
method. Unless you are keeping track of the config object yourself, your best bet is to leave this method
alone and let the superclass handle it.
7
response.setContentType("text/plain");
response.getWriter().println("User-Agent: " + userAgent);
response.getWriter().println("Content-Type: " + contentType);
}
}
In this example, we're using the `getHeader(String name)` method of the `HttpServletRequest` object to
retrieve specific headers like "User-Agent" and "Content-Type". You can access any header by specifying
its name as a parameter to the `getHeader` method.
Remember to deploy this servlet in your servlet container (e.g., Apache Tomcat) and map it to a specific
URL pattern in your `web.xml` file or using annotations if you're using Servlet 3.0 annotations.
Use the ServletOutputStream supplied by getOutputStream to deliver binary data in a MIME body
response (). Use the PrintWriter object given by getWriter to deliver character data (). Use a
ServletOutputStream and manually control the character sections to blend binary and text data, for
example, to generate a multipart response.
The setCharacterEncoding(java.lang.String) and setContentType(java.lang.String) methods can be used
to provide the charset for the MIME body response, or the setLocale(java.util.Locale) method can be used
to specify it implicitly. Implicit requirements are overridden by explicit specifications. ISO-8859-1 will
be used if no charset is supplied. For the character encoding to be utilized, the setCharacterEncoding,
setContentType, or setLocale methods must be called before getWriter and before committing the
response.
Some Important Methods of ServletResponse
Methods Description
String getCharacterEncoding() It returns the name of the MIME charset that was used in the body of
the client response.
String getContentType() It returns the response content type. e.g. text, HTML etc.
ServletOutputStream This method returns a ServletOutputStream that may be used to write
getOutputStream() binary data to the response.
PrintWriter getWriter() The PrintWriter object is used to transmit character text to the client.
void setContentLength(int len) Sets the length of the response’s content body. This function sets the
HTTP Content-Length header in HTTP servlets.
void setContentType(String type) Sets the type of the response data.
void setBufferSize(int size) specifies the recommended buffer size for the response’s body.
int getBufferSize() Returns the buffer size
void flushBuffer() Any material in the buffer will be forced to be written to the client.
boolean isCommitted() If the response has been committed, this method returns a boolean.
8
void setLocale(Locale loc) If the answer hasn’t been committed yet, it sets the response’s
location.
void reset() Clears the buffer’s data, as well as the headers and status code. To
acquire a comprehensive list of ways, go here.
To send data to a client and write the HTTP response header in Java servlets, you can use the
HttpServletResponse object provided by the servlet container. Here's an example code snippet to
demonstrate this:
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class YourServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
// Set the content type of the response
response.setContentType("text/html");
// Set any additional headers if needed
response.setHeader("CustomHeader", "CustomValue");
// Get the PrintWriter object to write the response body
PrintWriter out = response.getWriter();
// Write the response body
out.println("<html>");
out.println("<head><title>Response from GPTGO</title></head>");
out.println("<body>");
out.println("<h1>Hello Client!</h1>");
out.println("<p>This is the response from GPTGO.</p>");
out.println("</body>");
out.println("</html>");
// Close the PrintWriter after writing the response
out.close();
}
}
In this example, we define a servlet class that extends HttpServlet and overrides the `doGet` method to
handle HTTP GET requests. Inside the `doGet` method, we set the content type and any custom headers
using the HttpServletResponse object. We then use the PrintWriter object to write the response body in
HTML format.
WORKING WITH COOKIES
EXPLAIN ABOUT HOW TO WORKING WITH COOKIES.
In Java servlets, cookies are used to store information on the client's machine for later retrieval. Here's
how you can work with cookies in a Java servlet:
1. To create a cookie, you can use the HttpServletResponse object in your servlet:
Cookie cookie = new Cookie("username", "JohnDoe");
response.addCookie(cookie);
2. To retrieve cookies sent by the client, you can use the HttpServletRequest object in your servlet:
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
// Do something with the cookie values
}
}
3. To set the expiration time of a cookie, you can use the setMaxAge() method:
cookie.setMaxAge(24 * 60 * 60); // Cookie will expire in 1 day
9
4. To delete a cookie, you can set its max age to 0:
cookie.setMaxAge(0);
response.addCookie(cookie);
Remember to always be mindful of what information you store in cookies and ensure that sensitive
information is not stored in plain text.
10
For windows:
right-click on My Computer->
select Properties->
Click on Advanced System setting ->
Click on Environment Variables ->
Then, update the PATH value5 and press the OK button.
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
This is the final page that you will see in your browser. If you are not getting the required result then start
again from tomcat installation process.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend
Development - Live Course and embark on an exciting journey to master backend development
efficiently and on schedule.
JSP TAGS
WRITE ABOUT JSP TAGS.
JSP tags are a fundamental component of JavaServer Pages (JSP) technology, which is used to create
dynamic web content. There are several types of JSP tags, such as:
1. Directive tags: These provide global information about the JSP page and are used for importing
classes or setting global variables.
2. Scripting tags: These are used to embed Java code within the JSP page, allowing for dynamic
content generation.
3. Action tags: These are used to perform specific actions, like including files, forwarding requests, or
setting properties.
11
4. Expression language (EL) tags: These allow JSP pages to access data stored in JavaBeans
components or other shared data sources.
Overall, JSP tags are essential for creating interactive and dynamic web applications.
Declaration tag:
Whenever we use any variables as a part of JSP we have to use those variables in the form of declaration
tag i.e., declaration tag is used for declaring the variables in JSP page.
Syntax: <%! Variable declaration or method definition %>
When we declare any variable as a part of declaration tag those variables will be available as data
members in the servlet and they can be accessed through out the entire servlet. When we use any methods
definition as a part of declaration tag they will be available as member methods in servlet and it will be
called automatically by the servlet container as a part of service method.
For example-1:
<%! int a = 10, b = 30, c;%>
For example-2:
<%!
int count() {
return (a + b);
}
%>
Expression tag:
Expression tags are used for writing the java valid expressions as a part of JSP page.
Syntax: <%= java valid expression %>
Whatever the expression we write as a part of expression tags that will be given as a response to client by
the servlet container. All the expression we write in expression tag they will be placed automatically in
out.println () method and this method is available as a part of service method.
For example-1:
<%! int a = 10, b = 20 %>
<%= a + b%>
The equivalent servlet code for the above expression tag is out.println (a+b); out is implicit object of
JSPWriter class.
For example-2:
<%= new java.util.Date()%>
out.println (new java.util.Date ());
Scriplet tag:
Scriplets are basically used to write a pure java code. Whatever the java code we write as a part of
scriplet, that code will be available as a part of service () method of servlet.
Syntax:<% pure java code%>
COMPONENTS OF A JSP PAGE
WHAT ARE THE COMPONENTS OF JSP? EXPLAIN IT.
A JSP page typically consists of the following components:
1. Directives: These provide instructions to the JSP container about aspects such as imports and error
handling.
2. Declarations: Used to declare variables and methods in a JSP page.
3. Scriptlets: Enclosed within `<% %>` tags, scriptlets contain Java code that is executed when the JSP
page is processed.
4. Expressions: Enclosed within `<%= %>` tags, expressions are used to output dynamic data directly to
the response stream.
5. Actions: These are XML-based tags that control the behavior of JSP pages, such as including other
resources or forwarding requests.
6. Comments: Similar to HTML comments, JSP comments are used to document the code and are not
visible to the client-side.
These components work together to create dynamic web pages using Java Server Pages.
Structure of JSP Page :
JSPs are comprised of standard HTML tags and JSP tags. The structure of JavaServer pages are simple
and easily handled by the servlet engine. In addition to HTML ,you can categorize JSPs as following -
12
Directives
Declarations
Scriptlets
Comments
Expressions
Directives:
A directives tag always appears at the top of your JSP file. It is global definition sent to the JSP engine.
Directives contain special processing instructions for the web container. You can import packages, define
error handling pages or the session information of the JSP page. Directives are defined by using <%@
and %> tags.
Syntax - <%@ directive attribute="value" %>
Declarations :
This tag is used for defining the functions and variables to be used in the JSP. This element of JSPs
contains the java variables and methods which you can call in expression block of JSP page. Declarations
are defined by using <%! and %> tags. Whatever you declare within these tags will be visible to the rest
of the page.
Syntax - <%! declaration(s) %>
Scriptlets:
In this tag we can insert any amount of valid java code and these codes are placed in _jspService method
by the JSP engine. Scriptlets can be used anywhere in the page. Scriptlets are defined by using <% and
%> tags.
Syntax - <% Scriptlets%>
Comments :
Comments help in understanding what is actually code doing. JSPs provides two types of comments for
putting comment in your page. First type of comment is for output comment which is appeared in the
output stream on the browser. It is written by using the <!-- and --> tags.
Syntax - <!-- comment text -->
Second type of comment is not delivered to the browser. It is written by using the <%-- and --%> tags.
Syntax - <%-- comment text --%>
Expressions :
Expressions in JSPs is used to output any data on the generated page. These data are automatically
converted to string and printed on the output stream. It is an instruction to the web container for executing
the code with in the expression and replace it with the resultant output content. For writing expression in
JSP, you can use <%= and %> tags.
Syntax - <%= expression %>
13
resp = ex.toString();
}
%>
A scripting expression is then used to insert the value of resp into the output stream:
<h2><font color="black"><%= resp %>!</font></h2>
SCRIPTLETS
EXPLAIN ABOUT SCRIPLETS WITH EXAMPLE.
A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page.
The syntax for a scriptlet is as follows:
<%
scripting-language-statements
%>
When the scripting language is set to java, a scriptlet is transformed into a Java programming language
statement fragment and is inserted into the service method of the JSP page’s servlet. A programming
language variable created within a scriptlet is accessible from anywhere within the JSP page.
In the web service version of the hello1 application, greeting.jsp contains a scriptlet to retrieve the request
parameter named username and test whether it is empty. If the if statement evaluates to true, the response
page is included. Because the if statement opens a block, the HTML markup would be followed by a
scriptlet that closes the block.
<%
String username = request.getParameter("username");
if ( username != null && username.length() > 0 ) {
%>
<%@include file="response.jsp" %>
<%
}
%>
DIRECTIVES
EXAPLIN ABOUT DIRECTIVES WITH EXAMPLE.
JSP directives are the elements of a JSP source code that guide the web container on how to translate the
JSP page into its respective servlet.
Syntax : <%@ directive attribute = "value"%>
Directives can have a number of attributes that you can list down as key-value pairs and separate by
commas.
The blanks between the @ symbol and the directive name, and between the last attribute and the closing
%>, are optional.
Different types of JSP Directives:
There are three different JSP directives available. They are as follows:
Page Directives : JSP page directive is used to define the properties applying the JSP page, such as the
size of the allocated buffer, imported packages, and classes/interfaces, defining what type of page it is,
etc.
The syntax of JSP page directive is as follows:<%@page attribute = "value"%>
Different properties/attributes : The following are the different properties that can be defined using
page directive :
import: This tells the container what packages/classes are needed to be imported into the program.
Syntax: <%@page import = "value"%>
example
<%-- JSP code to demonstrate how to use page
directive to import a package --%>
14
Syntax: <%@page contentType="value"%>
Example:
<%-- JSP code to demonstrate how to use
page directive to set the type of content --%>
15
long n, result;
String str;
long fact(long n) {
if(n==0)
return 1;
else
return n*fact(n-1);
}
%>
<%
str = request.getParameter("val");
n = Long.parseLong(str);
result = fact(n);
%>
<b>Factorial value: </b> <%= result %>
</body>
</html>
POSSIBLE QUESTIONS
PART A
1. What is a Java Servlet?
a) A type of coffee popular in Indonesia
b) A server-side program that runs on the server and creates dynamic web content
c) A type of insect found in tropical regions
d) A programming language developed by Sun Microsystems
2. Which method is used to initialize a servlet?
a) init()
b) start()
c) setup()
d) begin()
3. What is the purpose of the doGet() method in a servlet?
a) To handle HTTP GET requests
b) To initiate a database connection
c) To send email notifications
d) To generate random numbers
4. What is the difference between GET and POST requests in servlets?
a) GET requests are used for retrieving data, while POST requests are used for submitting
data
b) GET requests are more secure than POST requests
c) POST requests require authentication, while GET requests do not
d) GET requests are faster than POST requests
5. What is the purpose of the destroy() method in a servlet?
a) To destroy the servlet instance
b) To delete the servlet from the server
c) To close the browser window
d) To restart the server
6. What is the purpose of the <jsp:include> tag in JSP?
a) To include the content of another file in the current JSP page
b) To declare a custom tag library
c) To define a Java scriptlet
d) To set an attribute in the request scope
7. Which JSP tag is used to declare reusable code that can be included in multiple JSP pages?
a) <jsp:useBean>
b) <jsp:include>
16
c) <jsp:declaration>
d) <jsp:directive.include>
8. What is the purpose of the <jsp:param> tag in JSP?
a) To declare a parameter in a custom tag
b) To include a parameter value in the URL string
c) To set a parameter in the page scope
d) To include a parameter in a request dispatcher
9. Which JSP tag is used to iterate over a collection or array in JSP?
a) <c:forEach>
b) <jsp:include>
c) <jsp:useBean>
d) <c:if>
10. What is the purpose of the <jsp:forward> tag in JSP?
a) To forward the request to another resource
b) To include the content of another file in the current JSP page
c) To set a response header in the JSP page
d) To redirect the client to another URL
PART B
1. Explain about Java Servlets.
2. What is CGI? Explain it.
3. What are the difference between Servlets and CGI?
4. How to reading data from a client in Java Servlets.
5. How to reading http request header in Java Servlets.
6. What are java server pages?
7. Why use JSP?
8. How to install JSP?
9. What are the Components of JSP? Explain it.
10. Explain about Directives with Example.
11. Explain about Expressions with Example.
12. Explain about Scriplets with Example.
13. Explain about Declarations with Example.
PART C
1. Discuss about Java Servlets with Example.
2. How to Sending Data to a Client and Writing the HTTP Response.
3. Explain about How to Working With Cookies.
4. Write about JSP tags.
5. Explain in detail about anatomy of a Java Servlets.
UNIT – IV COMPLETED
17