Web Application:
• A web application is an application accessible from the web.
• A web application is composed of web components like Servlet, JSP, etc.
and other elements such as HTML, CSS, and JavaScript.
• The web components typically execute in Web Server and respond to the
HTTP request.
Common Gateway Interface:
• CGI (Common Gateway Interface) scripting language is a basic server-
side programming language. which is used to develop dynamic web
pages.
• CGI technology enables the web server to call an external program and
pass HTTP request information to process the request.
Servlets
• A Servlet is a Java class used to build dynamic web applications.
• It runs on a Java-enabled web server or application server like Apache
Tomcat.
• A servlet acts as a middle layer between the client (browser) and the
backend (database or business logic).
What does a Servlet do?
• Receives HTTP requests from the client.
• Processes the request (can include accessing databases, performing logic,
etc.).
• Generates a response (typically HTML, JSON, or XML).
• Sends the HTTP response back to the browser.
To make it easier to create servlets, Java provides ready-made classes:
GenericServlet: A base class you can use for general types of services.
HttpServlet: A more specific class for handling web-related (HTTP) services. It
has methods like:
doGet(): for handling GET requests (like clicking a link),
doPost(): for handling POST requests (like submitting a form).
Servlet Vs CGI
What is a Web Application?
• A web application is a software program that runs on a web server.
• Users interact with it using a web browser over the Internet or an Intranet.
• Unlike traditional desktop applications, web applications don’t need to be
installed on the user’s computer.
Examples of Web Applications:
• Online banking systems (e.g., net banking)
• E-commerce sites (e.g., Amazon)
• Social media platforms (e.g., Facebook, Twitter)
• Online learning platforms (e.g., Coursera, Khan Academy)
• Email services (e.g., Gmail)
Web Application Architecture
1. Client Tier (Frontend)
• This is the user interface that runs in a web browser.
• Users interact with the web application through the client tier.
• Sends requests to the server using HTTP/HTTPS.
• Examples: HTML pages, JavaScript, CSS.
2. Web Server/Application Server (Middle Tier)
• Receives client requests.
• Uses Servlets (and possibly JSPs or other frameworks like Spring MVC) to process those requests.
Performs tasks like:
• Input validation
• Session tracking
• Interacting with databases
3. Database Server (Backend Tier)
• Stores the application's data.
• Responds to queries made by the server-side code (e.g., from Servlets).
• Common databases: MySQL, PostgreSQL, Oracle, MongoDB.
Advantages of Using Servlets
• Platform-independent (Java-based, so works across systems).
• Efficient and scalable: Uses multithreading, so multiple requests can be handled
simultaneously.
• Secure: Can include authentication and authorization mechanisms.
• Reusable: Servlets can be reused and extended.
• Integration: Easy to integrate with other Java technologies (e.g., JDBC for databases).
Challenges of Web Application
• Many users can use the web app at the same time, so the server must work
fast and not crash.
• Web apps need to remember users (like after they log in), but the web itself
doesn’t.
• Security is very important – web apps must protect user data and stop
hackers.
• Web apps depend on databases to store and get data.
• Users expect web apps to be fast and always available.
Servlet life cycle
A Servlet goes through different stages from creation to destruction. These stages are managed
by the Web Container (like Apache Tomcat).
1. Servlet Class is Loaded
• The classloader loads the servlet class.
• This happens when the first request for that servlet is received.
• Only happens once during the servlet’s life cycle.
2. Servlet Instance is Created
• The web container creates an object of the servlet class.
• Only one instance is created for the servlet.
• This instance is shared for all requests.
3. init() Method is Called
• The web container calls the init() method once, after the servlet object is created.
• Used to initialize the servlet (e.g., set up resources).
• Called only one time in the servlet's lifetime.
Syntax:
public void init(ServletConfig config) throws ServletException
4. service() Method is Called
• This method is called every time a request comes in.
• Handles the request and generates the response.
• If the servlet is not yet initialized, steps 1–3 happen first.
• If it’s already initialized, only service() is called.
Syntax:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5. destroy() Method is Called
• Called once when the servlet is being removed (e.g., server shutdown).
• Used to clean up resources (like closing connections, stopping threads).
Syntax:
public void destroy()
Lifecycle of a servlet describes how and when a servlet is loaded, initialized,
able to handle requests and unloaded.
New Instance is
• There are 3 methods in Created
lifecycle of servlet, Servlet Uninitialized
those are
Init() method Called
– init() : This method
initializes the servlet. One or more Servlet
Requests initialized and
processed by Ready to
– service() : This service() process
method process the method requests
http requests. Destroy() method
called
Instance
– destroy(): This Garbage
method is used to collected
destroy the servlet.
Handling Request and Response
• Requests come from the client (usually a web browser).
• The Servlet handles the request and sends back a response.
• The web container provides two important objects to help with this:
1. HttpServletRequest: Contains information about the client’s request.
2. HttpServletResponse: Used to send the response back to the client.
Example1:
• String name = request.getParameter("name");
• String agent = request.getHeader("User-Agent");
Example2:
• response.setContentType("text/html");
• PrintWriter out = response.getWriter();
out.println("<h1>Hello, user!</h1>");
Initializing a Servlet
• Initialization happens once when the servlet is first loaded.
• The init() method is called by the web container.
• It prepares the servlet for use (e.g., setting up database connections, reading
config files).
init() method:
• Called only once in the servlet life cycle.
• Provided by the javax.servlet.Servlet interface.
• You can override it to perform custom initialization.
Ex- public void init() throws ServletException {
// Initialization code here
System.out.println("Servlet is initializing..."); }
The Servlet API
• The Servlet API is a set of Java interfaces and classes used to
build web applications.
• It is provided by the Java EE (Jakarta EE) platform.
• It helps in creating, handling, and managing servlets.
HttpServlet
• HttpServlet is a subclass of GenericServlet.
• It is designed specifically for handling HTTP requests like from
web browsers.
• You write servlet by extending HttpServlet and overriding methods
like doGet() and doPost()
Deploying the Servlet
• Compile your Java servlet file (javac MyServlet.java).
• Place the .class file inside the /WEB-INF/classes/ folder of your web app.
• Package the folder as a .war (Web Application Archive) file (optional).
• Deploy the app in a web server like Apache Tomcat.
Developing a Servlet
• Write your servlet code in Java by extending the HttpServlet class.
• Override methods like doGet() or doPost() to handle requests.
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello from MyServlet</h1>");
}
}
Accessing Database
What is JDBC?
• JDBC (Java Database Connectivity) is an API in Java that allows you to
connect to and interact with databases.
• It provides a set of classes and interfaces to perform database operations
like reading and writing data.
Steps to Access a Database Using JDBC
1. Load the Database Driver
You must load the database driver class so Java can communicate with the
database.
Example:
Class.forName("com.mysql.cj.jdbc.Driver"); // For MySQL
2. Establish a Connection
Use DriverManager.getConnection() to connect to the database.
Example-
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection connection = DriverManager.getConnection(url, username,
password);
3. Create a Statement
Create a Statement object to send SQL queries to the database.
Statement statement = connection.createStatement();
4. Execute SQL Queries
Use executeQuery() for select queries and executeUpdate() for insert, update,
or delete queries.
Example:
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
System.out.println(resultSet.getString("username"));
}
<---for inserting data--->
String sql = "INSERT INTO users (username, password) VALUES ('john',
'secret')";
int rowsAffected = statement.executeUpdate(sql);
5. Close the Resources
Always close the Connection, Statement, and ResultSet to free up resources.
resultSet.close();
statement.close();
connection.close();
What is a Session?
• A session is a unique identifier for a user that the server creates
when the user first connects.
• The session allows the server to remember the user across
multiple requests.
• A session lasts from when the user connects until they log out or
the session expires.
Why Sessions are Needed?
HTTP is stateless: This means each time a user makes a request,
the server doesn't remember anything about the previous requests.
To keep track of users (like remembering who’s logged in), we need
sessions.
Use Sessions in Java Servlets
1. Create a Session
When a user visits your web application for the first time, you can
create a session:
HttpSession session = request.getSession(); // Get or create
session
2. Store Data in the Session
You can store user-specific data (like their name, preferences, or
shopping cart) in the session:
session.setAttribute("username", "Rohit"); // Store user data
3. Retrieve Data from the Session
When the user makes subsequent requests, you can retrieve their
stored data:
String username = (String) session.getAttribute("username"); // Get
user data
4. Invalidate/End a Session
When the user logs out or after a certain time, you should end the
session to free up resources:
session.invalidate(); // End the session
Session Management Features
Session ID: Every session has a unique identifier, usually stored in
a cookie (JSESSIONID), which the server uses to track the session.
Session Timeout: Sessions typically expire after a certain period of
inactivity (default is usually 30 minutes). You can configure this
timeout.
Dealing with Cookies
• Cookies are small pieces of data stored on the client side.
• They can store login info, preferences, or session IDs.
• Servlets can create, read, and delete cookies.
Uses of Cookies
• Remembering logged-in users.
• Storing preferences (like language or theme).
• Session tracking (when sessions are managed via cookies).
Example:-
Cookie cookie = new Cookie("username", "Rohit"); // Create a cookie
cookie.setMaxAge(60 * 60); // Set expiry time (in seconds), e.g., 1 hour
response.addCookie(cookie); // Send cookie to client
Transferring Requests in Servlets
Sometimes in a web application, we need to send a request from one servlet to
another, or redirect the user to a different page.
There are two main ways to do this:
1. Forwarding a Request
• Used within the server.
• The control is passed from one servlet (or JSP) to another on the server side.
• The user does not see the new URL.
• Useful for internal operations (e.g., from login servlet to dashboard servlet).
Ex- RequestDispatcher rd = request.getRequestDispatcher("SecondServlet");
rd.forward(request, response);
Redirecting a Request
• Used to send the client (browser) to a different URL.
• The browser makes a new request to a different page or servlet.
• The user can see the new URL in the address bar.
• Useful when moving to a completely different resource.
Syntax:
response.sendRedirect("secondServlet");
Example:-
Forward: After checking login credentials, forward to dashboard.jsp.
Redirect: After logout, redirect to login.html.
What is ServletContext?
• ServletContext is an object that gives information about the web application.
• It is shared across the entire application — all servlets can access it.
Used to:
• Get context-wide parameters
• Access shared resources (like files, folders)
• Log messages
Access Example:
ServletContext context = getServletContext();
String appName = context.getInitParameter("appName");
INIT Parameters (Servlet-specific)
• Init parameters are specific to one servlet.
• Set in the web.xml file or using annotations.
• Passed once when the servlet is initialized.
• Useful for servlet-specific settings (e.g., database name, admin email).
Define in web.xml:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@example.com</param-value>
</init-param>
</servlet>
Access in Java:
String email = getServletConfig().getInitParameter("adminEmail");
CONTEXT Parameters (Application-wide)
• Context parameters are shared by all servlets in the application.
• Set in web.xml, outside of any servlet tag.
• Useful for global config settings (e.g., site name, base path).
Define in web.xml:
<context-param>
<param-name>appName</param-name>
<param-value>MyWebApp</param-value>
</context-param>
Access in Java:
ServletContext context = getServletContext();
String appName = context.getInitParameter("appName");
Sharing Information Using Scope Objects
Scope objects are used to share data between different parts of a web
application (like servlets and JSPs).
They define how long the data will live and where it can be accessed.
1. Request Scope
• Lives only during a single request.
• Used to pass data between servlets or JSPs in the same request.
Useful for:
• Passing form data to a result page
• Forwarding data using RequestDispatcher
Set: request.setAttribute("user", "Rohit");
Get: String name = (String) request.getAttribute("user");
2. Session Scope
• Lives as long as the user's session (until the browser is closed or session
expires).
• Used to store user-specific data like login info or shopping cart.
Set:
HttpSession session = request.getSession();
session.setAttribute("username", "Rohit");
Get:
String user = (String) session.getAttribute("username");
3. Application Scope (ServletContext)
• Lives as long as the web application is running.
• Shared by all users and servlets.
• Good for global data like config settings or counters.
Set:
ServletContext context = getServletContext();
context.setAttribute("siteName", "MyWebsite");
Get:
String name = (String) context.getAttribute("siteName");
4. Page Scope (JSP only)
• Lives only within a single JSP page.
• Used to store and use data inside one page.
Set in JSP:
<%! String message = "Hello"; %>
<jsp:useBean id="msg" scope="page" class="java.lang.String" />
What is Concurrent Access?
• In web applications, many users can access the same servlet at the same
time.
• This is called concurrent access.
• If these users share common data (e.g. updating a counter, record, or file), it
can cause data inconsistency or errors.
Example:- Let’s say two users try to update the same record at the same time.
Without control, one user’s changes might overwrite the other’s.
Solution:- Use synchronization in Java to control access to critical sections of
code — parts where shared data is read or modified.
synchronized(this) {
// critical section
counter++;
}
What is User Authentication?
• Authentication is the process of verifying a user’s identity.
• It ensures that only authorized users can access protected parts of a web
application (like admin panels, user dashboards, etc.).
Login Forms
• Most common method in web apps.
• The user enters a username and password.
• The server checks the credentials against a database or file.
Steps:
1. User submits login form.
2. Servlet receives credentials.
3. Servlet checks them in the database.
4. If correct, user is logged in and a session is created.