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

AdvancedJava Complete Solutions

This document provides a comprehensive guide for the MCA Advanced Java Term End Examination at MIT World Peace University, including model answers and concept teaching for various topics. It covers Java Swing GUI with JDBC for database operations, session management using cookies in servlets, and client-server socket communication in Java. Each section includes detailed solutions, code examples, and key concepts to aid in understanding the material.

Uploaded by

ayushwhiskey1
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)
4 views24 pages

AdvancedJava Complete Solutions

This document provides a comprehensive guide for the MCA Advanced Java Term End Examination at MIT World Peace University, including model answers and concept teaching for various topics. It covers Java Swing GUI with JDBC for database operations, session management using cookies in servlets, and client-server socket communication in Java. Each section includes detailed solutions, code examples, and key concepts to aid in understanding the material.

Uploaded by

ayushwhiskey1
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

MIT World Peace University, Pune

MCA7PM07A – Advanced Java


Term End Examination – May/June 2024
Complete Solutions + Full Concept Teaching Guide

Program FYMCA – Semester II


Max Marks 40 (Answer any 5 × 8 marks each)
Duration 1 Hour 30 Minutes
Question Paper ID 035597
Document Purpose Model Answers + Concept Teaching for Each Question

How to use this document:


• Each question has a SOLUTION section (write this in exam) and a CONCEPT TEACHING
section (understand this)
• Code is formatted in monospace font for easy reading
• Key concepts are highlighted with notes
• All 7 questions are solved even though only 5 need to be answered
QUESTION 1 (8 Marks) – GUI for SALES Table with JDBC
Topic: Java Swing GUI + JDBC Database Operations

SOLUTION – Complete Java Program


The program creates a Swing GUI for the SALES table and performs all required database operations.

Part A – Full Java Program ([Link])


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

public class SalesGUI extends JFrame implements ActionListener {

// Text fields for SALES table columns


JTextField tfQNum, tfQAmt, tfPONum, tfSupName;
JTextField tfGST, tfPayAmt, tfOrderStatus;
JButton btnInsert, btnTop10, btnSuppliers, btnLatePayment;
JTextArea taOutput;
Connection con;

// Database connection details


static final String URL = "jdbc:mysql://localhost:3306/salesdb";
static final String USER = "root";
static final String PASS = "password";

public SalesGUI() {
setTitle("SALES Management System");
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// ---------- INPUT PANEL (NORTH) ----------


JPanel inputPanel = new JPanel(new GridLayout(4, 4, 5, 5));
[Link]([Link]("SALES Table Fields"));

[Link](new JLabel("Quotation Number:"));


tfQNum = new JTextField(); [Link](tfQNum);

[Link](new JLabel("Quotation Amount:"));


tfQAmt = new JTextField(); [Link](tfQAmt);

[Link](new JLabel("Purchase Order Number:"));


tfPONum = new JTextField(); [Link](tfPONum);

[Link](new JLabel("Supplier Name:"));


tfSupName = new JTextField(); [Link](tfSupName);

[Link](new JLabel("GST Number:"));


tfGST = new JTextField(); [Link](tfGST);

[Link](new JLabel("Payment Amount:"));


tfPayAmt = new JTextField(); [Link](tfPayAmt);
[Link](new JLabel("Order Status:"));
tfOrderStatus = new JTextField(); [Link](tfOrderStatus);

add(inputPanel, [Link]);

// ---------- BUTTON PANEL (CENTER-TOP) ----------


JPanel btnPanel = new JPanel(new FlowLayout());
btnInsert = new JButton("Insert Data");
btnTop10 = new JButton("Top 10 Purchase Orders");
btnSuppliers = new JButton("List All Suppliers");
btnLatePayment = new JButton("Late Payment Suppliers");

[Link](this);
[Link](this);
[Link](this);
[Link](this);

[Link](btnInsert);
[Link](btnTop10);
[Link](btnSuppliers);
[Link](btnLatePayment);
add(btnPanel, [Link]);

// ---------- OUTPUT AREA (SOUTH) ----------


taOutput = new JTextArea(10, 60);
[Link](false);
[Link](new Font("Monospaced", [Link], 12));
add(new JScrollPane(taOutput), [Link]);

connectDB();
setVisible(true);
}

// ---------- DATABASE CONNECTION ----------


void connectDB() {
try {
[Link]("[Link]");
con = [Link](URL, USER, PASS);
[Link]("Database connected successfully!");
} catch (Exception e) {
[Link]("Connection failed: " + [Link]());
}
}

// ---------- ACTION LISTENER ----------


public void actionPerformed(ActionEvent e) {
if ([Link]() == btnInsert) insertData();
else if ([Link]() == btnTop10) showTop10();
else if ([Link]() == btnSuppliers) listSuppliers();
else if ([Link]() == btnLatePayment) latePaymentSuppliers();
}

// ---------- (a) INSERT DATA ----------


void insertData() {
String sql = "INSERT INTO SALES (Quotation_Number, Quotation_Amount, " +
"Purchase_Order_Number, Supplier_Name, GST_Number, " +
"Payment_Amount, Order_Status) VALUES (?,?,?,?,?,?,?)";
try {
PreparedStatement ps = [Link](sql);
[Link](1, [Link]());
[Link](2, [Link]([Link]()));
[Link](3, [Link]());
[Link](4, [Link]());
[Link](5, [Link]());
[Link](6, [Link]([Link]()));
[Link](7, [Link]());
[Link]();
[Link]("Data inserted successfully!");
} catch (Exception ex) {
[Link]("Insert Error: " + [Link]());
}
}

// ---------- (b) TOP 10 PURCHASE ORDERS BY HIGHEST PAYMENT ----------


void showTop10() {
String sql = "SELECT Purchase_Order_Number, Supplier_Name, Payment_Amount " +
"FROM SALES ORDER BY Payment_Amount DESC LIMIT 10";
try {
Statement st = [Link]();
ResultSet rs = [Link](sql);
StringBuilder sb = new StringBuilder();
[Link]("Top 10 Purchase Orders by Payment Amount:\n");
[Link]("--------------------------------------------\n");
int rank = 1;
while ([Link]()) {
[Link](rank++ + ". PO: " + [Link](1)
+ " Supplier: " + [Link](2)
+ " Amount: " + [Link](3) + "\n");
}
[Link]([Link]());
} catch (Exception ex) {
[Link]("Query Error: " + [Link]());
}
}

// ---------- (c) LIST ALL SUPPLIERS ----------


void listSuppliers() {
String sql = "SELECT DISTINCT Supplier_Name, GST_Number FROM SALES";
try {
Statement st = [Link]();
ResultSet rs = [Link](sql);
StringBuilder sb = new StringBuilder("All Suppliers:\n");
[Link]("--------------------------------------------\n");
while ([Link]()) {
[Link]("Supplier: " + [Link](1)
+ " GST: " + [Link](2) + "\n");
}
[Link]([Link]());
} catch (Exception ex) {
[Link]("Query Error: " + [Link]());
}
}

// ---------- (d) SUPPLIERS WITH LATE PAYMENT ----------


void latePaymentSuppliers() {
// Order_Status = 'Late' means payment is due due to late delivery
String sql = "SELECT Supplier_Name, Purchase_Order_Number, Payment_Amount " +
"FROM SALES WHERE Order_Status = 'Late'";
try {
Statement st = [Link]();
ResultSet rs = [Link](sql);
StringBuilder sb = new StringBuilder(
"Suppliers with Late Payment (Late Order Delivery):\n");
[Link]("--------------------------------------------\n");
while ([Link]()) {
[Link]("Supplier: " + [Link](1)
+ " PO#: " + [Link](2)
+ " Payment Due: " + [Link](3) + "\n");
}
[Link]([Link]());
} catch (Exception ex) {
[Link]("Query Error: " + [Link]());
}
}

public static void main(String[] args) {


new SalesGUI();
}
}

SQL – Create SALES Table


CREATE TABLE SALES (
Quotation_Number VARCHAR(20) PRIMARY KEY,
Quotation_Amount DECIMAL(12,2),
Purchase_Order_Number VARCHAR(20),
Supplier_Name VARCHAR(100),
GST_Number VARCHAR(20),
Payment_Amount DECIMAL(12,2),
Order_Status VARCHAR(20) -- 'Delivered', 'Pending', 'Late'
);

CONCEPT TEACHING – JDBC & Swing


What is JDBC?
JDBC (Java Database Connectivity) is an API that enables Java programs to connect and execute SQL
queries on databases like MySQL, Oracle, PostgreSQL etc.
JDBC 4-Step Process:
1. Load Driver: [Link]("[Link]")
2. Get Connection: [Link](url, user, pass)
3. Create Statement: [Link]() OR prepareStatement()
4. Execute Query: executeQuery() for SELECT, executeUpdate() for INSERT/UPDATE/DELETE

Statement vs PreparedStatement
Statement PreparedStatement
Used for static SQL Used for dynamic SQL with parameters
No parameters Uses ? as placeholders
Less secure (SQL injection risk) More secure (prevents SQL injection)
Slower for repeated queries Faster due to precompilation

Key Java Swing Components Used


• JFrame – Main window container
• JPanel – Sub-container for grouping components
• JTextField – Single-line text input
• JButton – Clickable button
• JTextArea – Multi-line output area
• JScrollPane – Adds scrollbar to components
• GridLayout – Arranges components in rows/columns
• BorderLayout – Divides window into NORTH, SOUTH, EAST, WEST, CENTER
📌 Remember: Always use PreparedStatement to prevent SQL Injection attacks in real applications.
QUESTION 2 (8 Marks) – Session Management & Cookies in
Servlet
Topic: Servlet Session Management using Cookies

SOLUTION – Session Management in Servlet


What is Session Management?
HTTP is a stateless protocol – each request is independent and the server does not remember
previous requests. Session Management is a technique to maintain state (user data) across multiple
requests from the same user.

Types of Session Management in Servlet


5. Cookies
6. Hidden Form Fields
7. URL Rewriting
8. HttpSession Object

What is a Cookie?
A Cookie is a small piece of data (key-value pair) stored on the client's browser by the server. The
browser automatically sends cookies with every subsequent request to the same server.

Cookie Lifecycle – Create, Use, Delete


Step 1: Creating a Cookie
// [Link]
import [Link].*;
import [Link].*;
import [Link].*;

@WebServlet("/createCookie")
public class CreateCookieServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// Get username from form


String username = [Link]("username");

// Step 1: Create a Cookie object


Cookie userCookie = new Cookie("username", username);

// Step 2: Set cookie expiry time (in seconds)


// 60 * 60 * 24 = 86400 seconds = 1 day
[Link](60 * 60 * 24);

// Step 3: (Optional) Set cookie path


[Link]("/");

// Step 4: Add cookie to response


[Link](userCookie);

// Redirect or respond
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Welcome " + username + "!</h2>");
[Link]("<p>Cookie has been created and stored in your browser.</p>");
[Link]("<a href='readCookie'>Read Cookie</a>");
[Link]("</body></html>");
}
}

Step 2: Using (Reading) a Cookie


// [Link]
@WebServlet("/readCookie")
public class ReadCookieServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

// Retrieve all cookies from request


Cookie[] cookies = [Link]();
String username = "Guest"; // Default if no cookie found

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

[Link]("<html><body>");
[Link]("<h2>Hello, " + username + "! Your session is active.</h2>");
[Link]("<a href='deleteCookie'>Delete Cookie</a>");
[Link]("</body></html>");
}
}

Step 3: Deleting a Cookie


// [Link]
@WebServlet("/deleteCookie")
public class DeleteCookieServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// To delete a cookie: set same name, empty value, maxAge = 0


Cookie killCookie = new Cookie("username", "");
[Link](0); // 0 means delete immediately
[Link]("/");
[Link](killCookie);

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h2>Cookie deleted. You are logged out.</h2>");
[Link]("</body></html>");
}
}

CONCEPT TEACHING – Session Management Deep Dive


Cookie Methods – Quick Reference
Method Description
new Cookie(name, value) Creates a new cookie with name and value
setMaxAge(seconds) Sets expiry: 0=delete, -1=session only, positive=seconds
setPath(path) Sets the URL path where cookie is valid
setSecure(true) Cookie sent only over HTTPS
getName() Returns the cookie's name
getValue() Returns the cookie's value
[Link]() Returns all cookies as Cookie[] array
[Link](cookie) Adds cookie to the response
📌 Cookies are stored on CLIENT side. Use HttpSession (server-side) for sensitive data like user ID,
account balance etc.
QUESTION 3 (8 Marks) – Java Socket Programming
Topic: Client-Server Socket Communication in Java

SOLUTION
Part (a) – Client Program (Sends file name extension to server)
// [Link]
import [Link].*;
import [Link].*;

public class FileClient {


public static void main(String[] args) throws Exception {

// Step 1: Connect to server at localhost:8080


Socket socket = new Socket("localhost", 8080);
[Link]("Connected to server at port 8080");

// Step 2: Streams for communication


BufferedReader userInput =
new BufferedReader(new InputStreamReader([Link]));
PrintWriter toServer =
new PrintWriter([Link](), true);
BufferedReader fromServer =
new BufferedReader(new InputStreamReader([Link]()));

// Step 3: Ask user to enter filename with extension


[Link]("Enter file name (e.g. [Link], [Link]): ");
String fileName = [Link]();

// Step 4: Send file name to server


[Link](fileName);

// Step 5: Read server's response


String serverResponse = [Link]();
[Link]("Server Response: " + serverResponse);

// Step 6: If file found, read and display its contents


if ([Link]("FILE_FOUND")) {
[Link]("\n--- File Contents ---");
String line;
while ((line = [Link]()) != null
&& ![Link]("END_OF_FILE")) {
[Link](line);
}
[Link]("--- End of File ---");
}

[Link]();
[Link]("Connection closed.");
}
}

Part (b) – Server Program (Accepts filename, checks existence, sends contents)
// [Link]
import [Link].*;
import [Link].*;
public class FileServer {
public static void main(String[] args) throws Exception {

// Step 1: Create server socket listening on port 8080


ServerSocket serverSocket = new ServerSocket(8080);
[Link]("Server started. Waiting for client on port 8080...");

while (true) { // Keep server running for multiple clients


// Step 2: Accept incoming client connection
Socket clientSocket = [Link]();
[Link]("Client connected: " +
[Link]().getHostAddress());

// Step 3: Setup I/O streams


BufferedReader fromClient =
new BufferedReader(new InputStreamReader([Link]()));
PrintWriter toClient =
new PrintWriter([Link](), true);

// Step 4: Read file name sent by client


String fileName = [Link]();
[Link]("Client requested file: " + fileName);

// Step 5: Validate file extension


String ext = [Link]([Link]('.') + 1)
.toLowerCase();

if (![Link]("txt") && ![Link]("doc")) {


[Link]("ERROR: Only .txt and .doc files are supported.");
[Link]();
continue;
}

// Step 6: Check if file exists


File file = new File(fileName);
if (![Link]()) {
[Link]("FILE_NOT_FOUND: " + fileName +
" does not exist on server.");
} else {
[Link]("FILE_FOUND: " + fileName +
" exists. Sending contents...");

// Step 7: Read and send file contents line by line


BufferedReader fileReader =
new BufferedReader(new FileReader(file));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
[Link]("END_OF_FILE"); // Sentinel value
}

[Link]();
[Link]("Response sent. Client disconnected.");
}
}
}
CONCEPT TEACHING – Socket Programming
How Socket Communication Works
• A Socket is one endpoint of a two-way communication link between two programs running on a
network.
• ServerSocket: Binds to a port and WAITS for incoming connections.
• Socket (Client): Initiates a connection to the server's IP and port.
• Once connected, both sides get InputStream (to read) and OutputStream (to write).

Key Classes
Class Purpose
ServerSocket(port) SERVER: Listens for connections on given port
[Link]() SERVER: Blocks until client connects, returns Socket
new Socket(host, port) CLIENT: Connects to server at given host:port
[Link]() Read data coming IN from the other side
[Link]() Write data going OUT to the other side
PrintWriter(out, true) true = auto-flush after every println()
[Link]() Closes the connection
📌 Run the Server FIRST, then run the Client. Server must be running before the Client tries to connect.
QUESTION 4 (8 Marks) – Spring Framework Architecture
Topic: Spring Framework Overview and Architecture

SOLUTION
What is Spring Framework?
Spring Framework is an open-source, lightweight application framework for Java. It provides
comprehensive infrastructure support for developing Java enterprise applications. Spring simplifies
Java development through:
• Dependency Injection (DI) / Inversion of Control (IoC)
• Aspect-Oriented Programming (AOP)
• Easy integration with frameworks like Hibernate, JPA, Struts
• Modules for Web MVC, Security, Data, Testing, etc.

Key Principles of Spring


1. Inversion of Control (IoC):
In traditional programming, the programmer creates objects. In IoC, the Spring container creates and
manages objects (Beans). You surrender control to the framework — hence 'Inversion' of Control.
2. Dependency Injection (DI):
Instead of a class creating its own dependencies, Spring injects them. This promotes loose coupling.
// Without DI (tightly coupled)
class OrderService {
PaymentService ps = new PaymentService(); // creates itself
}

// With DI (loosely coupled) – Spring injects it


class OrderService {
@Autowired
PaymentService ps; // Spring injects this automatically
}

Spring Framework Architecture – 7 Modules


The Spring Framework is organized as a stack of modules. Each module is independent and can be
used separately.
Module / Layer Description
Core Container The foundation. Provides IoC/DI. BeanFactory and
ApplicationContext manage beans.
AOP Module Aspect-Oriented Programming. Adds cross-cutting concerns
(logging, security, transactions) without modifying business code.
Data Access / Integration Simplifies JDBC, supports ORM (Hibernate, JPA), Transaction
management.
Web (MVC) Module Full web framework. DispatcherServlet handles HTTP requests.
Supports REST APIs.
Spring Security Authentication and authorization. Protects web apps and REST
APIs.
Spring Test Supports JUnit and TestNG testing of Spring components.
Spring Boot Auto-configuration layer. Makes Spring apps runnable without XML
config.

Spring Bean – Simple Example


// 1. Create a Bean (POJO)
public class HelloBean {
private String message;
public void setMessage(String msg) { [Link] = msg; }
public void printMessage() { [Link](message); }
}

// 2. Spring XML Configuration ([Link])


<bean id="helloBean" class="HelloBean">
<property name="message" value="Hello from Spring!"/>
</bean>

// 3. Main class – Spring container creates the bean


ApplicationContext ctx =
new ClassPathXmlApplicationContext("[Link]");
HelloBean bean = (HelloBean) [Link]("helloBean");
[Link](); // Output: Hello from Spring!
📌 Spring Core = IoC Container. It creates beans, wires dependencies, and manages their lifecycle.
QUESTION 5 (8 Marks) – Voter Eligibility Servlet
(RequestDispatcher)
Topic: HTML Form + Servlet using forward() and include() methods

SOLUTION
File 1: [Link] (Voter Eligibility Form)
<!DOCTYPE html>
<html>
<head>
<title>Voter Eligibility Check</title>
<style>
body { font-family: Arial; background: #f0f0f0; }
.form-box { background: #4a4a6a; color: white; padding: 20px;
width: 300px; margin: 100px auto; border-radius: 8px; }
input { width: 100%; padding: 6px; margin: 8px 0; box-sizing: border-box; }
button { padding: 8px 20px; margin-right: 10px; cursor: pointer; }
</style>
</head>
<body>
<div class='form-box'>
<h2>Voter Eligibility Check</h2>
<form action='VoterServlet' method='post'>
<label>Name:</label>
<input type='text' name='name' required />
<label>Age:</label>
<input type='number' name='age' required />
<button type='submit'>Check</button>
<button type='reset'>Reset</button>
</form>
</div>
</body>
</html>

File 2: [Link] (Main Servlet with RequestDispatcher)


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

@WebServlet("/VoterServlet")
public class VoterServlet extends HttpServlet {

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// Get form parameters


String name = [Link]("name");
int age = [Link]([Link]("age"));

// Include the header at the top of the page


// include() method: includes content from another resource
// The included page's output is added to the CURRENT response
RequestDispatcher rdHeader =
[Link]("[Link]");
[Link](request, response);
// Set result as request attribute
[Link]("personName", name);
[Link]("age", age);

// Decide which page to forward to based on age


// forward() method: COMPLETELY transfers control to another resource
// The CURRENT servlet stops processing
if (age >= 18) {
[Link]("message",
"Hello " + name + ", you are eligible for voting.");
RequestDispatcher rd =
[Link]("[Link]");
[Link](request, response);
} else {
[Link]("message",
"Hello " + name + ", you are not eligible for voting.");
RequestDispatcher rd =
[Link]("[Link]");
[Link](request, response);
}
}
}

File 3: [Link]
<%@ page language="java" contentType="text/html" %>
<html><body>
<div style='color:green; font-size:20px; text-align:center; margin:50px;'>
<h2><%= [Link]("message") %></h2>
<p>You can register to vote at your nearest election office.</p>
<a href='[Link]'>Go Back</a>
</div>
</body></html>

File 4: [Link]
<%@ page language="java" contentType="text/html" %>
<html><body>
<div style='color:red; font-size:20px; text-align:center; margin:50px;'>
<h2><%= [Link]("message") %></h2>
<p>You must be at least 18 years old to vote.</p>
<a href='[Link]'>Go Back</a>
</div>
</body></html>

CONCEPT TEACHING – RequestDispatcher


forward() vs include() – Key Difference
forward(request, response) include(request, response)
Transfers complete control to another resource Includes another resource's output in current
response
Current servlet STOPS executing Current servlet CONTINUES after include
URL bar stays same (server-side redirect) URL bar stays same
Used for final response page (navigation) Used for reusable headers/footers
Cannot write to response before forward() Can write before and after include()
📌 [Link]() passes data to the forwarded/included page. Use [Link]() in the
JSP to retrieve it.
QUESTION 6 (8 Marks) – JSP Directive Elements
Topic: JSP Directives – page, include, taglib

SOLUTION
What are JSP Directives?
JSP Directives are special instructions to the JSP container (like Tomcat) that tell it how to process the
JSP page during TRANSLATION (conversion of JSP to Servlet). They do NOT produce any output in
the response.
Syntax: <%@ directive attribute="value" %>

There are 3 types of JSP Directives:


9. page directive
10. include directive
11. taglib directive

1. page Directive
The page directive defines page-level settings for the JSP. It configures attributes like language,
content type, imports, session, error handling etc.
Syntax: <%@ page attribute="value" %>
Important Attributes of page Directive:
Attribute Example Purpose
language language="java" Scripting language (always java)
contentType contentType="text/html" MIME type of the response
import import="[Link].*" Import Java packages (like import
in Java)
session session="true" Whether HTTP session is enabled
(default: true)
errorPage errorPage="[Link]" Page to redirect to on exception
isErrorPage isErrorPage="true" Marks this as an error handling
page
buffer buffer="8kb" Size of output buffer
isThreadSafe isThreadSafe="true" Whether JSP is thread safe

Example of page directive:


<%@ page language="java"
contentType="text/html; charset=UTF-8"
import="[Link], [Link].*"
session="true"
errorPage="[Link]" %>
2. include Directive
The include directive is used to include content from another file (JSP, HTML, text) into the current JSP
at TRANSLATION TIME (static include). The included file becomes part of the current JSP before it is
compiled.
Syntax: <%@ include file="[Link]" %>
Example:
<!-- [Link] -->
<html>
<body>
<%@ include file="[Link]" %> <!-- Includes header at compile time -->

<h2>Welcome to the main page!</h2>


<p>Today is: <%= new [Link]() %></p>

<%@ include file="[Link]" %> <!-- Includes footer -->


</body>
</html>

<!-- [Link] -->


<div style='background:blue; color:white; padding:10px;'>
<h1>My Website Header</h1>
</div>

include directive (Static Include) <jsp:include> (Dynamic Include)


Included at TRANSLATION time Included at REQUEST time (runtime)
File content is merged into JSP before compile File is processed separately at runtime
Faster (one compiled file) Slightly slower but more flexible
Cannot pass parameters Can pass parameters using <jsp:param>
Use for static content (header/footer) Use for dynamic content

3. taglib Directive
The taglib directive is used to include a Tag Library in the JSP page. A Tag Library is a collection of
custom JSP tags that extend the capabilities of HTML. The most popular is JSTL (JSP Standard Tag
Library).
Syntax: <%@ taglib uri="URI" prefix="prefix" %>
Example – Using JSTL Core Library:
<%@ taglib uri="[Link] prefix="c" %>

<html>
<body>
<h2>Student List</h2>

<!-- c:forEach iterates over a collection (like for-each loop) -->


<c:forEach var="student" items="${studentList}">
<p>${[Link]} - Age: ${[Link]}</p>
</c:forEach>

<!-- c:if is a conditional tag -->


<c:if test="${age >= 18}">
<p>You are eligible to vote.</p>
</c:if>
<!-- c:out safely prints a value (escapes HTML) -->
<c:out value="${username}" />

</body>
</html>
📌 The prefix (e.g. 'c' for core, 'fmt' for formatting) is used as a namespace to identify the tag library's
tags.

CONCEPT TEACHING – JSP Summary


• page directive: Configures the JSP page settings (language, imports, session, error)
• include directive: Statically merges another file into JSP at translation time
• taglib directive: Enables use of custom/JSTL tags in JSP
📌 All directives use <%@ ... %> syntax and appear at the TOP of the JSP file. They have NO output in
the browser.
QUESTION 7 (8 Marks) – GET vs POST + MVC Architecture
Topic: HTTP Methods and MVC Design Pattern

SOLUTION – Part (a): Difference Between GET and POST Methods


Feature GET Method POST Method
Data Location Appended to URL as query Sent in HTTP request body
string (?name=value) (not visible in URL)
Visibility Data visible in URL / browser Data hidden from URL (more
history private)
Security Less secure – data exposed in More secure – data in body
URL
Data Size Limit Limited (~2048 characters) No practical limit
Bookmarkable Yes – URL contains all No – cannot bookmark POST
parameters requests
Idempotent Yes – same request = same No – repeating may have side
result effects
Caching Responses can be cached Responses NOT cached
Use Case Fetching data, search queries, Submitting forms, login, file
navigation upload
Browser Back Safe to go back (no re-submit) Browser warns about re-
submitting
Servlet Method doGet(request, response) doPost(request, response)

Example of GET vs POST in HTML forms:


<!-- GET Form: Data visible in URL -->
<form action='SearchServlet' method='GET'>
<input type='text' name='query' placeholder='Search...' />
<input type='submit' value='Search' />
</form>
<!-- URL becomes: SearchServlet?query=java -->

<!-- POST Form: Data hidden in body -->


<form action='LoginServlet' method='POST'>
<input type='text' name='username' />
<input type='password' name='password' />
<input type='submit' value='Login' />
</form>
<!-- URL remains: LoginServlet (password not visible) -->

SOLUTION – Part (b): MVC Architecture


What is MVC?
MVC (Model-View-Controller) is a software design pattern that separates an application into 3
interconnected components. This separation makes the application easier to manage, test, and
maintain.

The 3 Components of MVC


Component In Java Web App Responsibility
MODEL Java Beans / POJO / Represents DATA and BUSINESS LOGIC. Handles
DAO database operations. Independent of UI.
VIEW JSP / HTML pages Represents the USER INTERFACE. Displays data
to the user. No business logic.
CONTROLLER Servlet (e.g. HANDLES USER REQUESTS. Calls Model, selects
DispatcherServlet) View, passes data between them.

MVC Flow – Step by Step


12. User sends a REQUEST from browser (e.g. submits a form)
13. CONTROLLER (Servlet) receives and processes the request
14. Controller calls the MODEL (Java Bean/DAO) to fetch/update data
15. MODEL returns data to Controller
16. Controller sets data as attributes and FORWARDS to VIEW (JSP)
17. VIEW (JSP) renders the data and sends RESPONSE to browser

MVC Example – Student Record


// MODEL: [Link] (POJO)
public class Student {
private int id;
private String name;
private int age;
// Getters and Setters...
}

// MODEL: [Link] (Data Access Object)


public class StudentDAO {
public List<Student> getAllStudents() {
// JDBC code to fetch from DB
List<Student> list = new ArrayList<>();
// ... DB code ...
return list;
}
}

// CONTROLLER: [Link]
@WebServlet("/students")
public class StudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest req,
HttpServletResponse res) throws Exception {
// 1. Call Model
StudentDAO dao = new StudentDAO();
List<Student> students = [Link]();

// 2. Pass data to View


[Link]("studentList", students);
// 3. Forward to View (JSP)
[Link]("[Link]")
.forward(req, res);
}
}

<!-- VIEW: [Link] -->


<%@ taglib uri="[Link] prefix="c" %>
<html><body>
<h2>Student List</h2>
<c:forEach var="s" items="${studentList}">
<p>${[Link]} - ${[Link]} - Age: ${[Link]}</p>
</c:forEach>
</body></html>

Advantages of MVC Architecture


• Separation of Concerns: Each layer has ONE responsibility
• Easy Maintenance: Change UI without touching business logic
• Reusability: Same Model can be used by multiple Views
• Testability: Can unit-test Model and Controller independently
• Parallel Development: Team can work on Model, View, Controller simultaneously
📌 In Spring MVC, DispatcherServlet acts as the Front Controller – all requests go through it first.
QUICK REVISION CHEATSHEET
Use this for last-minute revision before the exam!

Topic Summary Table


Question Core Concept Key Points to Remember
Q1 – JDBC GUI Swing + JDBC + 4 steps: Load driver, Connect,
PreparedStatement Statement, Execute. Use
PreparedStatement for params.
Q2 – Cookies Session Management via Cookies Create: new Cookie() +
addCookie(). Delete:
setMaxAge(0). Read: getCookies()
+ loop.
Q3 – Sockets Client-Server Socket Server: [Link]().
Communication Client: new Socket(host, port). Use
streams to communicate.
Q4 – Spring IoC, DI, Spring Architecture 7 modules: Core, AOP, Data, Web,
Security, Test, Boot. IoC =
container creates beans.
Q5 – Servlet RD RequestDispatcher forward/include forward() = transfers control.
include() = includes output.
setAttribute/getAttribute for data.
Q6 – JSP 3 JSP Directives page = settings. include = merge
file. taglib = use JSTL. All use <
%@ %> syntax.
Q7 – HTTP Methods + MVC Pattern GET = visible URL. POST = hidden
GET/POST/MVC body. MVC = Model(data) +
View(UI) + Controller(logic).

Best of Luck in Your Exam!


Study each concept, understand the code flow, and practice writing programs by hand.

You might also like