[go: up one dir, main page]

0% found this document useful (0 votes)
20 views17 pages

JAVA_UNIT_IV

The document provides an overview of Java Servlets, explaining their role in extending server capabilities for dynamic web applications through a request-response model. It contrasts Java Servlets with Common Gateway Interface (CGI), highlighting advantages such as performance and scalability. Additionally, it outlines the architecture, execution steps, and basic coding examples for creating and managing Java Servlets.

Uploaded by

mei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views17 pages

JAVA_UNIT_IV

The document provides an overview of Java Servlets, explaining their role in extending server capabilities for dynamic web applications through a request-response model. It contrasts Java Servlets with Common Gateway Interface (CGI), highlighting advantages such as performance and scalability. Additionally, it outlines the architecture, execution steps, and basic coding examples for creating and managing Java Servlets.

Uploaded by

mei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CLASS: I M.

Sc(CS) SUBJECT:ADVANCED JAVA PROGRAMMING 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:

Execution of Java Servlets


 Execution of Servlets basically involves Six basic steps:
1. The Clients send the request to the Web Server.
2. The Web Server receives the request.
3. The Web Server passes the request to the corresponding servlet.
1
4. The Servlet processes the request and generates the response in the form of output.
5. The Servlet sends the response back to the webserver.
6. The Web Server sends the response back to the client and the client browser displays it on the screen.
Need of Server-Side Extensions
 The Server-Side Extensions are nothing but the technologies that are used to create dynamic Web pages.
 Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web server.
 To meet this requirement, independent Web server providers offer some proprietary solutions in the form
of APIs (Application Programming Interface).
 These APIs allow us to build programs that can run with a Web server.
 Before learning about something, it’s important to know the need for that something, it’s not like that this
is the only technology available for creating Dynamic Web Pages.
 The Servlet technology is similar to other Web server extensions such as Common Gateway Interface
(CGI) scripts and Hypertext Preprocessor (PHP).
 However, Java Servlets are more acceptable since they solve the limitations of CGI such as low
performance and low degree scalability.
What is CGI (Common Gateway Interface)?
 CGI is actually an external application that is written by using any of the programming languages like C
or C++ and this is responsible for processing client requests and generating dynamic content.
 In CGI application, when a client makes a request to access dynamic Web pages, the Web server
performs the following operations:
 It first locates the requested web page i.e the required CGI application using URL.
 It then creates a new process to service the client’s request.
 Invokes the CGI application within the process and passes the request information to the application.
 Collects the response from the CGI application.
 Destroys the process, prepares the HTTP response, and sends it to the client.

WHAT ARE THE DIFFERENCE BETWEEN SERVLETS AND CGI?


Difference between Java Servlets and CGI

Servlet CGI (Common Gateway Interface)

Servlets are portable and efficient. CGI is not portable.

In Servlets, sharing data is possible. In CGI, sharing data is not possible.

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

Servlet Interface javax.servlet.*

ServletRequest Interface javax.servlet.*

ServletResponse Interface javax.servlet.*

GenericServlet Class javax.servlet.*

HttpServlet Class javax.servlet.http.*

HttpServletRequest Interface javax.servlet.http.*

HttpServletResponse Interface javax.servlet.http.*

Filter Interface javax.servlet.*

ServletConfig Interface javax.servlet.*


Advantages of a Java Servlet
 Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new request
received.
 Servlets, as written in Java, are platform independent.
 Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate
process. There is only a single instance that handles all requests concurrently. This also saves the memory
and allows a Servlet to easily manage the client state.
 It is a server-side component, so Servlet inherits the security provided by the Web server.
 The API designed for Java Servlet automatically acquires the advantages of the Java platforms such as
platform-independent and portability. In addition, it obviously can use the wide range of APIs created on
Java platforms such as JDBC to access the database.
 Many Web servers that are suitable for personal use or low-traffic websites are offered for free or at
extremely cheap costs eg. Java servlet. However, the majority of commercial-grade Web servers are
rather expensive, with the notable exception of Apache, which is free.
A SIMPLE JAVA SERVLETS
DISCUSS ABOUT JAVA SERVLETS WITH EXAMPLE.
 Steps to create a servlet example
 There are given 6 steps to create a servlet example. These steps are required for all the servers.
 The servlet example can be created by three ways:
 By implementing Servlet interface,
3
 By inheriting GenericServlet class, (or)
 By inheriting HttpServlet class
 The mostly used approach is by extending HttpServlet because it provides http request specific method
such as doGet(), doPost(), doHead() etc.
 Here, we are going to use apache tomcat server in this example. The steps are as follows:
 Create a directory structure
1. Create a Servlet
2. Compile the Servlet
3. Create a deployment descriptor
4. Start the server and deploy the project
5. Access the servlet
1. Create a directory structures
 The directory structure defines that where to put the different types of files so that web container may get
the information and responds to the client.
 The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the
directory structure that must be followed to create the servlet.

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

1) servlet-api.jar Apache Tomcat

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");

// Try to connect to a database via ODBC


conn = DriverManager.getConnection(
"jdbc:odbc:usingjsp");
}
catch (Exception exc)
{
// If there's an error, use the servlet logging API
getServletContext().log(
"Error making JDBC connection: ", exc);
}
}

The destroy Method


 Sometimes, the servlet engine decides that it doesn't need to keep your servlet loaded anymore. This
could happen automatically, or as the result of you deactivating the servlet from an administration tool.
Before the servlet engine unloads your servlet, it calls the destroy method to enable the servlet to perform
any necessary cleanup. The cleanup usually involves closing database connections, open files, and
network connections.
Destroy Method from JDBCServlet.java
public void destroy()
{
try
{
// Only try to close the connection if it's non-null
if (conn != null)
{
conn.close();

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.

READING DATA FROM A CLIENT


HOW TO READING DATA FROM A CLIENT IN JAVA SERVLETS.
 To read data from a client in Java servlets, you can use the `HttpServletRequest` object provided by the
Servlet container. Here's a basic example of how you can read data sent by a client in a Java servlet:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class YourServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String inputData = request.getParameter("inputData");
// Process the input data here
response.getWriter().println("Data received from client: " + inputData);
}
}
 In this example, we are using the `doPost` method to handle data sent via a POST request. We retrieve the
data sent by the client using `request.getParameter("inputData")`, where `'inputData'` is the name of the
input field in the client's form.
 Remember to configure your web.xml file or use annotations to map your servlet to a specific URL
pattern. You can then access your servlet from the client-side using a form submission or an AJAX
request.
READING HTTP REQUEST HEADER
HOW TO READING HTTP REQUEST HEADER IN JAVA SERVLETS.
 To read the HTTP request header in Java Servlets, you can use the `HttpServletRequest` object provided
by the Servlet API. Here's a simple example to demonstrate how you can access the headers:
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
String userAgent = request.getHeader("User-Agent");
String contentType = request.getHeader("Content-Type");

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.

SENDING DATA TO A CLIENT AND WRITING THE HTTP RESPONSE HEADER


HOW TO SENDING DATA TO A CLIENT AND WRITING THE HTTP RESPONSE.
 A web application is built using Servlet technology (resides at the server-side and generates a dynamic
web page). Because of the Java programming language, servlet technology is dependable and scalable.
CGI (Common Gateway Interface) scripting language was widely used as a server-side programming
language prior to Servlet.
Servlet – Response
 A servlet can use this object to help it provide a response to the client. A ServletResponse object is
created by the servlet container and passed as an argument to the servlet’s service function.

 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.

JAVA SERVER PAGES


JSP OVERVIEW
WHAT IS JAVA SERVER PAGES?
 JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content. This
helps developers insert java code in HTML pages by making use of special JSP tags, most of which start
with <% and end with %>.
 A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application. Web developers write JSPs as text files that combine HTML or
XHTML code, XML elements, and embedded JSP actions and commands.
 Using JSP, you can collect input from users through Webpage forms, present records from a database or
another source, and create Webpages dynamically.
 JSP tags can be used for a variety of purposes, such as retrieving information from a database or
registering user preferences, accessing JavaBeans components, passing control between pages, and
sharing information between requests, pages etc.
WHY USE JSP?
 JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway
Interface (CGI). But JSP offers several advantages in comparison with the CGI.
 Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages
itself instead of having separate CGI files.
 JSP are always compiled before they are processed by the server unlike CGI/Perl which requires the
server to load an interpreter and the target script each time the page is requested.
 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the
powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
 JSP pages can be used in combination with servlets that handle the business logic, the model supported
by Java servlet template engines.
 Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This
means that JSP can play a part in the simplest applications to the most complex and demanding.
Advantages of JSP
 Following table lists out the other advantages of using JSP over other technologies −
 Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is written in
Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second,
it is portable to other operating systems and non-Microsoft Web servers.
 Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
 Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real" programs
that use form data, make database connections, and the like.
 JavaScript: JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.
 Static HTML: Regular HTML, of course, cannot contain dynamic information.
INSTALLATION
HOW TO INSTALL JSP?
 The environment setup for JSP mainly consists of 3 steps:
 Setting up the JDK.
 Setting up the webserver (Tomcat).
 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.

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 %>

Different types of JSP directives :


There are three different JSP directives available. They are as follows:
EXPRESSIONS
EXPLAIN ABOUT EXPRESSIONS WITH EXAMPLE.
 A JSP expression is used to insert the value of a scripting language expression, converted into a string,
into the data stream returned to the client. When the scripting language is the Java programming
language, an expression is transformed into a statement that converts the value of the expression into a
String object and inserts it into the implicit out object.
 The syntax for an expression is as follows:
<%= scripting-language-expression %>
 In the web service version of the hello1 application, response.jsp contains the following scriptlet, which
gets the proxy that implements the service endpoint interface. It then invokes the sayHello method on the
proxy, passing the user name retrieved from a request parameter:
<%
String resp = null;
try {
Hello hello = new HelloService().getHelloPort();
resp = hello.sayHello(request.getParameter("username"));
} catch (Exception ex) {

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 --%>

<%@page import = "java.util.Date"%>


<%Date d = new Date();%>
<%=d%>
 contentType: This defines the format of data that is being exchanged between the client and the
server. It does the same thing as the setContentType method in servlet used to.

14
Syntax: <%@page contentType="value"%>
Example:
<%-- JSP code to demonstrate how to use
page directive to set the type of content --%>

<%@page contentType = "text/html" %>


<% = "This is sparta" %>
DECLARATIONS
EXAPLIN ABOUT DECLARATIONS WITH EXAMPLE.
 A JSP declaration is used to declare variables and methods in a page’s scripting language. The syntax for
a declaration is as follows:
<%! scripting-language-declaration %>
 When the scripting language is the Java programming language, variables and methods in JSP
declarations become declarations in the JSP page’s servlet class.
Initializing and Finalizing a JSP Page
 We can customize the initialization process to allow the JSP page to read persistent configuration data,
initialize resources, and perform any other one-time activities; to do so, you override the jspInit method
of the JspPage interface. You release resources using the jspDestroy method. The methods are defined
using JSP declarations.
 For example, an older version of the Duke’s Bookstore application retrieved the object that accesses the
bookstore database from the context and stored a reference to the object in the variable bookDBAO in the
jspInit method. The variable definition and the initialization and finalization methods jspInit and
jspDestroy were defined in a declaration:
<%!
private BookDBAO bookDBAO;
public void jspInit() {
bookDBAO =
(BookDBAO)getServletContext().getAttribute("bookDB");
if (bookDBAO == null)
System.out.println("Couldn’t get database.");
}
%>
 When the JSP page was removed from service, the jspDestroy method released the BookDBAO variable.
<%!
public void jspDestroy() {
bookDBAO = null;
}
%>
A COMPLETE EXAMPLE
Example:
 The following JSP program calculates factorial values for an integer number, while the input is taken
from an HTML form.
input.html
<html>
<body>
<form action="Factorial.jsp">
Enter a value for n: <input type="text" name="val">
<input type="submit" value="Submit">
</form>
</body>
</html>
Factorial.jsp
<html>
<body>
<%!

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

You might also like