[Go to site: main page, start]

0% found this document useful (0 votes)
4 views11 pages

Exam Notes Java Web

The document provides comprehensive exam notes on Java Web Technologies, covering Java Swing GUI components, the evolution of the web, and Java Servlets. It details various GUI components like JLabel, JTextField, and JList, and explains the transition from static to dynamic web content through technologies like CGI and Servlets. Additionally, it discusses session tracking and cookies for managing user data across web applications.

Uploaded by

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

Exam Notes Java Web

The document provides comprehensive exam notes on Java Web Technologies, covering Java Swing GUI components, the evolution of the web, and Java Servlets. It details various GUI components like JLabel, JTextField, and JList, and explains the transition from static to dynamic web content through technologies like CGI and Servlets. Additionally, it discusses session tracking and cookies for managing user data across web applications.

Uploaded by

Prajval (Arun)
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Web Technologies

Comprehensive Exam Notes

Covers: Java Swing GUI • Evolution of Web • Servlets • Sessions & Cookies

NIE Mysuru — Advanced Java


MODULE 1: Java Swing GUI Components
Java Swing is a GUI toolkit built on top of AWT. It provides a rich set of lightweight, platform-independent
components for building desktop applications.

1.1 JLabel and ImageIcon


• JLabel — Displays a short string or an image icon. It is a non-editable display area.
• Constructors: JLabel(String text) | JLabel(Icon icon) | JLabel(String text, Icon icon, int
horizontalAlignment)
• ImageIcon — Used to load and display images from file paths or URLs.
ImageIcon icon = new ImageIcon("[Link]");
JLabel label = new JLabel("NIE", icon, [Link]);

1.2 JTextField
• JTextField — Allows the user to edit a single line of text.
• Constructors: JTextField(int columns) | JTextField(String text, int columns)
• Key Methods: getText() | setText(String) | setEditable(boolean)
JTextField field = new JTextField("Enter Name", 20);

1.3 Swing Buttons


Component Purpose Example

JButton Push button that triggers an action JButton btn = new JButton("Submit");

JCheckBox Allows multiple independent selectionsJCheckBox cb = new JCheckBox("I agree");

JRadioButton Single selection from a group (use ButtonGroup)


JRadioButton rb = new JRadioButton("Male");

Note: Group JRadioButtons using ButtonGroup so only one can be selected at a time.

1.4 JTabbedPane and JScrollPane


• JTabbedPane — Provides tabbed navigation between multiple components/panels.
• Method: addTab(String title, Component c)
• JScrollPane — Wraps a component (e.g., JTextArea, JTable) to add scroll bars automatically.
JTabbedPane tabs = new JTabbedPane();
[Link]("Tab 1", new JPanel());
JScrollPane scroll = new JScrollPane(new JTextArea(10, 30));
[Link]("TextArea Tab", scroll);
[Link](tabs);

1.5 JList
• JList — Displays a scrollable list of items for single or multiple selection.
• Supports: SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, MULTIPLE_INTERVAL_SELECTION
• Key Methods: getSelectedValue() | getSelectedValuesList() | setSelectionMode(...)
String[] courses = {"ADA", "DBMS", "JAVA"};
JList<String> list = new JList<>(courses);
[Link](ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane sp = new JScrollPane(list); // wrap in scrollpane

1.6 JComboBox
• JComboBox — Shows a compact drop-down list; allows only one selection at a time.
• Key Methods: getSelectedItem() | addItem(String) | removeItem(String)
String[] branches = {"ISE", "CSE", "ECE"};
JComboBox<String> combo = new JComboBox<>(branches);

1.7 JTree
• JTree — Displays hierarchical data (Root → Branch → Leaf). Supports expand/collapse.
• DefaultMutableTreeNode — Used to build the tree structure; each node can have a parent and children.
• TreeSelectionListener — Interface to detect when a user selects a node.
• TreePath — Represents the path from root to a selected node.
DefaultMutableTreeNode root = new DefaultMutableTreeNode("B.E. (ISE)");
DefaultMutableTreeNode sem4 = new DefaultMutableTreeNode("Semester 4");
[Link](new DefaultMutableTreeNode("Advanced Java"));
[Link](sem4);
JTree tree = new JTree(root);
// Selection listener
[Link](e -> {
DefaultMutableTreeNode node =
(DefaultMutableTreeNode) [Link]();
[Link]("Selected: " + node);
});

1.8 JTable
• JTable — Displays tabular data in rows and columns. Cells are editable by default.
• Key classes: JTable, DefaultTableModel, JScrollPane (always wrap JTable in JScrollPane)
String[] cols = {"Roll No", "Name", "Marks"};
Object[][] data = {{"4NI23IS6", "Ravi", 85}, {"4NI23IS4", "Raj", 95}};
JTable table = new JTable(data, cols);
[Link](new JScrollPane(table));

Component Best Use Case Storage Type

JList Single/multi selection from a list Array / ListModel

JComboBox Single selection, compact space Array

JTree Hierarchical/nested data DefaultMutableTreeNode

JTable Tabular row-column data Object[][] / DefaultTableModel


MODULE 2: Evolution of the Web
Understanding the web's evolution explains why Java Servlets were introduced as a solution for dynamic content
generation.

Era Technologies Characteristics Example

Web 1.0
HTML, CSS Static pages, same content for all users, no interactivity
College syllabus page
(1990s–2000s)

Web 2.0 CGI, PHP, JSP,


Dynamically generated pages, login, forms, personalization
Login page: "Hello, Student!"
(2000s onward) Java Servlets

Web 2.5 AJAX, jQuery,


Partial page updates, no full reload, real-time feedback
Search suggestions while typing
(2005+) REST APIs

Web 3.0 React, Angular,


Personalized, intelligent, decentralized, cloud-based
Chatbots, recommendation engines
(Modern) Spring Boot, AI

2.1 Static vs Dynamic Web Content


• Static Content Flow: User → URL → HTTP Request → Server maps to file → HTTP Response (MIME type
text/html)
• Dynamic Content: Response is generated on the fly based on user input, database, time, etc.

2.2 CGI — Common Gateway Interface


• First approach to dynamic content; scripts written in C, C++, Perl.
• CGI spawns a new process for every incoming request — very resource-intensive.
• Problems with CGI: High CPU/memory usage • Inefficient DB connections • Platform-dependent • Poor
scalability

2.3 Servlets — The Solution


• Servlets run inside the web server's JVM — no new process per request; uses threads instead.
• Written in Java → platform-independent, secure, full access to Java libraries.

Feature CGI Java Servlets

Request handling New process per request New thread per request (efficient)

Platform Platform-dependent (C/Perl) Platform-independent (Java)

Performance Slow, heavy resource use Fast, lightweight

DB connections Opened/closed per request Can be pooled and reused

Security Limited Java Security Manager

Libraries Limited Full Java class library access

2.4 Why Java Servlets?


• Handle user HTTP requests and generate dynamic HTTP responses.
• Connect with databases, manage user sessions, maintain state.
• Form the foundation for Java EE web development (JSP, Spring MVC, etc.)
MODULE 3: Java Servlets — Server-Side Coding

3.1 What is a Servlet?


A Servlet is a Java class that runs on a server and handles HTTP requests, processing them and generating
HTTP responses. Servlets are part of Java EE (now Jakarta EE) and run inside a Servlet Container (e.g., Apache
Tomcat).

3.2 HTTP Requests — Preamble


• An HTTP Request is a message sent by the client (browser) to the server asking for a resource.

Part of Request Description

Method GET or POST (or PUT, DELETE, etc.)

URL The path being requested (e.g., /products)

Headers Extra metadata (Accept type, cookies, etc.)

Body Only in POST — contains the submitted data

Method Purpose Data Visibility Use Case

GET Retrieve data Visible in URL (query string) View a page, search

POST Send / submit data Hidden in request body Login, form submit

PUT Update a resource Hidden in body REST API update

DELETE Delete a resource In URL REST API delete

HTTP Response components: Status Code (200 OK, 404 Not Found, 500 Error) | Headers (content type) | Body
(HTML, JSON, etc.)

3.3 Servlet Lifecycle


The Servlet Container (Tomcat) manages the lifecycle automatically. You override the methods but never call them
directly.

Method Called By When Purpose

init() Servlet Container Once, when servlet is first loadedInitialize resources (DB connections, config)

service() Servlet Container On every HTTP request Dispatches to doGet(), doPost(), etc.

destroy() Servlet Container Once, before servlet is removed Clean up resources, close connections

doGet() service() method On HTTP GET request Override to handle GET

doPost() service() method On HTTP POST request Override to handle POST

Note: Lifecycle flow: init() → service() [→ doGet()/doPost()] → destroy()

3.4 Basic Servlet Structure


import [Link].*;
import [Link].*;
import [Link];
import [Link].*;

@WebServlet("/hello") // URL mapping


public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello, World!</h1>");
}

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Handle POST logic here
}
}

3.5 Key Request Methods


Method Description

[Link]("name") Get form field value

[Link]("headerName") Read a request header

[Link]() Get HTTP method (GET, POST, etc.)

[Link]() Get the requested URI path

[Link]() Get all cookies from browser

[Link]() Get or create an HttpSession

3.6 Key Response Methods


Method Description

[Link]("text/html") Set MIME type of response

[Link]() Get PrintWriter to write output

[Link](SC_OK) Set HTTP status code (200)

[Link](SC_NOT_FOUND) Send 404 error response

[Link]("url") Redirect client to another URL

[Link](cookie) Send a cookie to the browser

3.7 GET Request Example


@WebServlet("/greet")
public class GreetServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String name = [Link]("name");
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h2>Hello, " + name + "!</h2>");
}
}
// Access via: [Link]

3.8 POST Request Example


@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String username = [Link]("username");
String password = [Link]("password");
if ([Link]("admin") && [Link]("1234")) {
[Link]("[Link]");
} else {
[Link](HttpServletResponse.SC_UNAUTHORIZED,
"Invalid credentials");
}
}
}
MODULE 4: Session Tracking and Cookies

4.1 The Problem — HTTP is Stateless


HTTP is a stateless protocol — each request is independent; the server has no memory of previous requests. This
makes it impossible to track a user across multiple pages without extra mechanisms.
• Problem scenario: User logs in → navigates to another page → server 'forgets' who the user is.
• Goal of Session Tracking: Maintain user-specific data across multiple requests.

4.2 Cookies
• Definition: Cookies are small pieces of text data stored on the client-side (browser).
• The server sends cookies with the response; the browser sends them back with every subsequent request.
• Used for: Session identifiers, user preferences, login tokens, tracking visits.
• Size limit: ~4KB per cookie.

Creating and Sending a Cookie


// In doGet or doPost:
Cookie cookie = new Cookie("username", "Shashank");
[Link](60 * 60); // Expires in 1 hour
[Link](cookie); // Send to browser

Reading Cookies from the Browser


Cookie[] cookies = [Link]();
if (cookies != null) {
for (Cookie c : cookies) {
if ([Link]().equals("username")) {
[Link]("Hello, " + [Link]());
}
}
}

Important Cookie Methods


Method Description

new Cookie(name, value) Create a new cookie

[Link](seconds) Set expiry time (0 = delete cookie)

[Link]() Get the cookie value

[Link]() Get the cookie name

[Link](cookie) Send cookie to client

[Link]() Retrieve all cookies from client

4.3 HttpSession — Server-Side Session Tracking


• Definition: HttpSession is a server-side mechanism to store user data across multiple requests.
• More secure and flexible than cookies — actual data is stored on the server.
• The server creates a unique Session ID (JSESSIONID), usually stored in a browser cookie.
• Sessions expire on browser close or after a configured timeout period.

Creating / Accessing a Session


// Get existing session or create new one
HttpSession session = [Link]();
// Store data in session
[Link]("username", "Shashank");
[Link]("role", "admin");

// Retrieve data from session (in same or later request)


String user = (String) [Link]("username");
[Link]("Hello, " + user);

Other Important Session Methods


Method Description

[Link]() Get or create session

[Link](false) Get session only if it exists (no create)

[Link](key, value) Store an object in session

[Link](key) Retrieve stored object

[Link](key) Remove a specific attribute

[Link]() Destroy session (use on logout)

[Link]() Get the unique session ID string

[Link](sec) Set timeout (in seconds)

4.4 Cookies vs Session Tracking — Comparison


Aspect Cookies Session Tracking (HttpSession)

Storage Location Client-side (browser) Server-side

Data Capacity ~4 KB per cookie No fixed limit (server memory)

Security Less secure — can be stolen/tampered More secure — data on server

Lifespan Persists if expiry is set; survives browser close


Expires on browser close or timeout

Use Cases Remember preferences, track visits, language


Login state, shopping cart, authentication

Management Manual (create, read, delete) Automatic via HttpSession API

Dependency No server memory needed Requires server memory per user

Note: Use sessions for sensitive data (login, cart). Use cookies for non-sensitive persistent preferences.

4.5 Complete Login + Session Flow Example


// [Link] — handles POST from login form
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String user = [Link]("username");
String pass = [Link]("password");

if ("admin".equals(user) && "1234".equals(pass)) {


HttpSession session = [Link]();
[Link]("loggedUser", user);
[Link]("dashboard"); // Go to dashboard
} else {
[Link]("[Link]?error=1");
}
}
}

// [Link] — reads from session


@WebServlet("/dashboard")
public class DashboardServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = [Link](false);
if (session == null || [Link]("loggedUser") == null) {
[Link]("[Link]"); // Not logged in
return;
}
String user = (String) [Link]("loggedUser");
[Link]("text/html");
[Link]().println("<h1>Welcome, " + user + "!</h1>");
}
}

QUICK REFERENCE CHEATSHEET

Topic Key Points to Remember

JLabel / ImageIcon Displays text or image; use [Link] for alignment

JTextField Single-line input; getText(), setText(), setEditable()

JButton / JCheckBox / JRadioButton


JButton=action; JCheckBox=multi-select; JRadioButton=single (use ButtonGroup)

JTabbedPane addTab(title, component); container for multiple panels

JScrollPane Wrap JList, JTable, JTextArea to add scrollbars

JList Multi-select list; getSelectedValue(), setSelectionMode()

JComboBox Drop-down; single select; getSelectedItem()

JTree Hierarchical; DefaultMutableTreeNode; TreeSelectionListener

JTable Rows/columns; String[] cols + Object[][] data; wrap in JScrollPane

Web 1.0 → 3.0 Static HTML → Dynamic (Servlets) → AJAX → AI/React

CGI problems New process per request; slow; platform-dependent; hard to scale

Servlet advantages Threads (not processes); Java = platform-independent; fast; secure

Servlet lifecycle init() once → service() per request → destroy() once

GET vs POST GET=visible in URL, retrieve data; POST=hidden, submit data

doGet() Override to handle GET; read params with [Link]()

doPost() Override to handle POST; typically for form submissions

Cookies Client-side; ~4KB; new Cookie(k,v); setMaxAge(); addCookie()

HttpSession Server-side; setAttribute/getAttribute; invalidate() on logout


Session security Prefer session for sensitive data; cookies can be stolen

JSESSIONID Session ID stored as cookie in browser to track server session

You might also like