0% found this document useful (0 votes)
8 views74 pages

Mca 2nd Sem Java Technology Paper 2022

The document provides an overview of key Java concepts including threads, JDBC, JSP, MVC architecture, method overriding, and the DAO pattern. It explains how to create and manage threads, interact with databases using JDBC, and structure web applications using JSP and MVC. Additionally, it covers method overriding rules and the benefits of using the DAO design pattern for database operations.

Uploaded by

ankitjangid2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views74 pages

Mca 2nd Sem Java Technology Paper 2022

The document provides an overview of key Java concepts including threads, JDBC, JSP, MVC architecture, method overriding, and the DAO pattern. It explains how to create and manage threads, interact with databases using JDBC, and structure web applications using JSP and MVC. Additionally, it covers method overriding rules and the benefits of using the DAO design pattern for database operations.

Uploaded by

ankitjangid2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

1

MCA 2nd SEM JAVA TECHNOLOGY PAPER 2022


PART – A

1. What is thread in Java?

In Java, a thread is the smallest unit of execution within a process. Java


provides built-in support for multithreading, allowing multiple threads to
run concurrently, enabling parallel execution and better resource
utilization.

Key Concepts of Threads in Java

1. Thread Class & Runnable Interface


Java provides two ways to create a thread:
o Extending the Thread class
o Implementing the Runnable interface
2. Lifecycle of a Thread
A thread goes through several states:
o New → Created but not started
o Runnable → Ready to run but waiting for CPU
o Running → Actively executing
o Blocked/Waiting → Paused due to resource unavailability
o Terminated → Execution completed
3. Thread Methods
o start() – Starts the thread
o run() – Defines the task for the thread
o join() – Waits for a thread to complete
o sleep(ms) – Pauses execution for a given time
o yield() – Suggests giving up CPU to other threads
o synchronized – Ensures thread safety
2

Example: Creating a Thread in Java

1. Extending the Thread class

class MyThread extends Thread {


public void run() {
System.out.println("Thread is
running...");
}

public static void main(String args[]) {


MyThread t1 = new MyThread();
t1.start(); // Starts the thread
}
}

2. Implementing the Runnable Interface

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is
running...");
}

public static void main(String args[]) {


Thread t1 = new Thread(new
MyRunnable());
t1.start(); // Starts the thread
}
}
3

2. What is JDBC?

JDBC (Java Database Connectivity)

JDBC (Java Database Connectivity) is an API (Application


Programming Interface) in Java that allows applications to interact with
databases. It provides a standard way to connect to, execute queries, and
manage database results.

Key Components of JDBC

1. JDBC API – Provides methods to connect, execute queries, and


process results.
2. JDBC Driver – A bridge between Java applications and the
database.
3. Connection – Represents the database connection.
4. Statement – Used to execute SQL queries.
5. ResultSet – Holds the results of queries.

JDBC Architecture

JDBC works through four types of drivers:

1. JDBC-ODBC Bridge Driver (Type 1) – Uses ODBC drivers


(outdated).
2. Native API Driver (Type 2) – Uses native DB API (platform-
dependent).
3. Network Protocol Driver (Type 3) – Uses middleware for DB
connection.
4. Thin Driver (Type 4) – Directly connects to the database (most
commonly used).
4

Steps to Use JDBC

1. Load the JDBC Driver


Class.forName("com.mysql.cj.jdbc.Driver"); //
MySQL driver

2. Establish a Connection
Connection con =
DriverManager.getConnection("jdbc:mysql://localh
ost:3306/mydb", "username", "password");

3. Create and Execute a Query


Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM
users");
while (rs.next()) {
System.out.println(rs.getString("name"));
}

4. Close the Connection


rs.close();
stmt.close();
con.close();

Example: Full JDBC Program


import java.sql.*;
5

class JDBCExample {
public static void main(String[] args) {
try {
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
Connection con =
DriverManager.getConnection("jdbc:mysql://localh
ost:3306/mydb", "root", "password");

// Create statement
Statement stmt =
con.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT * FROM users");

// Process results
while (rs.next()) {
System.out.println("User: " +
rs.getString("name"));
}

// Close connections
rs.close();
stmt.close();
con.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}
6

JDBC Interfaces Overview

Interface Description
DriverManager Manages JDBC drivers and connections
Connection Represents a connection with the database
Statement Executes SQL queries
PreparedStatement Executes precompiled queries (prevents SQL
injection)
ResultSet Stores query results

3. Define JSP.

JSP (JavaServer Pages)

JSP (JavaServer Pages) is a server-side technology in Java used to


create dynamic web pages. It allows embedding Java code within HTML
to generate dynamic content.

Key Features of JSP

1. Mixes HTML with Java – JSP allows Java code inside HTML
using special tags.
2. Simpler than Servlets – Unlike servlets, JSP is more readable
since it mainly uses HTML.
3. Automatically Compiled – JSP pages are converted into servlets
and compiled automatically by the server.
4. Supports MVC Architecture – Often used as the View
component in the Model-View-Controller (MVC) design pattern.
7

JSP Syntax and Example

1. Basic JSP Page (index.jsp)

<%@ page language="java" contentType="text/html;


charset=UTF-8" %>
<html>
<head><title>JSP Example</title></head>
<body>
<h2>Welcome to JSP!</h2>
<p>Current Date and Time: <%= new
java.util.Date() %></p>
</body>
</html>

 <%= %> → Expression tag (outputs value in HTML).


 <%@ %> → Directive tag (defines page settings).

2. JSP Scripting Elements

Element Description Example


Declarations (< Declares methods <%! int x = 10; %>
%! %>) and variables
Scriptlets (<% Java code inside <% out.println("Hello,
%>) JSP World!"); %>
Expressions (< Outputs a value in <%= new Date() %>
%= %>) HTML
8

3. JSP Directives

Directive Purpose Example


Defines page <%@ page language="java"
Page contentType="text/html" %>
settings
Includes other <%@ include file="header.jsp"
Include
JSP/HTML files %>
Enables custom <%@ taglib uri="..."
Taglib prefix="..." %>
tags

4. JSP with Database (JSP + JDBC)


<%@ page import="java.sql.*" %>
<html>
<body>
<h2>Users List</h2>
<%
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localh
ost:3306/mydb", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT
* FROM users");

while(rs.next()) {
out.println("<p>" +
rs.getString("name") + "</p>");
}

rs.close();
stmt.close();
con.close();
%>
9

</body>
</html>

JSP vs Servlet

Feature JSP Servlet


Code Type Mix of HTML & Java Pure Java
Readability Easier (more HTML) Harder (all Java)
Performance Slower (converted to servlets) Faster
Use Case View Layer (UI) Controller Logic

Why Use JSP?

✅ Simplifies Web Development – No need to write full servlets.


✅ Supports Java EE Features – Can use JDBC, JSTL, and custom
tags.
✅ Efficient – Pages are compiled once and reused.

4. Define MVC

MVC (Model-View-Controller) Architecture

MVC (Model-View-Controller) is a design pattern used in software


development to separate concerns, making applications more
maintainable and scalable. It is commonly used in web applications
(like Java EE, Spring, and JSP-based apps).

MVC Components
10

1. Model (Data Layer)


o Represents the business logic and data of the application.
o Interacts with the database and performs operations like
CRUD (Create, Read, Update, Delete).
o Example: Java Beans, POJOs, DAO classes.
2. View (Presentation Layer)
o Responsible for the user interface (UI).
o Displays data from the Model to the user.
o Example: JSP, HTML, JavaScript, CSS.
3. Controller (Business Logic)
o Acts as a bridge between the Model and the View.
o Handles user input, processes requests, and calls the
appropriate model methods.
o Example: Servlets, Spring Controllers.

How MVC Works?

1. User sends a request → Controller receives it.


2. Controller processes → Calls the Model for data.
3. Model interacts with the database → Returns data.
4. Controller sends data to View → View displays the response to the
user.

Example: MVC in JSP & Servlets

1. Model (User.java)

public class User {


private String name;
public User(String name) {
this.name = name;
}
11

public String getName() {


return name;
}
}

2. Controller (UserServlet.java)

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
protected void doGet(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException {
User user = new User("John Doe"); //
Model
request.setAttribute("user", user);
request.getRequestDispatcher("user.jsp").forward
(request, response); // Forward to View
}
}

3. View (user.jsp)

<%@ page import="com.example.User" %>


12

<%@ page language="java" contentType="text/html;


charset=UTF-8" %>
<html>
<body>
<h2>Welcome, <%= ((User)
request.getAttribute("user")).getName() %>!</h2>
</body>
</html>

Advantages of MVC

✅ Separation of Concerns – Makes code more organized.


✅ Easier Maintenance & Scalability – UI, logic, and data are
independent.
✅ Improves Code Reusability – Each layer can be modified without
affecting others.

5. Define Overriding.

Method Overriding in Java

Method Overriding is a feature in Java that allows a subclass to


provide a specific implementation of a method that is already defined in
its parent class.

Key Rules of Overriding


13

1. Same Method Signature → The method in the subclass must


have the same name, return type, and parameters as in the
parent class.
2. Inheritance is Required → The subclass must extend the parent
class.
3. Access Modifiers
o Cannot reduce visibility (e.g., protected in the parent
cannot be overridden as private in the subclass).
o Can increase visibility (protected → public).
4. Cannot Override final Methods → If a method is declared
final in the parent class, it cannot be overridden.
5. Cannot Override static Methods → Static methods belong to
the class, not instances, so they cannot be overridden (but can be
redeclared).
6. Use of @Override Annotation → Helps catch errors at compile
time.

Example of Method Overriding


// Parent Class
class Animal {
void makeSound() {
System.out.println("Animal makes a
sound");
}
}

// Child Class
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
14

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Dog(); //
Upcasting
myAnimal.makeSound(); // Calls
overridden method in Dog
}
}

Output
Dog barks

Super Keyword in Overriding

You can use the super keyword to call the parent class method inside
the overridden method.

class Animal {
void makeSound() {
System.out.println("Animal makes a
sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
super.makeSound(); // Calls parent
method
System.out.println("Dog barks");
}
}
15

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound();
}
}

Output
Animal makes a sound
Dog barks

Overriding vs Overloading

Feature Overriding Overloading


Redefining a Defining multiple methods with the
Definition
method in a subclass same name but different parameters
Must be different (number, type, or
Parameters Must be the same
both)
Must be the same
Return Type Can be different
(or covariant)
Access Cannot reduce
No restriction
Modifier visibility
Static Cannot be
Can be overloaded
Methods overridden

6. Define DAO.
16

DAO (Data Access Object) in Java

DAO (Data Access Object) is a design pattern used in Java to separate


database access logic from business logic. It provides an abstraction
layer for CRUD (Create, Read, Update, Delete) operations, making the
code more modular, reusable, and maintainable.

Key Benefits of DAO Pattern

✅ Encapsulation – Hides database logic from the rest of the application.


✅ Modularity – Database code is separated from business logic.
✅ Reusability – The same DAO class can be used in different parts of
the application.
✅ Easy Maintenance – Changes to the database structure only affect
DAO classes, not the entire application.

DAO Pattern Structure

1. Model (Entity Class) – Represents a table in the database.


2. DAO Interface – Defines CRUD methods.
3. DAO Implementation – Implements database operations using
JDBC.
4. Service Layer (Optional) – Uses DAO for business logic.

Example: DAO Implementation in Java (JDBC + MySQL)

1. Model Class (User.java)

public class User {


17

private int id;


private String name;
private String email;

public User(int id, String name, String


email) {
this.id = id;
this.name = name;
this.email = email;
}

public int getId() { return id; }


public String getName() { return name; }
public String getEmail() { return email; }
}

7. What is JSP Tags?

JSP Tags in JavaServer Pages (JSP)

JSP tags are special elements used within JSP pages to control
execution, insert dynamic content, and interact with Java code. These
tags help separate Java logic from HTML, making JSP pages more
readable and maintainable.

Types of JSP Tags

1️⃣ Scripting Tags

These allow embedding Java code directly within JSP.


18

Tag Description Example

Declarations (<%! Defines variables or <%! int count = 0;


%>) methods %>

Executes Java code inside


Scriptlets (<% %>) <% count++; %>
JSP

Expressions (<%=
Outputs a value in HTML <%= new Date() %>
%>)

Example of Scripting Tags


<%@ page language="java" %>
<html>
<body>
<%! int count = 0; %>
<p>Current Count: <%= ++count %></p>
</body>
</html>

2️⃣ Directive Tags

These provide instructions to the JSP container.

Directive Purpose Example

Defines page <%@ page language="java"


Page
settings contentType="text/html" %>
19

Directive Purpose Example

Includes other
Include <%@ include file="header.jsp" %>
JSP/HTML files

Declares custom <%@ taglib uri="..." prefix="..."


Taglib
tag libraries %>

Example of Include Directive


<%@ include file="header.jsp" %>
<h1>Welcome to My Website</h1>
<%@ include file="footer.jsp" %>

3️⃣ Action Tags

These are predefined JSP tags that perform actions on Java objects.

Descriptio
Tag Example
n
Redirects
request to <jsp:forward
<jsp:forward>
another page="home.jsp"/>
resource
Includes
output of
<jsp:include
<jsp:include> another
page="menu.jsp"/>
file at
runtime
<jsp:param> Passes <jsp:include
20

Descriptio
Tag Example
n
parameter page="profile.jsp"><jsp:p
s to aram name="id"
included value="123"/></jsp:includ
files e>

Instantiat <jsp:useBean id="user"


<jsp:useBean> es a class="com.example.User"/
JavaBean >
<jsp:setProperty
Sets a
<jsp:setPropert name="user"
JavaBean
y> property="name"
property value="Alice"/>

Retrieves
<jsp:getProperty
<jsp:getPropert a
name="user"
y> JavaBean property="name"/>
property

Example of jsp:include
<jsp:include page="header.jsp"/>
<h2>Welcome to My JSP Page</h2>
<jsp:include page="footer.jsp"/>

4️⃣ Custom Tags (JSTL & Tag Libraries)

JSP allows developers to create custom tags using JSTL (JavaServer


Pages Standard Tag Library) or custom tag libraries.
21

Tag Description Example

Prints values (like <c:out value="$


<c:out>
out.print()) {user.name}"/>

Conditional <c:if test="${age >


<c:if>
statements 18}">Adult</c:if>

<c:forEach var="item"
Loops through
<c:forEach> items="${items}"> ${item}
collections </c:forEach>

Example using JSTL


<%@ taglib
uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
<c:forEach var="num" begin="1" end="5">
<p>Number: <c:out value="${num}"/></p>
</c:forEach>

8. Define package

What is a Package in Java?


22

A package in Java is a way to group related classes and interfaces


together to provide better organization, access control, and
namespace management. It helps avoid class name conflicts and
improves code modularity.

Types of Packages in Java

Java has two types of packages:

1. Built-in Packages – Predefined in Java (e.g., java.util,


java.io).
2. User-defined Packages – Created by developers for custom
organization.

How to Create and Use a Package?

1️⃣ Creating a Package

To create a package, use the package keyword at the beginning of


the Java file.

Example: Creating a Package


package mypackage; // Declaring a package

public class MyClass {


public void display() {
System.out.println("Hello from MyClass
in mypackage");
}
}
23

📝 Save this file as MyClass.java inside a folder named


mypackage.

2️⃣ Compiling and Running a Java Package

Steps to Compile & Run a Java Package

1. Compile the package

javac -d . MyClass.java

This creates a mypackage folder containing the compiled


.class file.

2. Use the package in another class

import mypackage.MyClass; // Import the


package

public class Test {


public static void main(String[] args) {
MyClass obj = new MyClass(); //
Using the class from the package
obj.display();
}
}

3. Compile and Run


javac Test.java
java Test

Output:
24

Hello from MyClass in mypackage

Using import vs fully qualified name

 Using import (Recommended)

import mypackage.MyClass;
MyClass obj = new MyClass();

 Using Fully Qualified Name (Without import)

mypackage.MyClass obj = new


mypackage.MyClass();

Advantages of Using Packages

✅ Avoids name conflicts – Different packages can have classes with the
same name.
✅ Organizes large projects – Group similar classes together.
✅ Provides access control – Controlled access using public,
protected, or private.
✅ Encapsulates reusable code – Helps in modular development.

9. Define spring.

What is Spring in Java?

Spring Framework is a powerful, open-source framework for building


Java applications. It provides dependency injection (DI), aspect-
25

oriented programming (AOP), transaction management, and


simplifies Java EE (Enterprise Edition) development.

Spring makes Java applications modular, testable, and scalable,


supporting both standalone and enterprise applications.

Key Features of Spring Framework

✅ Lightweight – Uses POJOs (Plain Old Java Objects) and avoids heavy
configurations.
✅ Dependency Injection (DI) – Manages object creation and
dependencies automatically.
✅ Aspect-Oriented Programming (AOP) – Separates cross-cutting
concerns (e.g., logging, security).
✅ Transaction Management – Handles database transactions
efficiently.
✅ Integration Support – Works well with Hibernate, JPA, JDBC,
JMS, and REST APIs.
✅ Spring MVC – A powerful web framework for building RESTful
applications.
✅ Spring Boot – Simplifies Spring applications with auto-
configuration.

Spring Framework Modules

Spring consists of several modules, categorized into Core, Data Access,


Web, Security, and Integration.

1️⃣ Core Module

 Spring Core – Provides Dependency Injection (DI).


26

 Spring Context – Manages beans using the ApplicationContext


container.

2️⃣ Data Access Module

 Spring JDBC – Simplifies database operations.


 Spring ORM – Integrates with Hibernate, JPA, and MyBatis.

3️⃣ Web Module

 Spring MVC – A powerful web framework for REST APIs and


web applications.
 Spring WebFlux – Reactive programming for asynchronous
applications.

4️⃣ Security Module

 Spring Security – Handles authentication and authorization.


5️⃣ Integration Module

 Spring JMS – Messaging support.


 Spring Cloud – Microservices support.

Spring Example: Dependency Injection

1️⃣ Creating a Spring Bean


package com.example;
27

public class HelloWorld {


public void sayHello() {
System.out.println("Hello, Spring
Framework!");
}
}

2️⃣ Spring Configuration Using XML

File: applicationContext.xml

<beans
xmlns="http://www.springframework.org/schema/bea
ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://www.springframework.o
rg/schema/beans
http://www.springframework.org/schema/beans/spri
ng-beans.xsd">
<bean id="helloBean"
class="com.example.HelloWorld"/>
</beans>

3️⃣ Running Spring with XML Configuration

import
org.springframework.context.ApplicationContext;
28

import
org.springframework.context.support.ClassPathXml
ApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationConte
xt.xml");
HelloWorld hello = (HelloWorld)
context.getBean("helloBean");
hello.sayHello();
}
}

Output:
Hello, Spring Framework!

Spring Boot (Simplified Spring)

Spring Boot simplifies Spring applications by removing boilerplate


XML configurations and adding auto-configuration.

Spring Boot Example


import
org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBoo
tApplication;

@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
29

SpringApplication.run(SpringBootApp.class,
args);
System.out.println("Spring Boot
Application Started!");
}
}

Why Use Spring?

✅ Reduces Boilerplate Code – Uses annotations instead of XML.


✅ Enterprise Ready – Handles transactions, security, and integration
easily.
✅ Microservices Support – Works with Spring Cloud for distributed
systems.
✅ Flexible & Modular – Can use only required modules instead of the
entire framework.

10. What does the action <jsp:use Been> do?

What does <jsp:useBean> do in JSP?

The <jsp:useBean> action tag instantiates a JavaBean or retrieves


an existing one, making it accessible in a JSP page.

It helps in storing, retrieving, and manipulating data without


manually writing Java code inside JSP.

Syntax of <jsp:useBean>
30

<jsp:useBean id="beanName"
class="package.ClassName" scope="page|request|
session|application"/>

 id – The reference name for the bean in JSP.


 class – The fully qualified name of the JavaBean class.
 scope – Defines the bean’s lifespan:
o page (default) – Available only on the current page.
o request – Available for the current request.
o session – Available throughout the user session.
o application – Available across the entire application.

Example 1: Using <jsp:useBean>

1️⃣ JavaBean Class (User.java)

package com.example;

public class User {


private String name;

public User() {} // Default constructor

public String getName() { return name; }


public void setName(String name) { this.name
= name; }
}

2️⃣ Using <jsp:useBean> in JSP

<jsp:useBean id="user" class="com.example.User"


scope="session"/>
31

<jsp:setProperty name="user" property="name"


value="Alice"/>
Hello, <jsp:getProperty name="user"
property="name"/>!

Output:
Hello, Alice!

How <jsp:useBean> Works?

1. Checks if the bean exists in the specified scope.


2. If it exists, reuses it; otherwise, it creates a new instance.
3. The bean can store and retrieve data using
<jsp:setProperty> and <jsp:getProperty>.

Example 2: Using Form Data with JSP Beans

1️⃣ User Registration Form (index.jsp)

<form action="welcome.jsp" method="post">


Enter Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>

2️⃣ Processing Data with JSP (welcome.jsp)

<jsp:useBean id="user" class="com.example.User"


scope="session"/>
<jsp:setProperty name="user" property="name"
param="name"/>

Welcome, <jsp:getProperty name="user"


property="name"/>!
32

Output (User enters "John"):


Welcome, John!

Key Benefits of <jsp:useBean>

✅ Encapsulates logic in JavaBeans, keeping JSP clean.


✅ Reuses objects across different JSP pages using scope.
✅ Reduces Java code in JSP, following MVC best practices.

PART – B

1. Differentiate between .jar and war file.

Difference Between .jar and .war Files in Java

Feature .jar (Java Archive) .war (Web Application Archive)

Full Form Java Archive Web Application Archive

Used for packaging web


Used for packaging Java class
Purpose applications (JSP, Servlets,
files, libraries, and metadata.
HTML, CSS, JS, and libraries).
33

Feature .jar (Java Archive) .war (Web Application Archive)

Used for deploying web


Used for standalone Java
Usage applications on a server (Tomcat,
applications, APIs, and libraries.
JBoss, GlassFish, etc.).

.class files, META-INF/, Everything in .jar + WEB-INF/,


Contains
libraries, and manifest file. JSP files, and web resources.

Executed via java -jar Deployed to a web container like


Deployment
filename.jar. Tomcat using webapps/.

META-INF/ (Manifest file and WEB-INF/ (web.xml, classes, lib),


Structure metadata), .class files, and META-INF/, JSPs, HTML, CSS,
dependencies. JS.

Spring Boot app as a JAR JSP-based web app as a WAR


Example
(myapp.jar). (myapp.war).

Example of .jar File

1️⃣ Compile Java files:


javac MyApp.java

2️⃣ Create a JAR file:


jar cvf MyApp.jar MyApp.class
34

3️⃣ Run:
java -jar MyApp.jar

Example of .war File

1️⃣ Web application structure:


myapp/
├── index.jsp
├── WEB-INF/
│ ├── web.xml
│ ├── classes/
│ ├── lib/
├── META-INF/

2️⃣ Create a WAR file:


jar cvf myapp.war -C myapp/ .

3️⃣ Deploy to Tomcat (webapps/ folder).

When to Use What?

 Use JAR for standalone Java applications or libraries.


 Use WAR for web applications running on a Java web server.
35

2. Define session tracking.

What is Session Tracking in Java?

Session tracking is the process of maintaining user-specific data (such


as login information, preferences, or shopping cart data) across
multiple HTTP requests in a web application. Since HTTP is stateless,
session tracking helps keep user data persistent during a browsing
session.

Types of Session Tracking in Java

There are four main methods to track a session in Java:

Method Description

Stores session ID and user data in the client’s


1. Cookies
browser.

2. URL Rewriting Appends session ID as a parameter in the URL.

Stores session data in form fields, submitted with


3. Hidden Form Fields
each request.

4. HttpSession Server-side session management using the


(Recommended) HttpSession object.
36

1️⃣ Session Tracking Using Cookies

Cookies store small pieces of user data in the browser.

Example using Cookies in JSP

Setting a Cookie (setcookie.jsp)


<%
Cookie cookie = new Cookie("username",
"JohnDoe");
cookie.setMaxAge(60*60); // Expires in 1
hour
response.addCookie(cookie);
%>
Cookie set successfully!

Retrieving a Cookie (getcookie.jsp)


<%
Cookie[] cookies = request.getCookies();
for(Cookie c : cookies) {
if(c.getName().equals("username")) {
out.print("Welcome, " +
c.getValue());
}
}
%>

2️⃣ Session Tracking Using URL Rewriting

URL rewriting appends a session ID as a query parameter.

Example (sessionurl.jsp)

<%
37

String url =
response.encodeURL("dashboard.jsp");
%>
<a href="<%= url %>">Go to Dashboard</a>

3️⃣ Session Tracking Using Hidden Form Fields

Stores session-related data in hidden form fields.

Example (form.jsp)

<form action="welcome.jsp" method="post">


<input type="hidden" name="sessionId"
value="<%= session.getId() %>">
<input type="submit" value="Submit">
</form>

4️⃣ Session Tracking Using HttpSession (Recommended)

HttpSession is the best method for session tracking as it stores


data server-side.

Example: Creating a Session (login.jsp)

<%
HttpSession session = request.getSession();
session.setAttribute("username", "JohnDoe");
%>
<a href="dashboard.jsp">Go to Dashboard</a>

Example: Retrieving Session Data (dashboard.jsp)

<%
38

String user = (String)


session.getAttribute("username");
if (user != null) {
out.print("Welcome, " + user);
} else {
out.print("No session found. Please
login.");
}
%>

Example: Invalidating a Session (logout.jsp)

<%
session.invalidate(); // Ends the session
out.print("Logged out successfully!");
%>

3. What does auto commit do?


What is AutoCommit in JDBC?

In JDBC (Java Database Connectivity), auto-commit is a mode in which


every SQL statement is executed and committed automatically to the
database without requiring an explicit commit() call.

By default, JDBC connections are in auto-commit mode (true),


meaning each individual SQL operation is automatically saved in the
database.

How to Check and Set AutoCommit Mode?


39

1️⃣ Checking AutoCommit Mode


Connection conn =
DriverManager.getConnection("jdbc:mysql://localh
ost:3306/mydb", "user", "password");
System.out.println("AutoCommit Mode: " +
conn.getAutoCommit()); // Default is true

2️⃣ Disabling AutoCommit (Recommended for Transactions)


conn.setAutoCommit(false); // Disable auto-
commit

3️⃣ Manually Committing Changes


conn.commit(); // Explicitly commits all changes

4️⃣ Rolling Back Changes


conn.rollback(); // Cancels changes if an error
occurs

Example: Using AutoCommit for Transactions

❌ Without Transactions (AutoCommit Enabled)

Each SQL statement is executed separately, meaning if one fails, others


still persist.

Connection conn =
DriverManager.getConnection("jdbc:mysql://localh
ost:3306/mydb", "user", "password");

// AutoCommit is enabled by default


Statement stmt = conn.createStatement();
40

stmt.executeUpdate("INSERT INTO users (id, name)


VALUES (1, 'Alice')"); // Committed immediately
stmt.executeUpdate("INSERT INTO users (id, name)
VALUES (2, 'Bob')"); // Committed immediately

conn.close();

❌ Problem: If an error occurs after some queries run, partial changes


remain in the database.

✅ With Transactions (AutoCommit Disabled)

All statements execute as a single unit, either all succeed (commit) or


none execute (rollback).

try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localh
ost:3306/mydb", "user", "password");
conn.setAutoCommit(false); // Disable auto-
commit for transaction

Statement stmt = conn.createStatement();


stmt.executeUpdate("INSERT INTO users (id,
name) VALUES (1, 'Alice')");
stmt.executeUpdate("INSERT INTO users (id,
name) VALUES (2, 'Bob')");

conn.commit(); // ✅ Commit only if all


queries succeed
} catch (SQLException e) {
conn.rollback(); // ❌ Rollback if any query
fails
e.printStackTrace();
41

✔ Benefit: If any error occurs, all changes are rolled back, preventing
data corruption.

Key Points About AutoCommit

Feature Description

Default Mode true (AutoCommit is enabled by default)

When to When using transactions (e.g., banking, e-commerce,


Disable? booking systems)

Commit
conn.commit(); (Saves all pending changes)
Method

Rollback
conn.rollback(); (Cancels all uncommitted changes)
Method

4. Describe the web application directory structure.

Web Application Directory Structure in Java (Servlet/JSP)

A Java web application follows a standard directory structure to organize files for deployment in a
servlet container (e.g., Tomcat, GlassFish). The structure ensures separation of concerns between static
content, Java classes, configuration files, and resources.
42

📂 Standard Web Application Directory Structure


43

Breakdown of Each Directory

1️⃣ /WEB-INF (Restricted Internal Files)

📌 This folder is not accessible directly via a browser. It contains:

 web.xml → The deployment descriptor (for servlet


configurations).
 /classes → Contains compiled Java classes (Servlets, Beans).
 /lib → Stores JAR libraries (e.g., JDBC, Hibernate).
 /views → Optional folder for JSP/HTML templates.
44

5. Define servlet life cycle.

🚀 Servlet Life Cycle in Java

The servlet life cycle refers to the stages a servlet goes through from its
creation to destruction within a web server.

📌 5 Stages of Servlet Life Cycle

Stage Method Called Description

The servlet
1. Loading & Class.forName() (done by the class is loaded
Instantiation container) and
instantiated.

Called once
2. when the
init(ServletConfig config)
Initialization servlet is first
loaded.
45

Stage Method Called Description

Called for each


service(HttpServletRequest client request
3. Request
req, HttpServletResponse (handles
Handling res) GET/POST
requests).

Called once
before the
4. Destroying destroy() servlet is
removed from
memory.

JVM garbage
5. Garbage collector
finalize() (JVM cleanup)
Collection removes the
servlet object.

📝 Servlet Life Cycle Flow

⃣ Servlet class is loaded


1️
⃣ `init()` method is called (only once)
2️
⃣ `service()` method is called for each request
3️
⃣ `destroy()` method is called when shutting
4️
down
46

⃣ Garbage collector removes the servlet


5️

🔥 Servlet Life Cycle Example (Simple Servlet)


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

⃣ Initialization (Called Once)


// 1️
public void init() throws ServletException {
System.out.println("Servlet
Initialized!");
}

// 2️⃣ Request Handling (Called for each


request)
public void service(HttpServletRequest req,
HttpServletResponse res) throws IOException {
res.getWriter().println("Hello, Servlet
Life Cycle!");
System.out.println("Service method
called!");
}

// 3️⃣ Destroying (Called Once Before


Removal)
public void destroy() {
System.out.println("Servlet
Destroyed!");
}
}
47

🔄 Life Cycle Methods in Detail

1️⃣ init() Method (Initialization)

 Called only once when the servlet is first loaded.


 Used for setting up resources like database connections.
public void init() {
System.out.println("Servlet is
initialized!");
}

2️⃣ service() Method (Request Processing)

 Handles client requests (GET/POST, etc.).


 Called each time a request is received.
public void service(HttpServletRequest req,
HttpServletResponse res) throws IOException {
res.getWriter().println("Processing
request...");
}

3️⃣ destroy() Method (Cleanup)

 Called once before the servlet is unloaded.


 Used to release resources (database, file handles).

public void destroy() {


System.out.println("Servlet is being
destroyed!");
}
48

🎯 Servlet Life Cycle Diagram

┌───────────────────┐
│ Class Loading │
└────────▲──────────┘

┌───────▼────────┐
│ init() Method │ (Called Once)
└───────▲────────┘

┌───────▼──────────┐
│ service() Method│ (Called for Each Request)
└───────▲──────────┘

┌───────▼──────────┐
│ destroy() Method│ (Called Once Before Removal)
└──────────────────┘

🚀 Summary

✔ Servlets follow a defined life cycle managed by the Servlet Container.


✔ init() → Called once when the servlet is loaded.
✔ service() → Handles each client request (GET/POST).
✔ destroy() → Called once before removal to free resources.

PART – C

1. Explain inter servlet communication its use and methods.

📌 Inter-Servlet Communication in Java

🚀 What is Inter-Servlet Communication?


49

Inter-Servlet Communication (ISC) allows one servlet to communicate


with another servlet running in the same web application. This helps
servlets share data, forward requests, or include responses from other
servlets.

💡 Why Use Inter-Servlet Communication?

 Modular Development: Divides logic into multiple servlets for


better maintainability.
 Request Chaining: Allows one servlet to process data and pass it
to another servlet.
 Code Reusability: One servlet can use another servlet’s
functionality instead of duplicating code.

🛠️Methods for Inter-Servlet Communication

There are 4 main methods for servlet-to-servlet communication:

Method Description Example Use Case

Transfers control Login processing →


1. RequestDispatcher
from one servlet to Redirect to Dashboard
(Forwarding/Including)
another. servlet.

User submits a form →


2. sendRedirect() (Client- Redirects user to
Redirect to
Side Redirect) another servlet/page.
confirmation page.

Stores shared data Store total site visitors


3. Using ServletContext
across servlets. count.
50

Method Description Example Use Case

(Shared Data)

Calls another
Servlet A calls a
4. Direct Method Invocation servlet's methods
method from Servlet B.
directly.

1️⃣ RequestDispatcher (Forwarding & Including)

The RequestDispatcher interface allows one servlet to forward a


request or include the response of another servlet.

✔ Forwarding a Request (forward())

📌 Transfers control to another servlet without returning to the


original servlet.
📌 Client does not see URL change (internal forwarding).

Example: Forwarding from LoginServlet to


DashboardServlet

RequestDispatcher rd =
request.getRequestDispatcher("DashboardServlet")
;
rd.forward(request, response);

🔹 Example Flow:

1. LoginServlet authenticates the user.


2. If valid, request is forwarded to DashboardServlet.
51

✔ Including Another Servlet’s Response (include())

📌 Executes another servlet and includes its response in the current


servlet’s output.

Example: Including HeaderServlet Inside MainServlet

RequestDispatcher rd =
request.getRequestDispatcher("HeaderServlet");
rd.include(request, response);

✅ Useful for reusable components (e.g., headers, footers).

2️⃣ sendRedirect() (Client-Side Redirect)

📌 Redirects the client to another servlet or webpage.


📌 The URL changes because the request is sent to the browser.

Example: Redirecting from LoginServlet to HomeServlet

response.sendRedirect("HomeServlet");

🔹 Difference from RequestDispatcher

 sendRedirect() creates a new request → URL changes.


 forward() keeps the same request → URL remains unchanged.

3️⃣ ServletContext (Shared Data Between Servlets)

📌 ServletContext is a shared memory space that allows servlets to


store and access data globally.
52

Example: Storing and Retrieving Shared Data

// Storing a value in one servlet


ServletContext context = getServletContext();
context.setAttribute("totalUsers", 100);

// Retrieving the value in another servlet


ServletContext context = getServletContext();
int totalUsers = (int)
context.getAttribute("totalUsers");
response.getWriter().println("Total Users: " +
totalUsers);

✅ Useful for storing global data like site visitors count, configuration
settings, etc.

4️⃣ Direct Method Invocation (Calling Another Servlet’s Methods)

📌 One servlet creates an instance of another servlet and calls its


methods directly.

Example: Servlet A Calling a Method from Servlet B

// Servlet A
ServletB servletB = new ServletB();
String message = servletB.getMessage();
response.getWriter().println("Message from
ServletB: " + message);

⚠ Issue: This approach does not use the servlet container


(Tomcat/Jetty), so it might not handle requests properly.
53

🔄 Comparison of Methods

URL Same
Method Use Case
Change? Request?
Internal navigation
RequestDispatcher.forward() ❌ No ✅ Yes
(login → dashboard)

Reusable
RequestDispatcher.include() components ❌ No ✅ Yes
(headers, footers)

External redirection
sendRedirect() (user logout → ✅ Yes ❌ No
home page)

ServletContext Global data sharing ❌ No ✅ Yes

Calling another
Direct Method Call ❌ No ✅ Yes
servlet’s method

2. Describe JSP architecture.

📌 JSP Architecture

🚀 What is JSP Architecture?


54

JSP (JavaServer Pages) follows a multi-tier architecture where the


presentation layer (JSP) interacts with the business logic (Servlets, Java
Beans) and the database layer (JDBC, Hibernate). It follows the Model-
View-Controller (MVC) pattern for structured web applications.

🛠️JSP Architecture Components

JSP architecture consists of 4 main components:

Component Description

The user sends an HTTP request from a web


1️⃣ Client (Browser)
browser.

2️⃣ JSP Page The JSP page processes the request and dynamically
(Presentation Layer) generates HTML.

3️⃣ Servlet (Controller Servlets handle business logic and forward requests
Layer) to JSPs or databases.

4️⃣ Database The database stores and retrieves data via JDBC or
(Persistence Layer) ORM frameworks like Hibernate.

📂 JSP Architecture Flow Diagram


55

🔄 Steps in JSP Request Processing

1️⃣ Client (User) sends an HTTP request

 Example: A user requests index.jsp.

2️⃣ Web Server (Tomcat) Receives the Request

 The server checks if the JSP page is compiled.


 If not compiled, the JSP is translated into a Servlet and then
compiled.
56

3️⃣ Servlet Processes Business Logic

 The request may go to a Servlet (Controller) for processing.


 The servlet interacts with Java Beans, databases, or external
APIs.

4️⃣ JSP Page Generates Response

 The JSP page uses the data from the servlet and dynamically
generates an HTML response.

5️⃣ Response Sent to the Client

 The browser receives the generated HTML and renders the web
page.

🔎 Detailed JSP Processing Lifecycle

Stage Process Description

1. Translation The JSP file is converted into a Java Servlet.

2.
The translated Java Servlet is compiled into a .class file.
Compilation

The compiled servlet is loaded into memory by the web


3. Loading
container.

The _jspService() method executes to generate the


4. Execution
response.

5. Destruction When not needed, the servlet is removed from memory.


57

🛠️Example of JSP Architecture in Action

1️⃣ index.jsp (Client Request - View Layer)

<%@ page language="java" contentType="text/html;


charset=UTF-8" %>
<html>
<head><title>JSP Example</title></head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text"
name="username"><br>
Password: <input type="password"
name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

2️⃣ LoginServlet.java (Controller Layer)

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

public class LoginServlet extends HttpServlet {


protected void doPost(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException {

String username =
request.getParameter("username");
String password =
request.getParameter("password");
58

if (username.equals("admin") &&
password.equals("1234")) {
request.setAttribute("user",
username);
request.getRequestDispatcher("dashboard.jsp").fo
rward(request, response);
} else {
response.sendRedirect("index.jsp?
error=Invalid Credentials");
}
}
}

3️⃣ dashboard.jsp (JSP View Layer)

<%@ page language="java" contentType="text/html;


charset=UTF-8" %>
<html>
<head><title>Dashboard</title></head>
<body>
<h2>Welcome, <%=
request.getAttribute("user") %>!</h2>
</body>
</html>

🎯 Key Features of JSP Architecture

✔ Follows MVC Pattern → JSP for View, Servlets for Controller,


Database for Model.
✔ Supports Dynamic Content → Generates HTML dynamically based
on user inputs.
✔ Encapsulates Java Code → Uses Java Beans and Servlets for logic,
keeping JSP clean.
59

✔ Efficient Processing → JSPs are converted into Servlets for faster


execution.

3. Describe JDBC architecture with diagram.

📌 JDBC Architecture

🚀 What is JDBC?

JDBC (Java Database Connectivity) is a Java API that allows Java


applications to interact with databases. It enables executing SQL
queries, retrieving results, and performing database operations.

🛠️JDBC Architecture Components

JDBC follows a 4-tier architecture:

Component Description

1️⃣ Java The client application that sends SQL queries using
Application JDBC API.

Provides methods for connecting to databases and


2️⃣ JDBC API
executing queries.
60

Component Description

A bridge between the Java application and the


3️⃣ JDBC Driver database. Converts Java calls into database-specific
calls.

The actual database where data is stored (e.g., MySQL,


4️⃣ Database
PostgreSQL, Oracle).

📂 JDBC Architecture Flow Diagram


61

🔄 Steps in JDBC Connection

1️⃣ Load the JDBC Driver → Select the correct driver for the database.
2️⃣ Establish Connection → Connect to the database using
DriverManager.
3️⃣ Create Statement → Prepare and execute SQL queries.
4️⃣ Process Results → Retrieve and manipulate data from the result set.
5️⃣ Close Connection → Release database resources.

🛠️Example: JDBC Connection with MySQL


62

import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";

try {
⃣ Load JDBC Driver
// 1️
Class.forName("com.mysql.cj.jdbc.Driver");

⃣ Establish Connection
// 2️
Connection conn =
DriverManager.getConnection(url, user,
password);

⃣ Create and Execute Statement


// 3️
Statement stmt =
conn.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT * FROM users");

⃣ Process Results
// 4️
while (rs.next()) {
System.out.println("User: " +
rs.getString("username"));
}

⃣ Close Connection
// 5️
rs.close();
stmt.close();
conn.close();
63

} catch (Exception e) {
e.printStackTrace();
}
}
}

📌 Types of JDBC Drivers

JDBC supports 4 types of drivers:

Driver Description Example


Type
Type 1:
Uses ODBC driver
JDBC-
(not sun.jdbc.odbc.JdbcOdbcDriver
ODBC
recommended)
Bridge
Type 2:
Uses native
Native API Oracle OCI Driver
database libraries
Driver
Type 3:
Converts JDBC
Network
calls to a network Middleware-based driver
Protocol
protocol
Driver
Type 4: Directly
Thin Driver communicates MySQL, PostgreSQL JDBC drivers
(Pure Java) with the database

✅ Type 4 drivers are most commonly used because they are fast,
platform-independent, and require no extra configuration.
64

🎯 Summary

✔ JDBC connects Java applications to databases.


✔ Uses JDBC API and drivers to communicate with databases.
✔ Follows a 4-tier architecture: Java App → JDBC API → JDBC Driver
→ Database.
✔ JDBC Drivers help in converting Java calls to database-specific
queries.
✔ Supports executing SQL queries and retrieving results efficiently.

4. Explain spring framework.

📌 Spring Framework Overview

🚀 What is Spring Framework?

Spring is a lightweight, open-source framework for building Java


enterprise applications. It provides dependency injection (DI), aspect-
oriented programming (AOP), and transaction management, making
Java development easier and more efficient.

🔹 Core Features: Dependency Injection, IoC (Inversion of Control),


MVC, JDBC support, AOP, Security, and Microservices.
🔹 Used For: Web applications, REST APIs, microservices, and enterprise
applications.

📂 Spring Framework Architecture


65

Spring follows a layered architecture:

Layer Description

Provides Dependency Injection (DI) and


1️⃣ Spring Core Container
Bean Management using IoC.

2️⃣ Spring AOP (Aspect-Oriented Enables cross-cutting concerns like logging


Programming) and security.

Provides JDBC, Hibernate, JPA, and


3️⃣ Spring Data Access Layer
Transaction Management support.

Used to create web applications and REST


4️⃣ Spring MVC (Web Layer)
APIs.

5️⃣ Spring Security Handles authentication and authorization.

Simplifies configuration for microservices


6️⃣ Spring Boot
and standalone applications.
66

📂 Spring Framework Flow Diagram

📌 Explanation of the Flow:

1️⃣ Client Request → Sent to the DispatcherServlet.


2️⃣ Handler Mapping → Determines which Controller should handle
the request.
3️⃣ Handler Adapter → Invokes the selected Controller.
67

4️⃣ Controller → Processes the request and interacts with the Service
layer.
5️⃣ Service Layer → Executes business logic and fetches data from the
Repository (DAO Layer).
6️⃣ View Resolver → Determines which View (JSP, Thymeleaf, etc.) to
render.
7️⃣ View → Generates the response using the Model data.
8️⃣ Response → Sent back to the client.

🔥 Key Spring Modules

Spring is divided into several modules:

Module Description

Spring Core Provides IoC and Dependency Injection.

Spring AOP Enables aspect-oriented programming (AOP).

Spring MVC Used to build web applications and REST APIs.

Spring Security Manages authentication and authorization.

Spring Boot Simplifies configuration and reduces boilerplate code.


68

Module Description

Spring Data JPA Helps with database interaction using Hibernate.

🛠️Example: Spring Boot REST API

1️⃣ Add Dependencies (pom.xml)

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-
web</artifactId>
</dependency>
</dependencies>

2️⃣ Create Spring Boot Application


import
org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBoo
tApplication;

@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class,
args);
}
69

3️⃣ Create a REST Controller


import
org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
}

4️⃣ Run the Application

 Start the application and open:


👉 http://localhost:8080/api/hello
 Expected output: Hello, Spring Boot!

🎯 Why Use Spring?

✔ Lightweight & Modular → Uses DI to reduce boilerplate code.


✔ Powerful Web & API Support → Spring MVC and RESTful services.
✔ High Security → Spring Security for authentication and authorization.
✔ Easy Database Access → Works with Hibernate, JPA, and JDBC.
✔ Microservices Ready → Spring Boot simplifies cloud-native
development.
70

5. Describe the packages of JSP and servlets with examples.

📌 JSP and Servlet Packages in Java

Java provides several built-in packages for working with JSP


(JavaServer Pages) and Servlets. These packages help in handling
requests, responses, sessions, and other web-related functionalities.

📂 1. Servlet Packages

🔹 javax.servlet (Core Servlet Package)

This package provides the basic classes and interfaces for handling
HTTP requests and responses in servlets.

Class / Interface Description


Servlet Interface for defining a servlet.
GenericServlet A protocol-independent servlet base class.
HttpServlet A base class for handling HTTP-specific requests.
ServletConfig Used to configure servlets.
ServletContext Provides access to servlet container information.

RequestDispatcher For forwarding or including resources in a servlet.


71

✅ Example: Basic Servlet Using javax.servlet

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {


protected void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException
{
response.getWriter().println("Hello,
this is a Servlet!");
}
}

🔹 javax.servlet.http (HTTP-Specific Servlet Package)

This package extends javax.servlet to handle HTTP requests


and responses.

Class / Interface Description


HttpServletRequest Represents an HTTP request.
HttpServletResponse Represents an HTTP response.
HttpSession Manages user sessions.
Cookie Creates and manages cookies.
72

Class / Interface Description


HttpServlet Base class for HTTP servlets.

✅ Example: Using HttpServletRequest and


HttpServletResponse

protected void doPost(HttpServletRequest


request, HttpServletResponse response)
throws ServletException, IOException {
String username =
request.getParameter("username");
response.getWriter().println("Welcome, " +
username);
}

📂 2. JSP Packages

🔹 javax.servlet.jsp (Core JSP Package)

This package provides interfaces and classes for working with JSP
pages.

Class / Interface Description

JspPage Defines the basic structure of a JSP page.


73

Class / Interface Description

HttpJspPage Extends JspPage for HTTP-specific functionality.

JspFactory Provides factory methods for creating JSP objects.

PageContext Provides access to various page-level objects.

JspWriter Handles output streaming in JSP.

✅ Example: Using JspWriter in JSP

<%@ page language="java" %>


<%
JspWriter out = pageContext.getOut();
out.println("Hello, JSP!");
%>

🔹 javax.servlet.jsp.tagext (JSP Tag Library Package)

This package is used for custom tag handling in JSP.

Class / Interface Description


Tag Defines a custom tag.
TagSupport A base class for custom tag handling.
BodyTagSupport Supports body content processing in custom tags.
74

Class / Interface Description


TagLibraryInfo Provides information about tag libraries.

✅ Example: Creating a Custom Tag in JSP


import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

public class HelloTag extends TagSupport {


public int doStartTag() {
try {
pageContext.getOut().print("Hello,
Custom Tag!");
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
}

You might also like