Solved Question Paper (Unit-3 - Unit -4).Docx
Solved Question Paper (Unit-3 - Unit -4).Docx
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.
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.
● 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.
// Initialization code...
}
● 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.
● 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.
// 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.
// Do required initialization
message = "Hello World";
}
● 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.
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" />
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.
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.
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.
5) Get request is more efficient and used more Post request is less efficient and used less
than Post. than get.
GenericServlet HttpServlet
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.
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.
GenericServlet
Example
import java.io.*;
import javax.servlet.*;
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.
// 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
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.
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.
● 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.
● 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)
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.
Output
● 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)
● 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.
● 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(HTML file)
Example(Submit.jsp)
Example(exception.jsp)
● 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 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
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:
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
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.
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.
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.
Example
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.
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.