Back End Development
Computer – IP –(Internet Programming)
Shraddha R. Kawji
Assistant Professor
Computer
SIES Graduate School of Technology
1
Faculty Name
Servlet
Faculty Name
Introduction Servlet
• Servlet is a server side java application which is used to create a dynamic web
pages
• A java Servlet extends the capability of server. Although servlet can respond to
any type of request, they most commonly implement application hosted on
web server
• The Servlets executes on a web or application server. It works an interface
between a client request which comes from a web browser or other HTTP
client and server side application
• Server are used to accept input from end user through the form ,present the
records from server database or any other storage from media and create a
dynamic web pages
• Before servlet there was a CGI(common getaway Interface)
3
Faculty Name
CGI
• CGI stands for Common Gateway Interface — it is a standard protocol used to enable
web servers to execute external programs (often scripts) and send the output back to the
client’s browser.
• Allows a web server to interact with external programs.
• Used to generate dynamic web content instead of serving only static HTML.
• Commonly written in languages like C, C++
4
Faculty Name
Faculty Name
Disadvantages of CGI
There are many problems in CGI technology:
• If number of clients increases, it takes more time for sending
response.
• For each request, it starts a process and Web server is limited to
start processes.
• It uses platform dependent language e.g. C, C++, perl.
Faculty Name
Faculty Name
The basic benefits of servlet are as follows:
• Better performance: because it creates a thread for each
request not process.
• Portability: because it uses java language.
• Robust: Servlets are managed by JVM so we don't need to
worry about memory leak, garbage collection etc.
• Secure: because it uses java language
Faculty Name
9
Faculty Name
Java Servlet Architecture
10
Faculty Name
Client
• In this architecture, the web browser acts as a Client.
• Client or user connected with a web browser.
• The client is responsible for sending requests or HttpRequest to the web server and
processing the Web server’s responses.
Web Server
• The web server controls how web users access hosted files and is responsible for
processing user requests and responses.
• Here server is software it understands URLs and HTTP protocol. Whenever a
browser needs to host a file on the web server, it processes a client request using
an HTTP request; if it finds the requested file, it sends it back to the browser
through HTTP Response. Static web servers send the file as it is, while dynamic
web servers update the server-hosted file before sending it to the browser.
Web Container
• A web container is a web server component that interacts with Java servlets.
• A web container manages the servlets’ lifecycle and performs the URL mapping
task.
• Web container handles the server-side requests of servlets, JSP, and other files.
• The critical tasks performed by servlets are loading and unloading servlets,
creating and managing requests and response objects, and performing servlet
management’s overall tasks.
11
Faculty Name
Servlet Request Flow
The steps to processing a servlet request; consider the above
diagram.
1. The client sends a request.
2. The web server accepts the request and forwards it to the web
container.
3. Web container searches [Link] file for request URL pattern and
gets the address of the servlet.
4. You should create and set up the servlet using the init() method if
it has not been created yet.
5. The container calls public service() by passing ServletRequest
and ServletResponse objects.
6. Public service() method typecast ServletRequest and
ServletResponse objects to HttpServletRequest and
HttpServletResponse objects, respectively.
7. The public service() method calls for protected service().
8. The protected service() method checks the client request &
corresponding method is called. 12
9. The request is handled by Faculty
sendingName the result generated by the
Servlet Life Cycle
13
Faculty Name
1. Loading and installation
2. Initialization
3. Servicing and request
4. Destroying the servlets
14
Faculty Name
Get and Post method
15
Faculty Name
What is Session Handling?
16
Faculty Name
What is Session
• A session is a temporary interaction between a client
(browser) and a server.
• It starts when the client logs in or accesses the app, and
ends when:
• The user logs out
• The session times out (e.g., after 30 min)
• The server shuts down
17
Faculty Name
18
Faculty Name
19
Faculty Name
20
Faculty Name
Ways of session tracking techniques
21
Faculty Name
Hidden Form Field
Hidden form fields are a technique in web development, including
Java Servlets, to pass data between pages or requests without it being
visible or directly modifiable by the user in the browser interface.
<form action="MyServlet" method="post">
<input type="hidden" name="userId" value="12345">
<input type="submit" value="Submit">
</form>
22
Faculty Name
When to use Hidden form field
• Passing Data Between Requests:
• Hidden fields are commonly used to pass data, such as user
IDs, session information, or other stateful data, between
different requests or pages in a web application, especially
when session management techniques like cookies or URL
rewriting are not suitable or preferred.
• Maintaining State:
• They can help maintain the state of a user's interaction across
multiple pages or form submissions without relying on server-
side sessions for every piece of data.
• Anonymous Shopping Carts:
• In scenarios like an anonymous shopping cart, hidden fields can
carry item details until checkout, where user identification
becomes necessary.
23
Faculty Name
Advantages:
• Browser Independence: Works even if cookies are disabled in the user's browser.
• Simple Implementation: Relatively easy to implement using basic HTML and Servlet
code.
Disadvantages:
• Security Risk:
• The data in hidden fields is visible in the page's source code, making it susceptible to
client-side manipulation. Sensitive information should not be stored in hidden fields
without proper encryption or validation.
• Overhead for Large Data:
• Passing large amounts of data through hidden fields can become a larger request sizes.
• Limited Data Types:
• Primarily suited for passing string values. Complex Java objects cannot be directly passed.
24
Faculty Name
URL Rewriting
URL rewriting is a session tracking technique used in
web applications, particularly in environments like
Java Servlets, to maintain session state when cookies
are disabled or not supported by the client
•URL Rewriting is a technique of session tracking in web applications.
•In this method, the session ID is appended to the URL of the client
request.
•Whenever the client makes a request, the server reads the session ID
from the URL to identify the user.
•Normally, sessions are tracked using cookies.
•But if cookies are disabled in the browser, the server
cannot store the session ID in cookies.
•In such cases, URL Rewriting is used as an alternative.
25
Faculty Name
How it works:
• When a session is created, the server generates a Session ID (e.g.,
JSESSIONID=12345).
• Instead of storing it in a cookie, the server appends it to the URL:
[Link]
• Every link in the response sent to the client will have this session
ID attached.
• When the client clicks another link, the session ID comes back to
the server.
• The server uses the ID to retrieve the correct session object.
26
Faculty Name
Advantages:
•Works even if cookies are disabled.
•Simple to implement with encodeURL().
Disadvantages:
•URL becomes lengthy and ugly.
•Session ID is visible in the browser → security risk.
•If user bookmarks the URL, session ID might get misused.
•Requires rewriting all URLs manually if not using
encodeURL().
27
Faculty Name
Cookies
•A cookie is a small piece of text data stored on the client’s browser.
•When a session is created, the server generates a unique session
ID (for example, JSESSIONID in Java).
•This session ID is stored inside a cookie and sent to the client.
•Cookies act as a carrier of the session ID between client and server,
making session tracking possible.
How it works
[Link] sends request → Server creates a new session.
[Link] generates session ID and stores session data on server memory.
[Link] sends session ID as a cookie to the client’s browser (example: Set-Cookie:
JSESSIONID=12345).
[Link] stores the cookie.
[Link] the next request, browser automatically sends Cookie: JSESSIONID=12345.
[Link] matches session ID → retrieves session data → continues the session.
28
Faculty Name
🔹 Advantages of Cookies in Session Tracking
• Automatic handling by browser.
• Works without requiring URL rewriting.
• Transparent to the user.
🔹 Disadvantages of Cookies in Session Tracking
• It will not work if the user disable the cookies from browser.
• Cookie object can be sent only text type of information
• If user disables cookies in browser → session tracking fails
(then URL rewriting is used).
• Cookies have size limits.
29
Faculty Name
HTTP session Object
•An HTTP session object is a server-side object that stores information
about a user across multiple requests.
•Servlet provides an interface Http Session for session handling and
store the information about particular user.
•The user interface is used by servlet container to create a session
between client and HTTP server
•There are two ways provided by the Http serveletRequest
1. public Httpsession getsession()
2. public Httpsession getsession(Boolean create)
30
Faculty Name
Commonly used method of Http session interface
Method Description
getId() Returns unique session ID.
getCreationTime() When session was created.
getLastAccessedTime() Last client request time.
setAttribute(String, Object) Store data in session.
getAttribute(String) Retrieve data.
removeAttribute(String) Remove stored data.
invalidate() Destroys the session.
setMaxInactiveInterval(int seconds) Sets session timeout.
31
Faculty Name
JDBC
32
Faculty Name
What is JDBC(Java Database connectivity)
• JDBC is an API that helps applications to
communicate with databases, it allows Java
programs to connect to a database, run queries,
retrieve, and manipulate data.
• Because of JDBC, Java applications can easily
work with different relational databases like
MySQL, Oracle, PostgreSQL, and more.
33
Faculty Name
34
Faculty Name
JDBC Drivers
JDBC drivers are client-side adapters that
convert requests from Java programs to a
protocol that the DBMS can understand.
There are 4 types of JDBC drivers:
[Link]-1 driver or JDBC-ODBC bridge driver
[Link]-2 driver or Native-API driver (partially java
driver)
[Link]-3 driver or Network Protocol driver (fully java
driver)
[Link]-4 driver or Thin driver (fully java driver)
35
Faculty Name
JDBC-ODBC bridge driver
• The JDBC-ODBC Bridge Driver, also known as a Type 1 JDBC driver, is a mechanism
in Java that allows Java applications to connect to databases via existing ODBC (Open
Database Connectivity) drivers.
How it functions:
JDBC Calls to Bridge
Conversion to ODBC
ODBC Driver Interaction
Database Communication
. Reverse Flow
36
Faculty Name
Native-API driver
A native-API driver, also known as a Type 2 driver, is a database
connectivity component that uses the vendor-supplied, client-side
libraries to translate API calls into the database's native communication
protocol.
37
Faculty Name
Network Protocol driver
•It is a JDBC driver that converts JDBC calls into a database-independent
network protocol.
•These calls are then sent to a middleware server (application server), which in
turn translates them into the database-specific protocol (e.g., Oracle, MySQL,
SQL Server).
38
Faculty Name
Thin Driver
1. A Type-4 JDBC Driver is called a Thin Driver.
2. It converts JDBC calls directly into the database-specific protocol (e.g.,
Oracle Net for Oracle, MySQL protocol for MySQL).
3. This means no middleware or native libraries are required — the driver
communicates directly with the database server.
39
Faculty Name
Steps to connect Java Application
40
Faculty Name
Steps to connect Java Application
Step 1: Register the JDBC Driver
Step 2: Establish a Connection
Step 3: Create a Statement
Step 4: Execute a Query
Step 5: Close the Connection
41
Faculty Name
Step 1: register the JDBC Driver
[Link]("[Link]");
Step 2: Establish a Connection
Connection connection = [Link](
"jdbc:mysql://localhost:3306/your_database",
"your_username",
"your_password"
);
42
Faculty Name
Step 3: Create a Statement
Statement statement = [Link]();
Step 4: Execute a Query
String query = "INSERT INTO students (id, name) VALUES (101, 'John Doe')";
int rowsAffected = [Link](query);
[Link]("Rows affected: " + rowsAffected);
Step 5: Close the Connection
[Link]();
[Link]();
43
Faculty Name
Reference video for installation of Mysql and mysql connector
[Link]
TN8xvMo
[Link]
[Link]
44
Faculty Name
JSP
45
Faculty Name
Why we need JSP
46
Faculty Name
What is JSP
•JSP (Java Server Pages) is a server-side technology developed
by Sun Microsystems (now Oracle).
•It is used to create dynamic, platform-independent web
applications.
•JSP allows you to embed Java code inside HTML pages to
generate content dynamically.
•The JSP pages are easier to maintain than the servlet because
we can separate designing and development
•JSP files usually have the extension .jsp
47
Faculty Name
Advantages of JSP
● Extension to servlet
○ We can use all the features of servlet in JSP, In addition we can
use object predefine and custom tags
● Easy to maintain
○ Business logic and presentation logic is differently implemented
● Fast development
○ No need to recompile project after modifying JSP pages
● Less code than servlet
○ Tags reduce the code
● Exception Handling
○ JSP take care of exceptional handling
● Readability
○ JSP increase readability of code by using tags
● Less complexity
○ Easy to learn and apply
48
Faculty Name
49
Faculty Name
JSP life cycle
50
Faculty Name
1. Translation of JSP page to Servlet
○ The JSP file is parsed and converted into a Java servlet source file ([Link]).
○ This step checks for syntax correctness.
2. Compilation of JSP page(Compilation of JSP into [Link])
○ The generated [Link] file is compiled into a class file ([Link]).
○ This step converts the servlet code into bytecode.
3. Classloading ([Link] to [Link])
○ The container dynamically loads the compiled class.
4. Instantiation(Object of the generated Servlet is created)
○ The container creates an instance of the generated servlet class.
5. Initialization(jspInit() method is invoked by the container)
○ This method is called only once when the JSP is first loaded.
○ It is used for initializing resources like database connections or configurations.
6. Request processing(_jspService()is invoked by the container)
○ This method is called for every request.
○ It cannot be overridden because it is auto-generated and declared as final.
○ It receives HttpServletRequest and HttpServletResponse objects to handle the request.
7. Destroy/destruction(jspDestroy() method is invoked by the container)
○ This method is called once before removing the JSP from service.
○ It is used for releasing resources, such as closing database connections or cleaning up open
files.
51
Faculty Name
JSP Tags
52
Faculty Name
Scriptlet Tag
● Used to write any Java code (loops, conditions, variable declarations, etc.).
Syntax
<% Java code %>
Example:
<%
int x = 10;
int y = 20;
[Link]("Sum is: " + (x+y));
%>
53
Faculty Name
Expression Tag
•Used to output the result of an expression directly into the HTML
response.
•Automatically calls [Link]() behind the scenes.
Syntax
<%= expression %>
example
Current Time: <%= new [Link]() %>
54
Faculty Name
Declaration Tag
● Used to declare variables or methods that are placed outside the service() method (like class-
level members).
Syntax:
<%! declaration %>
Example
<%! int counter = 0; %>
<%! public int getSquare(int n){ return n*n; } %>
55
Faculty Name
JSP Comments
● syntax
<%-- This is a JSP comment --%>
•These comments are not included in the HTML output sent to the browser.
•They are only visible in the JSP source file.
•Useful for adding notes or explanations for developers.
56
Faculty Name
Directive Tag
● Provides global information about the JSP page.
Syntax:
<%@ directive attribute="value" %>
● Types of Directives:
○ page → Defines page-level settings (language, import, errorPage, etc.).
○ <%@ page language="java" import="[Link].*" %>
○ include → Includes a static file at translation time.
○ <%@ include file="[Link]" %>
○ taglib → Declares a custom tag library (like JSTL).
○ <%@ taglib uri="[Link] prefix="c" %>
57
Faculty Name
Action Tag
● Used to perform actions (forwarding, including, using beans).
● Syntax:
● <jsp:action ... />
● Examples:
○ <jsp:include page="[Link]" /> → Includes another JSP dynamically.
○ <jsp:forward page="[Link]" /> → Forwards request to another resource.
○ <jsp:useBean> → Uses JavaBeans in JSP.
58
Faculty Name