603_CA
603_CA
A servlet is a Java program that runs on a server and handles requests and responses in a web
application. It is part of the Java EE (Jakarta EE) platform and is used to create dynamic web
content. Servlets extend the capabilities of servers and are commonly used to process form
data, manage sessions, and control web page flow.
b) What is a protocol?
A protocol is a set of rules or standards that define how data is transmitted and received over a
network. It ensures proper communication between devices. Examples include HTTP, FTP, and
TCP/IP.
c) What is a socket?
A socket is an endpoint for communication between two machines over a network. It allows
programs to communicate using standard protocols. In Java, the Socket and ServerSocket
classes are used for client-server communication.
d) What is TCP/IP?
TCP/IP (Transmission Control Protocol/Internet Protocol) is a suite of communication protocols
used to interconnect network devices on the internet.
Thread.sleep(milliseconds);
pg. 1
1. TYPE_FORWARD_ONLY
2. TYPE_SCROLL_INSENSITIVE
3. TYPE_SCROLL_SENSITIVE
h) What is Hibernate?
Hibernate is an open-source Java framework for object-relational mapping (ORM). It simplifies
database interactions by mapping Java classes to database tables. It eliminates the need for
manual SQL queries in most cases.
i) What is a port?
A port is a logical access channel through which data is sent and received between a computer
and a network. Ports are identified by numbers (e.g., HTTP uses port 80, HTTPS uses port 443).
j) What is a session?
A session is a way to store information (state) about a user across multiple requests in a web
application. It helps maintain user data like login status, preferences, etc., while they interact
with the site.
2. TYPE_SCROLL_INSENSITIVE – The cursor can move forward and backward, but changes
made to the database after the ResultSet was created are not visible.
pg. 2
3. TYPE_SCROLL_SENSITIVE – The cursor can move in both directions and reflects changes
made to the database while the ResultSet is open.
b) What is IP Address?
c) What is JDBC?
JDBC (Java Database Connectivity) is an API in Java that allows applications to interact with
databases. It provides methods for querying and updating data in a database using SQL
commands.
d) What is servlet?
A Servlet is a Java class used to handle HTTP requests and generate dynamic web content. It
runs on a web server or application server and follows the Java EE (Jakarta EE) specification.
e) What is cookies?
Cookies are small pieces of data stored on the client-side (browser) by the server. They are used
to maintain session state, store user preferences, and track user activity on websites.
f) What is UDP?
UDP (User Datagram Protocol) is a connectionless transport protocol used for sending short
messages called datagrams. It does not guarantee delivery, ordering, or error checking, making
it faster but less reliable than TCP.
g) What is thread?
pg. 3
A Thread is the smallest unit of a process that can be executed independently. In Java, threads
are used to perform multiple tasks concurrently (multithreading), enhancing performance and
responsiveness.
h) What is socket?
A Socket is an endpoint for communication between two machines over a network. In Java,
sockets are used for client-server communication using TCP or UDP protocols.
j) What is networking?
Networking refers to the practice of connecting computers and other devices to share resources
and information. In computing, it involves hardware, software, and protocols that enable data
communication between devices.
Cookies are used to store information on the client-side to maintain session state between the
client and server. They help in tracking user activity, storing user preferences, and managing
login sessions across multiple pages.
The Runnable interface is used to define a task that can be executed by a thread. It provides a
run() method, which contains the code that runs in the thread. It is commonly used for creating
threads without subclassing the Thread class.
pg. 4
c) Explain thread priority.
Thread priority in Java determines the order in which threads are scheduled for execution. Each
thread is assigned a priority between:
• MIN_PRIORITY (1)
• MAX_PRIORITY (10)
Threads with higher priority are more likely to be executed before lower-priority
threads, although exact behavior depends on the thread scheduler.
f) What is networking?
Networking refers to connecting computers and devices to share data and resources. In
programming, it involves using protocols and APIs to enable communication between systems
over a network (e.g., using sockets in Java).
pg. 5
• url – JDBC URL of the database
The yield() method is a static method of the Thread class that temporarily pauses the currently
executing thread, allowing other threads of the same priority to execute. It does not stop the
thread but gives a chance to others.
The Socket class in Java is used to create a client-side socket that establishes a connection with a
server socket over TCP. It enables two-way communication between client and server programs.
j) What is servlet?
A Servlet is a Java class that handles HTTP requests and responses in web applications. It runs
on a server and is used to build dynamic web pages by generating content based on client
requests.
Q2
Directives in JSP provide global information about the JSP page and control how the JSP engine
processes the page. There are three types:
1. Page Directive
o Used to define attributes like import packages, session control, error handling,
etc.
o Example:
pg. 6
2. Include Directive
o Example:
3. Taglib Directive
o Example:
• wait()
• notify()
• notifyAll()
Example:
class Shared {
System.out.println("Waiting...");
wait();
pg. 7
System.out.println("Notifying...");
notify();
}).start();
try {
Thread.sleep(1000);
obj.signal();
} catch (InterruptedException e) {}
}).start();
pg. 8
Feature Statement PreparedStatement
SQL
Prone Prevents SQL Injection
Injection
Common Methods:
Method Description
pg. 9
Syntax Example:
Q3
execute() boolean (true for ResultSet) Used for any SQL statement
b) Architecture of Hibernate
Common Methods:
Example:
pg. 10
Socket s = new Socket("localhost", 1234);
s.close();
<html>
<body>
<%
%>
<%
%>
<%
} else {
%>
<%
%>
</body>
</html>
pg. 11
e) JDBC Program to delete employees starting with ‘A’
con.close();
Q4
Advantages:
Disadvantages:
pg. 12
Example:
Advantages:
Disadvantages:
@WebServlet("/AddServlet")
int a = Integer.parseInt(request.getParameter("num1"));
int b = Integer.parseInt(request.getParameter("num2"));
int sum = a + b;
response.setContentType("text/html");
pg. 13
}
ResultSet rs = ps.executeQuery();
while(rs.next()) {
con.close();
Q2
1. Driver – Loads the JDBC driver class. Interfaces connect Java applications to a database.
9. RowSet – Interface that extends ResultSet and allows JavaBeans style usage.
Diagram:
JSP Page
Class Loading
Object Instantiation
Initialization (jspInit())
Destruction (jspDestroy())
Synchronization is a mechanism that ensures only one thread can access a resource at a time.
It's essential in multithreading to prevent race conditions.
class Counter {
int count = 0;
count++;
pg. 16
import java.sql.*;
try {
if(rs.next()) {
con.close();
} catch(Exception e) {
e.printStackTrace();
Q3
• Methods:
pg. 17
o executeUpdate(): Executes INSERT, UPDATE, DELETE, returns rows affected.
t1.setPriority(Thread.MAX_PRIORITY);
System.out.println("Hello Java");
pg. 18
e) Java program to delete salary column from Emp table.
import java.sql.*;
try {
System.out.println("Column deleted.");
con.close();
} catch(Exception e) {
e.printStackTrace();
Q4
import java.net.*;
InetAddress ip = InetAddress.getLocalHost();
pg. 19
}
2. Initialization (init())
4. Destruction (destroy())
↑ ↓
init() destroy()
Multithreading is the ability of a CPU to execute multiple threads concurrently. Java uses Thread
class or Runnable interface.
Benefits:
pg. 20
• Non-blocking UI.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
HTML Form:
</form>
Great! Let's go through each question one by one with detailed explanations and code
examples where required.
Q2)
JSP (JavaServer Pages) goes through several phases during its lifecycle:
pg. 21
1. Translation: The JSP file is translated into a Servlet by the JSP engine.
3. Loading and Instantiation: The class file is loaded into memory and an instance is
created.
Diagram:
┌──────────────┐
│ JSP File │
└────┬─────────┘
┌─────────────────────┐
└────────┬────────────┘
┌─────────────────────┐
└────────┬────────────┘
┌─────────────────────────────┐
│ Loading, Instantiation, │
│ Initialization (jspInit) │
└────────┬────────────────────┘
┌───────────────────────┐
pg. 22
│ Request Handling │ -> _jspService()
└────────┬──────────────┘
┌──────────────────────┐
│ Destruction (jspDestroy) │
└──────────────────────┘
JDBC drivers are used to connect Java applications with databases. Four types of drivers exist:
c) doGet( ) vs doPost( )
pg. 23
Feature doGet() doPost()
Bookmarkable Yes No
System.out.println(i);
try {
Thread.sleep(2000); // 2 seconds
} catch (InterruptedException e) {
System.out.println(e);
t1.start();
pg. 24
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
out.println("<h1>Hello Java</h1>");
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
pg. 25
Q3)
Why needed?
To avoid data inconsistency when multiple threads modify shared data simultaneously.
class Table {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {}
Table t;
MyThread1(Table t) {
this.t = t;
t.printTable(5);
}
pg. 26
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
t.printTable(100);
t1.start();
t2.start();
Cookies are small pieces of information stored on the client’s machine by the browser. They
help in session tracking by maintaining state between requests.
// Setting a cookie
pg. 27
Cookie c = new Cookie("username", "John");
response.addCookie(c);
// Reading cookies
Use in session tracking: Cookies store session ID or user data to identify returning users and
keep the session alive.
1. Page Directive
Attributes:
• language
• contentType
• import
• errorPage
• isErrorPage
2. Include Directive
3. Taglib Directive
pg. 28
Declares tag libraries.
<%
int fact = 1;
fact *= i;
%>
<%
%>
Q4)
1. Statement
pg. 29
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
2. PreparedStatement
ps.setInt(1, 101);
ps.setString(2, "Rahul");
ps.setDouble(3, 89.5);
ps.executeUpdate();
3. CallableStatement
cs.setInt(1, 101);
cs.execute();
import java.sql.*;
try {
pg. 30
Class.forName("com.mysql.cj.jdbc.Driver");
ps.setInt(1, 1);
ps.setString(2, "Amit");
ps.setDouble(3, 92.5);
ps.executeUpdate();
System.out.println("Record inserted.");
con.close();
} catch (Exception e) {
System.out.println(e);
System.out.println("Hello Java");
pg. 31
public static void main(String[] args) {
t.start();
import java.io.*;
import java.net.*;
ss.close();
Client Code:
import java.io.*;
import java.net.*;
pg. 32
public class MyClient {
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
Q5 – Short Notes
a) run() Method
Example:
System.out.println("Thread is running");
pg. 33
t1.start(); // This calls run() internally
Example:
c) HttpServlet
• It is the base class for all servlets that handle HTTP requests.
• It provides methods like doGet(), doPost(), doPut(), doDelete() for handling different
HTTP operations.
Basic structure:
pg. 34
These methods are used for inter-thread communication and are defined in the Object class.
• wait() – Makes the current thread release the monitor and go to waiting state.
Example:
synchronized(obj) {
• Web Applications – Using Spring MVC for REST APIs and full-stack development.
• Data Access – Simplified JDBC and ORM with Spring Data JPA.
Common Methods:
• createStatement()
• prepareStatement(String sql)
• setAutoCommit(boolean)
pg. 35
• commit() / rollback()
Example:
Advantages:
• Transparent persistence
• Database independence
b) Connection Interface
c) Thread Priorities
o Thread.MIN_PRIORITY = 1
o Thread.NORM_PRIORITY = 5
pg. 36
o Thread.MAX_PRIORITY = 10
Example:
t1.setPriority(Thread.MAX_PRIORITY);
pg. 37