0% found this document useful (0 votes)
26 views24 pages

Downloadfile

Java m4

Uploaded by

dslab68
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)
26 views24 pages

Downloadfile

Java m4

Uploaded by

dslab68
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/ 24

MODULE -4

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.

SESSION : Java Servlets: Introduction to servlets


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 webserver, process the request, produce the
response, then send a response back to the webserver.
Properties of Servlets are as follows:
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from the webserver.
Servlet Architecture is can be depicted from the image itself as provided below as follows:

Execution of Servlets basically involves six basic steps:


1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
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.
Now let us do discuss eccentric point that why do we need For 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. In this case, Java
Servlet is also one of the component APIs of Java Platform Enterprise Edition which sets
standards for creating dynamic Web applications in Java.
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?
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.

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.

Difference between Servlet 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.

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:

Component Type Package

Servlet Interface javax.servlet.*

Component Type Package

Servlet Request Interface javax.servlet.*

Servlet Response Interface javax.servlet.*

Generic Servlet Class javax.servlet.*

Http Servlet Class javax.servlet.http.*

HttpServletRequest Interface javax.servlet.http.*

HttpServletResponse Interface javax.servlet.http.*

Filter Interface javax.servlet.*

Servlet Config Interface javax.servlet.*

SESSION: Servlet Application Programming interface


Two packages contain the classes and interfaces that are required to build the servlets .They are

jakarta.servlet and jakarta.servlet.http.

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

The jakarta.servlet package contains a number of interfaces and classes


thatestablish the framework in which servlets operate.

Interfaces of Jakarta.Servlet Package


Classes of 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.

4. The javax.servlet.http Package


The javax.servlet.http package contains a number of interfaces classes that are
commonlyused by servlet developers.
Reading Servlet Parameters

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

SESSION: The servlet architecture

SERVLETS: JAVASERVLET ARCHITECTURE

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.

The properties of Servlets areas follows:

• Servlets work on the server side.


• Servlets are capable of handling complex requests obtained from the webserver.

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:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

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.

1) Servlet class is loaded

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.

2) Servlet instance is created

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

4) service method is invoked

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:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked

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:

1. public void destroy()

SESSION: Simple hello world servlet


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

public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {

message = "Hello World";


}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {

}
}

SESSION: Introduction to Java Server Pages: Introduction,


JSP(JavaServer Pages)

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

Easier coding process Complex coding process

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

Ability to utilise client-side validation Cannot utilise client-side validation

Includes in-built implicit objects No in-built implicit objects

Cannot override the service () function Can override the service () function

7
AdvancedJava

SESSION: Life cycle of a JSP page.

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.

The following are the paths followed by a JSP

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

The compilation process involves three steps:

• Parsing the JSP.

• Turning the JSP into a servlet.

• Compiling the servlet.

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:

public void jspInit(){


// Initialization code...
}

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 takes an HttpServletRequest and an HttpServletResponse as itsparameters as


follows:

void _jspService(HttpServletRequest request,


HttpServletResponse response)
{
// Service handling code... 7
}
AdvancedJava

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.

The jspDestroy() method has the following form:

public void jspDestroy()


{
// Your cleanup code goes here.
}

Deploying and executing JSP.

Setting Up the Environment

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.

Structure of a Web Application

Writing a Simple JSP Page

7
A basic JSP page contains HTML with embedded Java code.

For example:
AdvancedJava

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"%>


<html>
<body>
<h1>Hello, World! This is a JSP page.</h1>
</body>
</html>

Deployment of JSP

Once the JSP page is ready, it needs to be deployed to a servlet container (e.g., Apache Tomcat).

Steps for Deployment:

1. Copy the Web Application:


o Place your web application folder (containing your JSP file and WEB-INF/ folder) into the
webapps/ directory of the Tomcat installation.

C:\apache-tomcat-x.x.xx\webapps\mywebapp\

2. Configuration (Optional):

• web.xml (Optional for simple JSPs): Define servlet mappings if necessary. Example:

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-


instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<jsp-file>/hello.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

3.Start the Servlet Container (Tomcat):

• 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

4.Access the JSP Page:

• Open a web browser and go to the following URL

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.

6.Modifying and Redeploying the JSP

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

Troubleshooting JSP Execution

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

• In Tomcat, if you want to redeploy a web application, you can do so by:


1. Stopping the server.
2. Deleting the mywebapp directory from the webapps/ folder.
3. Replacing it with a new version of your web application.
4. Restarting Tomcat.
• Alternatively, Tomcat Manager (if enabled) allows you to deploy and redeploy applications
7 dynamically
through the browser interface.

9. Advanced Deployment (Optional)


AdvancedJava

For more complex web applications:

• 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

Deploying and executing a JSP involves the following steps:

1. Set up the environment (JDK and servlet container).


2. Write your JSP page.
3. Deploy the JSP file in the correct folder.
4. Start the servlet container (e.g., Tomcat).
5. Access the JSP page through the browser.
6. Troubleshoot if any issues arise during execution.

With this process, JSP pages can be effectively deployed and executed within a web application environment.

JSP Implicit Objects:

JSP supports nine automatically defined variables, which are also called implicit objects.
Thesevariables are:

Objects Description

request This is the HttpServletRequest object associated with the


request.

response This is the HttpServletResponse object associated with the


response to the client.

out This is the PrintWriter object used to send output to the client.

session This is the HttpSession object associated with the request.

This is the ServletContext object associated with application


application context. 7

config This is the ServletConfig object associated with the page.


AdvancedJava

pageContext This encapsulates use of server-specific features like higher


performance JspWriters.

This is simply a synonym for this, and is used to call the


page methods defined by the translated servlet class.

Exception The Exception object allows the exception data to be accessed


by designated JSP.

JSP Directives:

A JSP directive affects the overall structure of the servlet class. It usually has the
followingform:

<%@ directive attribute="value" %>

There are three types of directive tag:

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

JSP Action Tags:


JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You
can dynamically insert a file, reuse JavaBeans components, forward the user to another page,
or generate HTML for the Java plugin.

There is only one syntax for the Action element, as it conforms to the XML standard:

<jsp:action_name attribute="value" />

Action elements are basically predefined functions and there are following JSP actions
available:

Syntax Purpose

jsp:include Includes a file at the time the page is requested

jsp:useBean Finds or instantiates a JavaBean

jsp:setProperty Sets the property of a JavaBean

jsp:getProperty Inserts the property of a JavaBean into the output

jsp:forward Forwards the requester to a new page

Generates browser-specific code that makes an OBJECT or


jsp:plugin EMBED tag for the Java plugin

jsp:element Defines XML elements dynamically.

jsp:attribute Defines dynamically defined XML element's attribute.

jsp:body Defines dynamically defined XML element's body.

jsp:text Use to write template text in JSP pages and documents.

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

You might also like