Downloadfile
Downloadfile
Java Servlets: Introduction to servlets, Servlet Application Programming interface, The servlet
architecture, The servlet life cycle, Simple hello world servlet. Introduction to Java Server Pages:
Introduction, Disadvantages, JSP vs Servlets, Life cycle of a JSP page. Deploying and executing JSP.
So, in CGI server has to create and destroy the process for every request. It’s easy to understand
that this approach is applicable for handling few clients but as the number of clients increases, the
workload on the server increases and so the time is taken to process requests increases.
Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
Servlets API’s:
Servlets are build from two packages:
• javax.servlet(Basic)
• javax.servlet.http(Advance)
Various classes and interfaces present in these packages are:
They constitute the core of the Servlet API. Keep in mind that these packages are not part of the Java
core packages. Therefore, they are not included with Java SE. Instead, they are provided by the servlet
implementation, which is Tomcat in this case.
The jakarta.servlet Package
Methods of Servlet
The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes
thatestablish the framework in which servlets operate.
• The ServletRequest class includes methods that allow you to read the names
andvalues of parameters that are included in a client request.
• The example contains two files. A Web page is defined in PostParameters.htm and
aservlet is defined in PostParametersServlet.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.
Servlets are grouped under the Advanced Java tree that is used to create dynamic web applications. Servlets
are robust, well scalable, and are primarily used in developing server-side applications. If we go a little back in
time, we would be able to witness that before the introduction of servlets, CGI(CommonGatewayInterface) was
used. Among several indigenous tasks that a servlet is capable of doing, dynamically performing client requests
and responses are most common. Other tasks that a servlet can do effectively are:
• Can easily manage/control the application flow.
• Suitable to implement business logic.
• Can effectively balance the load on the server side.
• Easily generate dynamic web content.
• Handle HTTP Request and Response
• Also act as an intercept or filter for a specific group of requests.
ServletArchitecturecanbedepictedfromtheimageitselfasprovidedbelowasfollows:
Types of Servlet
• Generic Servlets: These are those servlets that provide functionality for implementing a servlet. It is a generic
class from which all the customizable servlets are derived. It is protocol-independent and provides support
for HTTP, FTP, and SMTP protocols. The class used is ‘javax.servlet.Servlet’ and it only has 2 methods –
init() to initialize & allocate memory to the servlet and destroy() to deallocate the servlet.
HTTP Servlets: These are protocol dependent servlets, that provides support for HTTP request
and response. It is typically used to create web apps. And has two of the most used methods – do GET() and do
POST() each serving their own purpose.
There are three potential ways in which we can employ to create a servlet:
• Implementing Servlet Interface
• Extending Generic Servlet
• Extending HTTP Servlet
Components of Servlet Architecture
Servlet Architecture contains the business logic to process all the requests made by client. Below is the
high-level architecture diagram of servlet. Let’s see in brief, how does each component add to the working of a
servlet.
1. Client
The client shown in the architecture above is the web browser and it primarily works as a medium that
sends out HTTP requests over to the web server and the web server generates a response based on some
processing in the servlet and the client further processes the response.
2. Web Server
Primary job of a web server is to process the requests and responses that a user sends over time and maintain
how a web user would be able to access the files that has been hosted over the server. The server we are talking
about here is a software which manages access to a centralized resource or service in a network. There are
precisely two types of webservers:
• Static webserver
• Dynamic webserver
3. Web Container
Web container Is another typical component in servlet architecture which is responsible for communicating with
the servlets. Two prime tasks of a web container are:
• Managing the servlet lifecycle
• URL mapping
Web container sits at the server-side managing and handling all the requests that are coming in either from the
servlets or from some JSP pages or potentially any other file system.
How does a Servlet Request flow?
Everyservletshouldoverridethefollowing3methodsnamely:
1. init():To initalize/instantiate the servlet container.
2. service():ThismethodactslikeanintermediatorybetweentheHTTPrequestandthe business logic to serve that
particular request.
destroy(): This method is used to deallocate the memory allocated to the servlet. These methods are used to
process the request from the user.
SESSION: The servlet life cycle
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet
is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the
ready state. In the ready state, servlet performs all the tasks. When the web container invokes the
destroy() method, it shifts to the end state.
The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.
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 web container calls the init method only once after creating the servlet instance. The init method is used
initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method
given below:
1. public void init(ServletConfig config) throws Servlet Exception
The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given below:
The web container calls the destroy method before removing the servlet instance from the service. It
gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax
of the destroy method of the Servlet interface is given below:
}
}
JavaServer Pages (JSP) is a technology for developing web pages that support dynamic
contentwhich helps developers insert java code in HTML pages by making use of special
JSP tags.
Using JSP, you can collect input from users through web page forms, present records
from adatabase or another source, and create web pages dynamically.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of
.html.
• The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code that implements the corresponding
dynamic behavior of the page.
• The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format, which the servlet
engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static HTML
content.
• Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
AdvancedJava
SESSION: Disadvantages
Disadvantages of JSP
While many advantages of JSP exist, especially for non-Java programmers, you must recognise its
disadvantages. Commonly considered disadvantages include the following:
• Speed is slow because of the need to translate JSP to Java code before compiling
• Can only deal with an HTTP request
• Difficult to debug and trace errors
• Lack of advanced features
• Database connectivity can be an issue
• Limited to HTML format output
• Requires more storage on the server than on other pages
JSP vs Servlets
HTML-based Java-based
Slower execution; users must compile into Servlets Faster performance; users execute directly on
before executing web servers
Can only accept HTTP requests Accept requests from all protocols
Can use JSP API to create custom JSP tags Cannot create custom tags
Cannot override the service () function Can override the service () function
7
AdvancedJava
LIFE CYCLE:
A JSP life cycle can be defined as the entire process from its creation till the destruction which is
similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
• Compilation
• Initialization
• Execution
• Cleanup
7
AdvancedJava
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the
page has never been compiled, or if the JSP has been modified since it waslast compiled, the JSP engine
compiles the page.
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to
perform JSP-specific initialization, override the jspInit() method:
Typically initialization is performed only once and as with the servlet init method, you generally initialize
database connections, open files, and create lookup tables in the jspInit method.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP isdestroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSPengine invokes
the _jspService() method in the JSP.
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response
for that request and this method is also responsible for generating responses to all seven of the HTTP methods
ie. GET, POST, DELETE etc.
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when
you need to perform any cleanup, such as releasing database connections or closing open files.
Before deploying and executing a JSP, ensure you have the following tools set up:
Required Software:
• Java Development Kit (JDK): Install the JDK on your machine to compile and run Java code.
• Servlet Container: A server is required to run JSP pages. Common options include:
o Apache Tomcat (most popular for JSP and Servlets).
o Jetty and GlassFish are also used for JSP deployment.
7
A basic JSP page contains HTML with embedded Java code.
For example:
AdvancedJava
Deployment of JSP
Once the JSP page is ready, it needs to be deployed to a servlet container (e.g., Apache Tomcat).
C:\apache-tomcat-x.x.xx\webapps\mywebapp\
2. Configuration (Optional):
• web.xml (Optional for simple JSPs): Define servlet mappings if necessary. Example:
• Go to the bin/ folder in your Tomcat installation directory and execute the startup.bat7 (Windows) or
startup.sh (Linux/Mac).
Example: C:\apache-tomcat-x.x.xx\bin\startup.bat
AdvancedJava
http://localhost:8080/mywebapp/hello.jsp
5.Execution of JSP
• When a user accesses a JSP file, the servlet container performs several tasks:
1. Translation: The JSP is converted into a servlet (Java class).
2. Compilation: The servlet is compiled into bytecode (a .class file).
3. Execution: The servlet container processes the request and executes the generated servlet.
• After you make changes to the JSP file, the servlet container will automatically detect changes and recompile the
JSP.
• However, for larger applications with servlets or other resources, you might need to restart the servlet container or
redeploy the web application.
If your JSP page doesn’t display or work as expected, you can troubleshoot using the following methods:
1. Check Logs:
o Look for error logs in the logs/ folder of your servlet container.
o In Tomcat, check catalina.out or localhost.<date>.log for errors.
2. Verify File Paths and Permissions:
o Ensure the JSP file is in the correct location (e.g., in the webapps/mywebapp/ directory).
o Ensure the correct permissions are set for your files (read/write permissions).
3. Servlet Container Console:
o Check the Tomcat console (when running in command-line mode) for any startup errors or issues
related to your JSP or the server.
4. Clear Browser Cache:
o Sometimes browsers cache old versions of JSP pages. Clear the cache or use incognito mode to
ensure you're loading the latest version.
8. Redeploying JSP
• Database Integration: Configure JDBC connections if the JSP page needs to interact with a database.
• Servlets and Filters: Deploy servlets and configure filters in web.xml to handle additional request
processing.
• External Libraries: Include any required JAR files in the lib/ folder under WEB-INF/.
10. Conclusion
With this process, JSP pages can be effectively deployed and executed within a web application environment.
JSP supports nine automatically defined variables, which are also called implicit objects.
Thesevariables are:
Objects Description
out This is the PrintWriter object used to send output to the client.
JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the
followingform:
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as scripting language,
error page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the
page
7
AdvancedJava
There is only one syntax for the Action element, as it conforms to the XML standard:
Action elements are basically predefined functions and there are following JSP actions
available:
Syntax Purpose
7
AdvancedJava
To give an example for a JSP code, first we are going to print the text "Hello Hiox".
Try the thefollowing syntax code.
Example :
<html>
<body>
<! -- This is the JSP file-->
<%
out.println ("Hello HIOX");
%>
</body>
</html>
Result :
Hello HIOX
7
AdvancedJava
AdvancedJava