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

Solved Question Paper (Unit-3 - Unit -4).Docx

Uploaded by

Shivam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Solved Question Paper (Unit-3 - Unit -4).Docx

Uploaded by

Shivam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Unit -3

Q1. Explain the life-cycle of Java Servlets.


Solution:
● A servlet is a Java Programming language class that is used to extend the capabilities of
servers that host applications accessed by means of a request-response programming model.
● Servlets can respond to any type of request; they are commonly used to extend the
applications hosted by web servers.
● It is also a web component that is deployed on the server to create a dynamic web page.

How Servlet works:


● Servlet is a class instantiated by the server to produce a dynamic response.
● A client sends a request to the server and the server generates the response, analyses it and
sends the response to the client.
● Java servlets serve the same purpose as programs implemented using common Gateway
Interface (CGI). But servlets offer several advantages in comparison to CGI.
o Performance is significant better.
o Servlets execute within the address space of a web server. It is necessary to create
separate processes to handle each client request.
o Servlet are platform independent between they are written in Java.
o Java security Manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
o The full functionality of the java class library is available to a servlet. It can communicate
with applets, database or other software via sockets and RMI machine that you have seen
already.

Servlet Life Cycle


The web container maintains the life cycle of a servlet instance:

1. Servlet class is Loaded


2. Servlet instance is created
3. init method is created
4. Service method is invoked
5. Destroy method is invoked.

When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all
the servlets.

The servlet is initialized by calling the init() method. The Servlet.init() method is called by the
Servlet container to indicate that this Servlet instance is instantiated successfully and is about to
put into service.
The servlet then calls service() method to process a client’s request. This method is invoked to
inform the Servlet about the client requests.
The servlet is terminated by calling the destroy().
The destroy() method runs only once during the lifetime of a Servlet and signals the end of the
Servlet instance.

1. Servlet class is loaded:


The class loader is responsible to load servlet class. The servlet class is loaded when the first
request fort the servlet is received by the web container.

2. The init() Method:

The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.

3. init method is invoked:

● The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations.

● The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.

● When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate.

● The init ( ) method simply creates or loads some data that will be used throughout the life of
the servlet.

The init ( ) method looks like this −


public void init ( servletConfig config) throws ServletException {

// Initialization code...
}

4. Service method is invoked:

● The service() method is the main method to perform the actual task.
● The servlet container (i.e. web server) calls the service() method to handle requests coming
from the client( browsers) and to write the formatted response back to the client.
● Each time the server receives a request for a servlet, the server spawns a new thread and calls
service.
● The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and
calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response) throws ServletException,


IOException

5. The destroy ( ) Method:

● The destroy() method is called only once at the end of the life cycle of a servlet.
● This method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
● After the destroy( ) method is called, the servlet object is marked for garbage collection.

The destroy method definition looks like this −

public void destroy( ) {

// Finalization code...

Example: Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically write servlets that extend
javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is
specially designed to handle HTTP requests.

Sample Code: Print Hello world


// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {

// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}
Q2. Explain client –server technology.
Solution:
● Java Servlets: A servlet is a Java Programming language class that is used to extend the
capabilities of servers that host applications accessed by means of a request-response
programming model.
● Servlets can respond to any type of request; they are commonly used to extend the
applications hosted by web servers.
● It is also a web component that is deployed on the server to create a dynamic web page.

How Servlet works:


● Servlet is a class instantiated by the server to produce a dynamic response.
● A client sends a request to the server and the server generates the response, analyses it and
sends the response to the client.
● Java servlets serve the same purpose as programs implemented using common Gateway
Interface (CGI). But servlets offer several advantages in comparison to CGI.
o Performance is significant better.
o Servlets execute within the address space of a web server. It is necessary to create
separate processes to handle each client request.
o Servlet are platform independent between they are written in Java.
o Java security Manager on the server enforces a set of restrictions to protect the resources
on a server machine. So servlets are trusted.
o The full functionality of the java class library is available to a servlet. It can communicate
with applets, database or other software via sockets and RMI machine that you have seen
already.

Java Servlet Architecture


● First, it reads the explicit data sent by the clients (browsers). This data can include an HTML
form on a Web page, an applet or a custom HTTP client program.
● It also reads implicit HTTP request data sent by the clients (browsers). This can include
cookies, media types and compression schemes the browser understands, and so forth.

● After that, the servlet processes the data and generate the results. This process may require
communicating to a database, executing an RMI, invoking a Web service, or computing the
response directly.
● After processing, it sends the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or XML), binary (GIF
images), or Excel formats.
● Finally, it also sends the implicit HTTP response to the clients (browsers). This includes telling
the browsers or other clients what type of document is being returned.
Execution of Servlets:
● The client sends the request to the web server.
● The web server receives the request.
● The web server passes the request to the corresponding servlets.
● The servlets process the request and generate the response in the form of output.
● The servlet sends the responses back to the web server.

Q3. Differentiate between GET and POST Request in Java Servlets.


Solution:
GET and POST
Two common methods for the request-response between a server and client are:
● GET- It requests the data from a specified resource
● POST- It submits the processed data to a specified resource

Get Method:

GET method is used to appends form data to the URL in name or value pair. If we use GET, the
length of URL will remain limited. It helps users to submit the bookmark the result. It is better
for the data which does not require any security or having images or word documents.
Java Get Request Program
The following program demonstrates how one can make the GET request to a server.

Abc.html

1. <html
2. xmlns="http://www.w3.org/1999/xhtml">
3. <body>
4. <form method="get" action="GetDataUsingget.java">
5. User Name:
6. <input id="txtuserName" type="text" name="username" />

7. <input id="btnSubmit" type="submit" value="Submit data


using GET" />
8. </form>
9. </body>
10. </html>

File Name: GetDataUsingget.java

1. <html
2. xmlns="http://www.w3.org/1999/xhtml">
3. </head>
4. <body>
5. <form id="form1" runat="server">
6. <div>
7. Welcome
8. <b><% out.println(Request.QueryString["username"].ToSt
ring()); %>
9. </b>
10. </div>
11. </form>
12. </body>undefined</html>

Output
From there i have entered my name and then data will be posted on "GetDataUsingget.aspx"
page.

After clicking on button this will be like as shown in below picture

Post Method:
POST is a method that is supported by HTTP and depicts that a web server accepts the data
included in the body of the message. It is often used by World Wide Web to send user generated
data to the web server or when you upload file.

Java Post Request Program


The following program demonstrates how one can make the POST request to a server.

GET POST

1) In case of Get request, only limited amount of In case of post request, large amount of
data can be sent because data is sent in header. data can be sent because data is sent in
body.

2) Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second Post request is non-idempotent.


request will be ignored until response of first
request is delivered

5) Get request is more efficient and used more Post request is less efficient and used less
than Post. than get.

Q4. Difference between Generic Servlet & HTTP Servlet?


Solution:
● The Key difference between GenericServlet and HttpServlet is that the GenericServlet is
protocol independent and whereas HttpServlet is protocol dependent.
● GenericServlet belongs to javax.servlet.GenericServlet package while HttpServlet belongs to
javax.servlet.http.HttpServlet package.

GenericServlet and HttpServlet Comparison Chart

GenericServlet HttpServlet

1. It is defined by javax.servlet package. It is defined by javax.servlethttp package.

2. It describes protocol-independent servlet It describes protocol-dependent servlet.

3. GenericServiet is not dependent on any HttpServlet is a dependent protocol and is only


particular protocol. It can be used with any used with HTTP protocol.
protocol such as HTTP, SMTP, FTP, and so
on.

4. All methods are concrete except the service() All methods are concrete (non-abstract).
method. service() method is an abstract service() is non-abstract method. service() can
method. be replaced by doGet() or doPost() methods.

5. The service method is abstract. The service method is non-abstract


GenericServlet HttpServlet

6. It forwards and includes a request and is also It forwards and includes a request but it is not
possible to redirect a request. possible to redirect the request.

7. GenericServlet doesn’t allow session HTTPServlet allows session management with


management with cookies and HTTP cookies and HTTP sessions.
sessions.

8. It is an immediate child class of Servlet It is an immediate child class of GenericServlet


interface. class.

9. GenericServlet is a superclass of HttpServlet HttpServlet is a subclass of GenericServlet


class. class.

GenericServlet

● GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides


the implementation of all the methods of these interfaces except the service method.
● GenericServlet class can handle any type of request so it is protocol-independent.
● You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.

Methods of GenericServlet class


There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that
servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public void init() it is a convenient method for the servlet programmers, now there is no
need to call super.init(config)
6. public ServletContext getServletContext() returns the object of ServletContext.
7. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
8. public String getServletName() returns the name of the servlet object.

Example

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

public class First extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}

HttpServlet
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Methods of HttpServlet class


There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the
protected service method by converting the request and response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the
request from the service method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the
GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the
POST request. It is invoked by the web container.
5. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the
DELETE request. It is invoked by the web container.
6. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT
request. It is invoked by the web container.

Methods of HttpServlet Class


1. doGet() Method
This method is used to handle the GET request on the server-side. This method also
automatically supports HTTP HEAD (HEAD request is a GET request which returns nobody in
response ) request. The GET type request is usually used to preprocess a request.

Modifier and Type: protected void


protected void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{

// Servlet code
}
Parameters:
● request – an HttpServletRequest object that contains the request the client has made of the
servlet.
● response – an HttpServletResponse object that contains the response the servlet sends to the
client.
Exceptions:
● IOException – if an input or output error is detected when the servlet handles the GET
request.
● ServletException – Use to handle the GET request.

2. doPost() Method

● This method is used to handle the POST request on the server-side.


● This method allows the client to send data of unlimited length to the webserver at a time.
● The POST type request is usually used to post-process a request.

Modifier and Type: protected void


Syntax:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException
{
// Servlet code
}
Parameter:
● request – an HttpServletRequest object that contains the request the client has made of the
servlet.
● response – an HttpServletResponse object that contains the response the servlet sends to the
client.
Throws:
● IOException – if an input or output error is detected when the servlet handles the POST
request.
● ServletException – Use to handle the POST request.

Introduction to Web. Xml


● xml stands Extensible Markup Language.
● xml is markup language much like html.
● Xml defines set of rules for encoding document in a format that readable by both as human
and machine.
● Xml was designed to carry and store data, not to display data. Xml is designed to be
self-descriptive.
Web.xml defines mapping between URL paths and servlets that handle requests with those
paths. The web.xml file provides configuration and deployment deployment information for the
Web components that comprise a Web application. The web.xml descriptor files represents the
core of the java application. The web.xml file is located in WEB-INF directory of web
application.
Servlet web.xml is an application deployment descriptor that describes the
classes, configuration, and resources for a web server application that uses server web
requests. When the web server receives an application request, it contains the deployment
descriptor for mapping the URL for the request code, which was used to handle the request.
Note: Deployment is a term that is commonly used in web application development. Once a web
application is ready to be used/tested, we create an enterprise archive file (EAR file). We need to
place this EAR file in this server and point it to the server so that requests to access that web
application are serviced by the server. This is called deployment. There are various tools that
help us in doing a deploy. You can use the servers console interface to deploy or you can use
tools like Apache Ant.
Example:
Web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
Elements in Web.xml
Description of elements Used in web.xml file:
1. <web-aap>: This element represents whole application of web.xml file
2. <servlet>: This is the sub element of and represents the servlet
3. <servlet-name>: This is the sub element of servlet and used to represents the name of servlet
4. <servlet-class>: This is the sub element of servlet and used to represents the class of servlet
5. <servlet-mapping>: This is the sub element of and used to map the servlet
6. <url-pattern>: This is the sub element of servlet-mapping and used to client side to invoke
the servlet.
Web.xml Tags
Tags used in web.xml file are:
1. Welcome-file-list tag; This tag is used to specify the default page of web application if none
is specified.
Example:
[code lang=”xml”]
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
[/code]
In the above example index.jsp used as web page for web application
2. Session config tag: This tag is used to specify the session configuration parameter.
Example:
[code lang=”xml”]
<session-config>
<session-timeout>
15
</session-timeout>
</session-config>[/code]
In the above example session-config tag contains another tag session-timeout which specifies the
http session timeout. The time specify in minutes.
3. Error page tag: This tag is used to specify the error occurred in the while weblogic server is
responding to a HTTP request, returns an HTML page that displays either the HTTP error
code.
[code]
<error-page>
<error-code>105</error-code>
<location>/jsp/error/PageNotFound.jsp</location>
</error page>[/code]
In the above example error-page tag specify the error code as 105 and location describes the
location of the jsp page.

Advantages of web.xml file


● The first benefit of the xml is we can write it in our own markup language. There is a no
restricted to limited sets of tags. By defining our own tag we can create a markup language in
terms of specific problem.
● Searching the data is easy and efficient.
● Completely compatible with Java™ and 100% portable.

Unit – 4
Q1 JSP architecture?
Solution:
● JSP technology is used to create web application just like Servlet technology.
● It can be thought of as an extension to Servlet because it provides more functionality than
servlet such as expression language, JSTL, etc.
● A JSP page consists of HTML tags and JSP tags.
● The JSP pages are easier to maintain than Servlet because we can separate designing and
development.
● It provides some additional features such as Expression Language, Custom Tags, etc.

JSP Architecture

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the
WEB-INF folder or in any directory.

● JSP architecture is a 3-tier architecture that separates a web application's presentation, logic,
and data layers.
● The presentation layer, or client side, is responsible for displaying the user interface and
handling user interaction.
● The logic layer, or server-side, is responsible for processing user requests and handling
business logic.
● The data layer is responsible for storing and retrieving data from a database or other storage
system.
● This separation of concerns allows for better maintainability and scalability of the
application.
What is a web Container?

● A JSP-based web application requires a JSP engine, also known as a web container, to
process and execute the JSP pages.
● The web container is a web server component that manages the execution of web programs
such as servlets, JSPs, and ASPs.
● When a client sends a request for a JSP page, the web container intercepts it and directs it to
the JSP engine.
● The JSP engine then converts the JSP page into a servlet class, compiles it, and creates an
instance of the class.
● The service method of the servlet class is then called, which generates the dynamic content
for the JSP page.

The web container also manages the lifecycle of the JSP pages and servlets, handling tasks such
as instantiating, initializing and destroying them. Additionally, it provides security, connection
pooling, and session management services to the JSP-based web application.

Component of JSP Architecture:

JSP architecture is a web application development model that defines the structure and
organization of a JSP-based web application. It consists of the following components:

● JSP pages: These are the main building blocks of a JSP application. They contain a
combination of HTML, XML, and JSP elements (such as scriptlets, expressions, and
directives) that generate dynamic content.
● Servlets: JSP pages are converted into servlets by the JSP engine. Servlets are Java
classes that handle HTTP requests and generate dynamic content.
● JSP engine (web container): This web server component is responsible for processing
JSP pages. It converts JSP pages into servlets, compiles them, and runs them in the Java
Virtual Machine (JVM).
● JavaBeans: These are reusable Java classes that encapsulate business logic and data.
They are used to store and retrieve information from a database or other data sources.
● JSTL (JavaServer Pages Standard Tag Library): This is a set of predefined tags that
can be used in JSP pages to perform common tasks such as iterating over collections,
conditional statements, and internationalization.
● Custom Tag Libraries: JSP allows the creation of custom tags that can be used on JSP
pages. These reusable Java classes encapsulate complex logic and can generate dynamic
content cleanly and consistently.
JSP Architecture Flow

JSP architecture flow refers to the sequence of steps a JSP-based web application goes through to
process and execute JSP pages. The general flow of a JSP architecture can be described as
follows:

1. A client (such as a web browser) sends a request for a JSP page to a web server.
2. The web server forwards the request to the JSP engine responsible for processing JSP
pages.
3. The JSP engine checks if the requested JSP page has been compiled into a servlet. If not,
it compiles the JSP page into a servlet class. This is done by parsing the JSP page and
converting its elements (such as scriptlets, expressions, and directives) into Java code.
4. The JSP engine then compiles the servlet class, which creates a Java class file that can be
executed by the Java Virtual Machine (JVM).
5. The JSP engine then creates an instance of the servlet class and calls the service()
method, which generates the dynamic content for the JSP page. Within the service()
method, the JSP engine generates the HTML code for the response by combining the
static template in the JSP page with the dynamic content generated by the Java code.
6. The JSP engine sends the generated HTML code back to the web server, which then
sends it back to the client as a response.
7. The JSP engine also maintains a cache of the compiled servlet classes so subsequent
requests for the same JSP page can be handled more efficiently.

Q2. JSP session management.


Solution:
● A session can be defined as an object associated with each user with a unique session ID, and
the user's data is based on the account they have registered.
● Different forms of data can be set in a session; These data related to each user of the site help
the user and the website owner in different ways.
● HTTP is a "stateless" protocol; Whenever a user visits a web page, the user opens a separate
connection with the webserver, and the server does not keep a record of preceding client
requests.

Different approaches to maintain a session between client and server are:

● Cookies: Cookies are text files that allow programmers to store some information on a client
computer, and they are kept for usage tracking purposes.
● Passing Session ID in URL: Adding and passing session ID to URL is also a way to identify
a session. However, this method is obsolete and insecure because the URL can be tracked.

The session Implicit object

● A session object is the most commonly used implicit object implemented to store user data to
make it available on other JSP pages until the user's session is active.
● The session implicit object is an instance of a javax. servlet. http. HttpSession interface.
● This session object has different session methods to manage data within the session scope.
Example: Here is an example of a JSP request and session implicit objects where a user submits
login information, and another JSP page receives it for processing:
(HTML File)
( login.jsp)

JSP Session Methods


● public Object getAttribute(String name): is used for returning the object bound with the
specified name for a session and null if there is no object.
● public Enumeration getAttributeNames(): is used for returning an Enumeration of String
objects that will hold the names of all the objects to this session.
● public long getCreationTime(): is used for returning the time when the session was created
right from midnight January 1, 1970, GMT.
● public String getId(): is used for returning a string that will hold a unique identifier assigned
to your session.
● public long getLastAccessedTime(): is used for returning the latest time your client sent a
request linked with the session.
● public void setAttribute(String name, Object value): is used for binding an object to your
session with the help of a specified name.

Q3. JSP Implicit Object


● JSP implicit objects are essential components used in this regard. In this chapter, you will
learn how to deal with implicit objects and implement them.
● The JSP engine produces these objects during the translation phase (i.e., at the time of
translation from JSP to Servlet).
● They are being formed within the service method so that JSP developers can use them
directly in Scriptlet without declaration and initialization.

There are a total of nine implicit objects supported by the JSP. These are:

1. out: javax.servlet.jsp.JspWriter
2. request: javax.servlet.http.HttpServletRequest
3. response: javax.servlet.http.HttpServletResponse
4. session: javax.servlet.http.HttpSession
5. application: javax.servlet.ServletContext
6. exception: javax.servlet.jsp.JspException
7. page: java.lang.Object
8. pageContext: javax.servlet.jsp.PageContext
9. config: javax.servlet.ServletConfig

The brief information about the implicit objects are given below:
1. The out Implicit Object

● An out object is an implicit object for writing data to the buffer and sending output as a
response to the client's browser.
● The out implicit object is an instance of a javax.servlet.jsp.jspWriter class.

Example (HTML file):

Output

2. The request implicit object

● A request object is an implicit object that is used to request an implicit object, which is to
receive data on a JSP page, which has been submitted by the user on the previous JSP/HTML
page.
● The request implicit object used in Java is an instance of
a javax.servlet.http.HttpServletRequest interface where a client requests a page every time
the JSP engine has to create a new object for characterizing that request.
● The container creates it for every request.
● It is used to request information such as parameters, header information, server names,
cookies, and HTTP methods.
● It uses the getParameter() method to access the request parameter.

Example: An example of a JSP request implicit object where a user submits login information,
and another JSP page receives it for processing:

(HTML file):

(login.jsp)

3. Response Implicit Object

● A response object is an implicit object implemented to modify or deal with the reply sent to
the client (i.e., browser) after processing the request, such as redirect responding to another
resource or an error sent to a client.
● The response implicit object is an instance of
a javax.servlet.http.HttpServletResponse interface.
● The container creates it for every request.

4. The session Implicit Object

● A session object is the most commonly used implicit object implemented to store user data to
make it available on other JSP pages until the user's session is active.
● The session implicit object is an instance of a javax.servlet.http.HttpSession interface.
● This session object has different session methods to manage data within the session scope.

5. The application Implicit Object

An application object is another implicit object implemented to initialize application-wide


parameters and maintain functional data throughout the JSP application.

6. The exception Implicit Object


● An exception implicit object is implemented to handle exceptions to display error messages.
● The exception implicit object is an instance of the java.lang.Throwable class.
● It is only available for JSP pages, with the isErrorPage value set as "True". This means
Exception objects can only be used in error pages.

Example(HTML file)

Example(Submit.jsp)
Example(exception.jsp)

7. Page Implicit Object


● A page object is an implicit object that is referenced to the current instance of the servlet.
● You can use it instead. Covering it specifically is hardly ever used and not a valuable implicit
object while building a JSP application.

<% String pageName = page.toString();


out.println("The current page is: " +pageName);%>

8. The config Implicit Object

● A config object is a configuration object of a servlet that is mainly used to access and receive
configuration information such as servlet context, servlet name, configuration parameters,
etc.
● It uses various methods used to fetch configuration information.
Q4. Java Scriplet
● Java provides various scripting elements that allow you to insert Java code from your JSP
code into the servlet.
● Scripting elements have different components that are allowed by JSP.

Scripting Elements in JSP

Scripting elements in JSP must be written within the <% %> tags. The JSP engine will process
any code you write within the pair of the <% and %> tags, and any other texts within the JSP
page will be treated as HTML code or plain text while translating the JSP page.

Example

Here are five different scripting elements:

● Comment <%-- Set of comment statements --%>


● Directive <%@ directive %>
● Declaration <%! declarations %>
● Scriptlet <% scriplets %>
● Expression <%= expression %>

Comment:
Comments are marked as text or statements that are ignored by the JSP container. They are
useful when you want to write some useful information or logic to remember in the future.
Example
Directive:

These tags are used to provide specific instructions to the web container when the page is
translated. It has three subcategories:

● Page: <%@ page ... %>


● Include: <%@ include ... %>
● Taglib: <%@ taglib ... %>

Declaration
It is used to declare methods and variables you will use in your Java code within a JSP file.
According to the rules of JSP, any variable must be declared before it can be used.
Syntax

Example
Java Scriptlet Tag
The scriptlet tag allows writing Java code statements within the JSP page. This tag is responsible
for implementing the functionality of _jspService() by scripting the java code.

Syntax

Example

Another code snippet that shows how to write and mix scriptlet tags with HTML:

Example
Expression
Expressions elements are responsible for containing scripting language expression, which gets
evaluated and converted to Strings by the JSP engine and is meant to the output stream of the
response. Hence, you are not required to write out.print() for writing your data. This is mostly
used for printing the values of variables or methods in the form of output.
Example

Q5. JSP Directives


● Directives supply directions and messages to a JSP container.
● The directives provide global information about the entire page of JSP.
● Hence, they are an essential part of the JSP code. These special instructions are used for
translating JSP to servlet code.
● In JSP's life cycle phase, the code must be converted to a servlet that deals with the
translation phase.
● They provide commands or directions to the container on how to deal with and manage
certain JSP processing portions.
● Directives can contain several attributes that are separated by a comma and act as key-value
pairs.
● In JSP, directives are described with a pair of <%@ .... %> tags.

The syntax of Directives looks like:

There are 3 types of directives:


1. Page directive
2. Include directive
3. Taglib directive

1. Page Directive

● The page directive is used for defining attributes that can be applied to a complete JSP page.
● You may place your code for Page Directives anywhere within your JSP page.
● Page directives are implied at the top of your JSP page.

The basic syntax of the page directive is:

The XML equivalent for the above derivation is:

The attributes used by the Page directives are:

1. buffer: Buffer attribute sets the buffer size in KB to control the JSP page's output.
2. contentType: The ContentType attribute defines the document's MIME (Multipurpose
Internet Mail Extension) in the HTTP response header.
3. autoFlush: The autofill attribute controls the behavior of the servlet output buffer. It
monitors the buffer output and specifies whether the filled buffer output should be flushed
automatically or an exception should be raised to indicate buffer overflow.
4. errorPage: Defining the "ErrorPage" attribute is the correct way to handle JSP errors. If an
exception occurs on the current page, it will be redirected to the error page.
5. extends: extends attribute used for specifying a superclass that tells whether the generated
servlet has to extend or not.
6. import: The import attribute is used to specify a list of packages or classes used in JSP code,
just as Java's import statement does in a Java code.
7. isErrorPage: This "isErrorPage" attribute of the Page directive is used to specify that the
current page can be displayed as an error page.
2. Include Directive
● The JSP "include directive" is used to include one file in another JSP file.
● This includes HTML, JSP, text, and other files. This directive is also used to create templates
according to the developer's requirement and breaks the pages in the header, footer, and
sidebar.

To use this Include Directive, you have to write it like:

The XML equivalent of the above way of representation is:

Example

3. Taglib Directive
● The JSP taglib directive is implemented to define a tag library with "taglib" as its prefix.
● Custom tag sections of JSP use taglib. JSP's taglibdirective is used as standard tag libraries.

To implement taglib, you have to write it like this:

Example

Q6. The Lifecycle of a JSP Page


The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

1. Translation Phase:
● When a user navigates to a page ending with a .jsp extension in their web browser, the
web browser sends an HTTP request to the webserver.
● The webserver checks if a compiled version of the JSP page already exists.
● If the JSP page's compiled version does not exist, the file is sent to the JSP Servlet
engine, which converts it into servlet content (with .java extension). This process is
known as translation.
● The web container automatically translates the JSP page into a servlet. So as a developer,
you don't have to worry about converting it manually.
2. Compilation Phase:
● In case the JSP page was not compiled previously or at any point in time, then the JSP
page is compiled by the JSP engine.
● In this compilation phase, the Translated .java file of the servlet is compiled into the Java
servlet .class file.
3. Initialization Phase:
In this Initialization phase, the container will
1. Load the equivalent servlet class.
2. Create instance.
3. Call the jspInit() method for initializing the servlet instance.

This initialization is done only once with the servlet's init method where database connection,
opening files, and creating lookup tables are done.

4. Execution Phase:
● This Execution phase is responsible for all JSP interactions and logic executions for all requests
until the JSP gets destroyed.
● As the requested JSP page is loaded and initiated, the JSP engine has to invoke the _jspService()
method.
● This method is invoked as per the requests, responsible for generating responses for the
associated requests, and responsible for all HTTP methods.
5. Destruction Phase(Clean up Phase)
● This destruction phase is invoked when the JSP has to be cleaned up from use by the container.
The jspDestroy() method is invoked.
● You can incorporate and write cleanup codes inside this method for releasing database connections
or closing any file.
Summary: JSP page is translated into Servlet by the help of JSP translator. The JSP translator is
a part of the web server which is responsible for translating the JSP page into Servlet. After that,
Servlet page is compiled by the compiler and gets converted into the class file. All the processes
that happen in Servlet are performed on JSP later like initialization, committing response to the
browser and destroy.

Example : Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the
JSP page.
It will print 10 on the browser.

You might also like