CONTENT
❖ Introduction to Advanced Java
Difference between Core Java and Advanced Java
JDK, JRE, and JVM refresher
Packages and Import statements
❖ . Java Database Connectivity (JDBC)
JDBC Architecture
Types of JDBC Drivers
Steps to connect to a database
Connection, Statement, PreparedStatement, ResultSet
Transaction Management
Batch Processing
Stored Procedures
❖ 3. Servlets
Servlet Life Cycle (init(), service(), destroy())
Request & Response Handling (GET, POST)
Deployment Descriptor ([Link])
HttpServlet class
Session Tracking (Cookies, URL Rewriting, HttpSession)
RequestDispatcher & ServletContext
❖ . JSP (JavaServer Pages)
JSP Life Cycle
Scripting Elements: Scriptlets, Declarations, Expressions
JSP Directives & Action Tags
Implicit Objects (request, response, session, etc.)
Expression Language (EL)
JSTL (JSP Standard Tag Library)
❖ . Java Applets (legacy / for understanding GUI basics)
Life Cycle of Applet (init(), start(), paint(), etc.)
AWT Controls and Graphics
Event Handling in Applets
❖ . RMI (Remote Method Invocation)
Distributed Application Basics
RMI Architecture
Creating Remote Interface, Implementation, Client
❖ . Web Tech
HTML
CSS
Bootstrap
JavaScript (Intro)
❖ . Server- Side Web Programming
Apache Tomcat Server Configuration
servlet programming (with Tomcat)
Introduction to SQL (Oracle/MySQL)
. Connect Servlet to MySQL
1. Introduction to Advanced Java
Advanced Java is the next level of Java programming used to build web-based, enterprise-
level, distributed, and network applications. It builds on Core Java by adding technologies such
as:
• JDBC (Java Database Connectivity)
• Servlets
• JSP (JavaServer Pages)
• Applets
• Sockets/Networking
• RMI (Remote Method Invocation)
2. Difference Between Core Java and Advanced Java
Feature Core Java Advanced Java
General-purpose Web and enterprise application
Purpose development
programming
Main OOP, Data Types, Control JDBC, Servlets, JSP, Applets,
Components Statements Networking
Package Focus java.* javax.*, [Link], [Link], etc.
Web apps, server-side apps,
Applications Desktop apps, utilities distributed apps
Learning Level Beginner Intermediate to Advanced
3. JDK, JRE, and JVM Refresher
Component Description
JVM (Java Virtual Executes Java bytecode. It is platform-dependent and
Machine) provides memory management, security, and garbage
Component Description
collection.
Provides the environment to run Java applications. It
JRE (Java Runtime contains JVM + libraries + other files needed to run Java
Environment) apps.
A full-featured development kit. It contains JRE +
JDK (Java development tools (compiler javac, debugger, etc.). Required
Development Kit) to write, compile, and run Java code.
Relationship:
JDK = JRE + Development Tools
JRE = JVM + Core Libraries
4. Packages and Import Statements
What is a Package?
A package in Java is a namespace that organizes a set of related classes and interfaces.
• Java provides built-in packages ([Link], [Link], etc.)
• You can also create custom packages
Built-in Package Example:
import [Link];
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter name: ");
String name = [Link]();
[Link]("Hello, " + name);
}
}
Custom Package Example:
1. Create a file mypack/[Link]
package mypack;
public class Hello {
public void greet() {
[Link]("Hello from custom package!");
}
}
2. Create a file [Link]
import [Link];
public class Test {
public static void main(String[] args) {
Hello h = new Hello();
[Link]();
}
}
To compile and run:
javac mypack/[Link]
javac -cp . [Link]
java Test
2. Java Database Connectivity (JDBC)
JDBC Architecture
1. Application: Java program using JDBC API.
2. JDBC API: Interfaces like Connection, Statement, PreparedStatement, ResultSet.
3. JDBC Driver Manager: Loads database drivers and manages connections.
4. JDBC Driver: Translates Java calls to database-specific calls.
5. Database: Actual data storage (e.g., MySQL, Oracle).
Types of JDBC Drivers
Type Description Pros Cons
Type JDBC-ODBC Deprecated, not
Easy setup portable
1 Bridge
Type Platform
Native-API driver Better performance dependent
2
Needs
Type Network middleware
No native library needed
3 Protocol driver server
Type Thin driver (pure Platform-independent, Database-specific
4 Java) best performance
Steps to Connect to a Database using JDBC
1. Load and register the driver:
[Link]("[Link]");
2. Create connection:
Connection con = [Link](url, user, password);
3. Create statement:
Statement stmt = [Link]();
4. Execute query:
ResultSet rs = [Link]("SELECT * FROM table");
5. Close connection:
[Link]();
JDBC Core Interfaces
• Connection: Manages the connection with the DB.
• Statement: Executes static SQL.
• PreparedStatement: Precompiled SQL with parameters (?).
• ResultSet: Holds the data retrieved from a query.
Transaction Management
[Link](false); // Start transaction
try {
// perform queries
[Link](); // Commit transaction
} catch (SQLException e) {
[Link](); // Rollback on failure
}
Batch Processing
PreparedStatement ps = [Link]("INSERT INTO employee VALUES (?, ?)");
for (...) {
[Link](1, id);
[Link](2, name);
[Link]();
}
[Link](); // Executes all in one go
Stored Procedures
MySQL procedure:
CREATE PROCEDURE getEmployee()
BEGIN
SELECT * FROM employee;
END;
Java:
CallableStatement cs = [Link]("{call getEmployee()}");
ResultSet rs = [Link]();
Example: JDBC MySQL CRUD Operations
MySQL Table:
CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(100)
);
Java Code Example:
import [Link].*;
public class JDBCDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "root";
String password = "your_password";
try {
[Link]("[Link]");
Connection con = [Link](url, user, password);
// INSERT
PreparedStatement psInsert = [Link]("INSERT INTO employee
VALUES (?, ?)");
[Link](1, 1);
[Link](2, "Alice");
[Link]();
// READ
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM employee");
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
// UPDATE
PreparedStatement psUpdate = [Link]("UPDATE employee SET
name=? WHERE id=?");
[Link](1, "Bob");
[Link](2, 1);
[Link]();
// DELETE
PreparedStatement psDelete = [Link]("DELETE FROM employee
WHERE id=?");
[Link](1, 1);
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
3. Servlets: A Servlet is a Java class used to handle requests and responses
in a web application. It runs on a Servlet container (like Apache Tomcat).
Servlet Life Cycle
1. init() – Called once when the servlet is first loaded.
2. service() – Called every time the servlet handles a request (doGet(), doPost(), etc.).
3. destroy() – Called once before the servlet is removed from memory.
public class MyServlet extends HttpServlet {
public void init() {
// Initialization code
}
protected void service(HttpServletRequest req, HttpServletResponse res) {
// Called for each request
}
public void destroy() {
// Cleanup code
}
}
POST Request
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
String username = [Link]("username");
String password = [Link]("password");
// Authenticate here
}
Deployment Descriptor ([Link])
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
HttpServlet Class
HttpServlet is an abstract class in [Link] that provides methods like:
• doGet()
• doPost()
• doPut()
• doDelete()
Session Tracking Techniques
1. Cookies
Cookie cookie = new Cookie("user", "Alice");
[Link](cookie);
2. URL Rewriting
[Link]("[Link]?user=Alice");
3. HttpSession
HttpSession session = [Link]();
[Link]("user", "Alice");
RequestDispatcher & ServletContext
• RequestDispatcher: For forwarding or including content from another resource.
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
• ServletContext: Provides context for the entire web application.
ServletContext context = getServletContext();
[Link]("globalParam");
Example: Login Form using Servlet
1. HTML Form ([Link])
<form action="login" method="post">
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password" /><br/>
<input type="submit" value="Login"/>
</form>
2. [Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = [Link]("username");
String pass = [Link]("password");
[Link]("text/html");
PrintWriter out = [Link]();
if ("admin".equals(user) && "1234".equals(pass)) {
HttpSession session = [Link]();
[Link]("username", user);
[Link]("<h2>Login successful. Welcome " + user + "!</h2>");
} else {
[Link]("<h2>Login failed. Invalid username or password.</h2>");
}
}
}
3. [Link] Configuration
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
4. JSP (JavaServer Pages): JSP allows you to embed Java code directly
into HTML pages, simplifying the development of dynamic web content. It
is typically used in MVC (Model-View-Controller) web applications for the
View layer.
JSP Life Cycle
1. Translation – JSP file is translated into a Servlet.
2. Compilation – The servlet is compiled into a .class file.
3. Loading – Class is loaded by the container.
4. Instantiation – Servlet instance is created.
5. Initialization – jspInit() is called.
6. Request Handling – _jspService() is invoked per request.
7. Destruction – jspDestroy() is called when it's taken out of service.
Scripting Elements in JSP
1. Scriptlets (<% ... %>) – Java code inside HTML:
<% int count = 5; %>
2. Declarations (<%! ... %>) – Declare methods or variables:
<%! int counter = 0; %>
3. Expressions (<%= ... %>) – Output values to browser:
<%= counter %>
JSP Directives & Action Tags
Directives
• Page: Defines page-level settings:
<%@ page contentType="text/html" %>
• Include: Includes a file at translation time:
<%@ include file="[Link]" %>
• Taglib: Declares tag libraries (like JSTL):
<%@ taglib uri="[Link] prefix="c" %>
Action Tags
• <jsp:include> – Includes a file at request time.
• <jsp:forward> – Forwards to another resource.
• <jsp:param> – Passes parameters.
• Implicit Objects in JSP
Object Description
request HttpServletRequest object
response HttpServletResponse object
session HttpSession object
application ServletContext object
out JspWriter object
config ServletConfig object
pageContext Gives access to all namespaces
page Refers to the current JSP page
exception Used for error pages only
Expression Language (EL)
Simplifies access to data:
${[Link]} // request parameter
${[Link]} // session attribute
${[Link]} // request-scoped attribute
JSTL (JSP Standard Tag Library)
Includes tags for:
• Core: <c:if>, <c:forEach>
• Format: <fmt:formatDate>
• SQL: <sql:query> (not recommended for production)
• Functions: <fn:length>, etc.
<c:if test="${not empty [Link]}">
Hello, ${[Link]}
</c:if>
Example: Registration Form with JSP + Validation
1. [Link] – Registration Form
<%@ page contentType="text/html" %>
<%@ taglib uri="[Link] prefix="c" %>
<html>
<head><title>Register</title></head>
<body>
<h2>Registration Form</h2>
<form action="[Link]" method="post">
Username: <input type="text" name="username"
value="${[Link]}"/><br/>
Password: <input type="password" name="password"/><br/>
Email: <input type="email" name="email" value="${[Link]}"/><br/>
<input type="submit" value="Register"/>
</form>
<c:if test="${not empty [Link] || not empty [Link]}">
<c:choose>
<c:when test="${empty [Link] || empty [Link] || empty
[Link]}">
<p style="color:red;">All fields are required.</p>
</c:when>
<c:otherwise>
<p style="color:green;">Registration successful for
${[Link]}!</p>
<!-- In real-world, you'd store data in DB here -->
</c:otherwise>
</c:choose>
</c:if>
</body>
</html>
How This Works
• When the user submits the form, the same [Link] page handles the POST.
• JSTL <c:if> and <c:choose> check whether all fields are filled.
• No Java code is embedded, making it clean and modern (using JSTL + EL).
5. Java Applets (legacy / for understanding GUI basics):
Deprecated: Applets are no longer supported in modern browsers and are deprecated
in Java SE.
Still useful for understanding GUI basics using AWT.
Applets are small Java programs that run inside a browser or applet viewer using the
[Link] or [Link] class.
Applet Life Cycle
Method Purpose
init() Called once when the applet is loaded
start() Called each time the applet becomes active
paint(Graphics g) Used to render graphics
stop() Called when the applet is stopped
destroy() Called when the applet is destroyed
public class MyApplet extends Applet {
public void init() { }
public void start() { }
public void paint(Graphics g) {
[Link]("Hello Applet", 20, 20);
}
public void stop() { }
public void destroy() { }
}
AWT Controls and Graphics
• Controls: Button, TextField, Label, Checkbox, Choice, List, etc.
• Layout Managers: FlowLayout, BorderLayout, GridLayout
• Graphics: Use paint(Graphics g) to draw shapes:
[Link]([Link]);
[Link](50, 50, 100, 100);
Event Handling in Applets
Handled using:
• Listeners like ActionListener, MouseListener, etc.
• Example for a button:
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
// action code
}
});
Example: Calculator Applet
Functionality: Add, Subtract, Multiply, Divide two numbers
import [Link];
import [Link].*;
import [Link].*;
/* <applet code="CalculatorApplet" width=300 height=200></applet> */
public class CalculatorApplet extends Applet implements ActionListener {
TextField num1, num2, result;
Button add, sub, mul, div;
public void init() {
setLayout(new GridLayout(5, 2));
add(new Label("Number 1:"));
num1 = new TextField(5);
add(num1);
add(new Label("Number 2:"));
num2 = new TextField(5);
add(num2);
add = new Button("Add");
sub = new Button("Subtract");
mul = new Button("Multiply");
div = new Button("Divide");
[Link](this);
[Link](this);
[Link](this);
[Link](this);
add(add); add(sub);
add(mul); add(div);
add(new Label("Result:"));
result = new TextField(10);
[Link](false);
add(result);
}
public void actionPerformed(ActionEvent e) {
try {
double n1 = [Link]([Link]());
double n2 = [Link]([Link]());
double res = 0;
if ([Link]() == add) res = n1 + n2;
else if ([Link]() == sub) res = n1 - n2;
else if ([Link]() == mul) res = n1 * n2;
else if ([Link]() == div) res = n2 != 0 ? n1 / n2 : 0;
[Link]([Link](res));
} catch (NumberFormatException ex) {
[Link]("Invalid input");
}
}
}
Running the Applet
1. Save as [Link]
2. Compile: javac [Link]
3. Create HTML file:
<html>
<body>
<applet code="[Link]" width="300" height="200"></applet>
</body>
</html>
4. Run using Applet Viewer (Java 8 or earlier):
appletviewer [Link]
6. RMI (Remote Method Invocation): Java RMI (Remote Method Invocation)
allows an object running in one Java Virtual Machine (JVM) to invoke methods on an object
running in another JVM. It enables distributed computing in Java by abstracting network
communication.
RMI Architecture Components
1. Remote Interface – Declares remote methods.
2. Remote Object (Implementation) – Implements the remote interface.
3. Stub – Client-side proxy for the remote object.
4. Skeleton – Server-side handler (auto-generated in old RMI versions).
5. RMI Registry – A name service that allows clients to obtain references to remote
objects.
RMI Workflow
1. Define a remote interface.
2. Implement the remote interface.
3. Compile with javac, generate stub classes (if Java version < 5).
4. Start the RMI registry (rmiregistry).
5. Bind the remote object to the registry.
6. Client looks up the remote object and invokes methods.
RMI Example: Remote Calculator
import [Link].*;
public interface Calculator extends Remote {
public int add(int a, int b) throws RemoteException;
public int subtract(int a, int b) throws RemoteException;
}
2. Remote Object Implementation:
import [Link];
import [Link];
public class CalculatorImpl extends UnicastRemoteObject implements Calculator {
public CalculatorImpl() throws RemoteException {}
public int add(int a, int b) { return a + b; }
public int subtract(int a, int b) { return a - b; }
}
3. Server Code:
import [Link];
import [Link];
public class CalculatorServer {
public static void main(String[] args) {
try {
CalculatorImpl calc = new CalculatorImpl();
Registry registry = [Link](1099);
[Link]("CalcService", calc);
[Link]("Calculator Service is running...");
} catch (Exception e) {
[Link]();
}
}
}
4. Client Code:
import [Link];
import [Link];
public class CalculatorClient {
public static void main(String[] args) {
try {
Registry registry = [Link]("localhost", 1099);
Calculator stub = (Calculator) [Link]("CalcService");
[Link]("3 + 4 = " + [Link](3, 4));
} catch (Exception e) {
[Link]();
}
}
}
Compile and Run Steps:
1. Compile all files:
javac *.java
2. Start RMI registry in the background:
start rmiregistry
3. Run server:
java CalculatorServer
4. Run client:
java CalculatorClient
Output (Client Side)
3+4=7
7. Web tech:
[Link] (HyperText Markup Language)
HTML is the backbone of web pages, used to structure content.
Basic HTML Structure
<!DOCTYPE html>
<html>
<head>
<title>My First Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
<a href="[Link] to Google</a>
</body>
</html>
Common HTML Elements
Element Purpose
<h1> to <h6> Headings
<p> Paragraph
<a> Anchor/link
<img> Image
<table> Table
<form> Input form
<div>, <span> Grouping elements
2. CSS (Cascading Style Sheets)
CSS styles the HTML elements—colors, layout, fonts, spacing, etc.
<style>
body { background-color: #f2f2f2; }
h1 { color: blue; font-family: Arial; }
p { font-size: 16px; }
</style>
Types of CSS
1. Inline: <h1 style="color: red;">Hello</h1>
2. Internal: In <style> tag inside HTML
3. External: Linked via a .css file
<link rel="stylesheet" href="[Link]">
3. Bootstrap (CSS Framework)
Bootstrap is a popular CSS framework for building responsive and attractive websites
quickly.
Setup
Add in the <head>:
<link href="[Link]
rel="stylesheet">
Common Bootstrap Components
<button class="btn btn-primary">Click Me</button>
<div class="container">
<div class="row">
<div class="col-md-6">Column 1</div>
<div class="col-md-6">Column 2</div>
</div>
</div>
Responsive Grid
Bootstrap uses a 12-column grid system, adapting to screen sizes using classes like:
• col-sm-*, col-md-*, col-lg-*
JavaScript (Intro)
JavaScript adds interactivity to websites. It runs in the browser and responds to events.
Example:
<script>
function greet() {
alert("Hello from JavaScript!");
}
</script>
<button onclick="greet()">Click Me</button>
• Handle button clicks, form validation
• Manipulate the DOM (HTML elements)
• Fetch data from APIs (AJAX)
• Build interactive UIs (sliders, modals)
Simple Web Page Example (HTML + CSS + JS + Bootstrap):
<!DOCTYPE html>
<html>
<head>
<title>Web Tech Demo</title>
<link
href="[Link]
rel="stylesheet">
<style>
body { padding: 20px; }
</style>
<script>
function showMessage() {
[Link]("output").innerText = "Welcome to Web
Technologies!";
}
</script>
</head>
<body>
<div class="container">
<h1 class="text-primary">Welcome</h1>
<button class="btn btn-success" onclick="showMessage()">Click Me</button>
<p id="output" class="mt-3"></p>
</div>
</body>
</html>
Summary:
Tech Use
HTML Page structure
CSS Styling and layout
Bootstrap Ready-to-use responsive design
JavaScript Interactivity and logic
[Link] side web programming: Server-Side Web Programming
refers to writing code that runs on the web server rather than the user's
browser. It processes client requests, interacts with databases, performs
business logic, and dynamically generates HTML, JSON, or other content sent
back to the client.
Apache Tomcat Server Configuration
Apache Tomcat is a popular open-source server to run Java Servlets and JSP.
Steps to Set Up Tomcat:
1. Download Tomcat:
[Link]
2. Extract & Install:
Unzip the downloaded file to a directory like C:\Tomcat.
3. Set Environment Variables:
o JAVA_HOME → Path to your JDK (e.g., C:\Program Files\Java\jdk-17)
o Optionally: Add CATALINA_HOME = Tomcat install dir
4. Start Server:
Run bin/[Link] (Windows) or bin/[Link] (Linux/Mac)
5. Access Tomcat:
Open browser → [Link]
2. Servlet Programming (with Tomcat)
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloWorldServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello, World from Servlet!</h1>");
}
}
[Link] (Deployment Descriptor)
Place in WEB-INF/[Link] of your web app:
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Directory Structure:
MyWebApp/
├── WEB-INF/
│ ├── [Link]
│ └── classes/
│ └── [Link]
Deploy:
Copy MyWebApp folder to TOMCAT_HOME/webapps/, restart Tomcat.
Access: [Link]
3. Introduction to SQL (Oracle/MySQL)
SQL Basics:
• SELECT * FROM table_name;
• INSERT INTO table (col1, col2) VALUES ('val1', 'val2');
• UPDATE table SET col1 = 'new' WHERE id = 1;
• DELETE FROM table WHERE id = 1;
Create Table Example (MySQL):
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
password VARCHAR(100)
);
4. Connect Servlet to MySQL
1. Add MySQL JDBC Driver:
• Download from [Link]
• Add [Link] to WEB-INF/lib
2. JDBC Code in Servlet:
import [Link].*;
public class DBExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String pass = "password";
try {
[Link]("[Link]");
Connection con = [Link](url, user, pass);
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM users");
PrintWriter out = [Link]();
while ([Link]()) {
[Link]("<p>" + [Link]("username") + "</p>");
}
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
Summary
Topic Technology
Server Apache Tomcat
Server-Side Language Java (Servlets)
Database Oracle or MySQL
Database Access JDBC
Web Config [Link]