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

AJ - Question Bank With Answer

The document provides a comprehensive overview of key concepts in Advanced Java Programming, focusing on Servlets and JSP (Java Server Pages). It covers topics such as the purpose and lifecycle of Servlets, advantages over CGI, web server roles, session tracking techniques, and the MVC architecture in JSP. Additionally, it includes practical examples and explanations of JSP scripting elements, directives, scopes, JavaMail API, and JavaBeans usage in JSP.

Uploaded by

rjfdfn8rjd
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 views7 pages

AJ - Question Bank With Answer

The document provides a comprehensive overview of key concepts in Advanced Java Programming, focusing on Servlets and JSP (Java Server Pages). It covers topics such as the purpose and lifecycle of Servlets, advantages over CGI, web server roles, session tracking techniques, and the MVC architecture in JSP. Additionally, it includes practical examples and explanations of JSP scripting elements, directives, scopes, JavaMail API, and JavaBeans usage in JSP.

Uploaded by

rjfdfn8rjd
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/ 7

UNIT – I

Important questions with answers from Unit-I of Advanced Java Programming:

1. What is a Servlet? Explain its purpose in web applications.


Answer:
A Servlet is a Java program that runs on a web server and handles client requests to generate dynamic web content. It is
part of Java EE (Java Enterprise Edition) and is used for web application development.
Purpose in Web Applications:
 Processes HTTP requests (GET, POST, etc.).
 Generates dynamic content (HTML, JSON, etc.).
 Handles user interactions with web applications.
 Provides better performance compared to CGI (Common Gateway Interface).

2. Describe the lifecycle of a Servlet with an example.


Answer:
The lifecycle of a Servlet is managed by the web container and consists of three main phases:
1. Initialization (init())
o The servlet is loaded and initialized when the web server starts or on the first request.
o Example:
public void init(ServletConfig config) throws ServletException {
// Initialization code
}
2. Request Handling (service())
o This method is called for each client request and determines whether doGet() or doPost() should be executed.
o Example:
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Welcome to Servlets</h1>");
}
3. Destruction (destroy())
o When the servlet is no longer needed, the destroy() method is called to release resources.
o Example:
public void destroy() {
// Cleanup code
}

3. What are the key interfaces and classes in the Servlet API?
Answer:
Key Interfaces:
1. Servlet – The basic interface that every servlet must implement.
2. ServletRequest – Provides request data from the client.
3. ServletResponse – Allows the servlet to send a response to the client.
4. HttpServletRequest – Handles HTTP-specific request data.
5. HttpServletResponse – Handles HTTP-specific response data.
Key Classes:
1. GenericServlet – A general implementation of the Servlet interface.
2. HttpServlet – An abstract class used for handling HTTP requests.
4. What are the advantages of Servlets over CGI?
Answer:
Feature CGI (Common Gateway Interface) Servlets
Performance Slower (New process created for each request) Faster (Uses threads instead of processes)
Memory High (Multiple processes consume more Low (Threads share memory, reducing
Usage memory) overhead)
Scalability Poor (High load causes performance issues) High (Efficient request handling)
Security Limited Supports authentication and session tracking

5. What is a Web Server? Explain its role in serving web requests.


Answer:
A web server is a software or hardware that processes client requests and serves web pages using HTTP (HyperText
Transfer Protocol).
Role in Serving Web Requests:
1. Receives HTTP requests from web browsers.
2. Processes the request and forwards it to appropriate resources (HTML files, Servlets, etc.).
3. Sends the response (web pages or data) back to the client.
Examples of Web Servers:
 Apache HTTP Server – Open-source and widely used.
 Microsoft IIS – Web server from Microsoft.
 Lighttpd – Lightweight and efficient web server.

6. What is Servlet Chaining? Explain with examples.


Answer:
Servlet Chaining is the process of passing a request through multiple servlets before generating the final response.
Techniques of Servlet Chaining:
1. Forwarding a Request (forward())
o Passes control from one servlet to another without returning to the first servlet.
o Example:
RequestDispatcher rd = request.getRequestDispatcher("NextServlet");
rd.forward(request, response);
2. Including Output of Another Servlet (include())
o Includes the output of one servlet in the response of another servlet.
o Example:
RequestDispatcher rd = request.getRequestDispatcher("HeaderServlet");
rd.include(request, response);
7. What are Session Tracking techniques in Java?
Answer:
Session Tracking is used to maintain user state across multiple HTTP requests.
Techniques of Session Tracking:
1. Cookies
o Stores small data on the client-side browser.
o Example:
Cookie userCookie = new Cookie("username", "John");
response.addCookie(userCookie);
2. URL Rewriting
o Appends session ID to the URL.
o Example:
String url = response.encodeURL("dashboard.jsp");
3. Hidden Form Fields
o Stores session data in hidden HTML form fields.
o Example: html
<input type="hidden" name="sessionID" value="12345">
4. HttpSession API (Preferred Method)
o Stores session data on the server.
o Example:
HttpSession session = request.getSession();
session.setAttribute("username", "John");

8. What is JDBC? How does JDBC work in Servlets?


Answer:
JDBC (Java Database Connectivity) is an API that allows Java programs to connect to databases and execute SQL
queries.
How JDBC Works in Servlets:
1. Establish Connection – Connects to the database.
2. Execute Queries – Retrieves or updates data using SQL.
3. Process Results – Displays or processes the results.
Example: Servlet with JDBC
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class JDBCServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost: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>");
}
con.close();
} catch (Exception e) {
out.println("Database Error");
}
}
}

9. How does an Applet communicate with a Servlet?


Answer:
An Applet can send requests to a Servlet using URLConnection or HttpURLConnection.
Example: Applet Sending Data to Servlet
URL url = new URL("http://localhost:8080/MyServlet");
URLConnection con = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

10. Difference between Applet and Servlet


Feature Applet Servlet
Execution Runs in a browser Runs on a server
Purpose Client-side UI Server-side processing
Security Restricted by sandbox Can access server resources
Example Java game in a Login handling servlet
browser

UNIT – II
Important questions with answers from Unit-II of Advanced Java Programming (JSP – Java Server Pages).

1. What is JSP? Explain its purpose in web applications.


Answer:
JSP (Java Server Pages) is a technology that allows web developers to create dynamic web pages using Java embedded
in HTML. It is part of the Java EE platform and acts as an extension to Servlets.
Purpose in Web Applications:
 Allows mixing Java code with HTML using JSP scripting elements.
 Simplifies web development by reducing Java code compared to Servlets.
 Used to retrieve and display database records, collect user input, and manage sessions.
 Supports MVC (Model-View-Controller) architecture for cleaner web application design.

2. Explain the JSP Life Cycle with steps.


Answer:
The JSP life cycle involves four major stages:
1. Compilation
o When the JSP page is first requested, it is converted into a Servlet.
o The steps include parsing, conversion to Servlet, and compilation.
2. Initialization (jspInit())
o Called when the JSP is loaded for the first time.
o Used for resource initialization, such as opening database connections.
public void jspInit() {
// Initialization code
}
3. Execution (_jspService())
o Called each time a request is sent to the JSP.
o Generates dynamic content.
void _jspService(HttpServletRequest request, HttpServletResponse response) {
// Code to generate response
}
4. Cleanup (jspDestroy())
o Called before the JSP is removed from memory.
o Used to release resources like database connections.
public void jspDestroy() {
// Cleanup code
}

3. Explain the MVC Architecture in JSP.


Answer:
MVC (Model-View-Controller) is a design pattern that separates the application into three layers:
1. Model (Data Layer)
o Manages business logic and database operations.
o Example: User.java (JavaBean for storing user data).
2. View (Presentation Layer)
o JSP pages for displaying user interface.
o Example: login.jsp (HTML form for user login).
3. Controller (Logic Layer)
o Handles user requests and directs them to appropriate JSP pages.
o Example: LoginController.java (Servlet that processes login requests).
✅ Advantages of MVC in JSP:
 Separation of concerns – easier to maintain.
 Better reusability of components.
 Scalable – multiple developers can work on different layers.

4. What are JSP Scripting Elements? Explain with examples.


Answer:
JSP scripting elements allow embedding Java code within JSP files.
Scripting Element Description Example
Declaration (<%! ... Defines variables/methods outside <%! int count = 0; %>
%>) _jspService()
Scriptlet (<% ... %>) Executes Java code inside _jspService() <% out.println("Hello JSP!"); %>
Expression (<%= ... %>) Outputs values directly to the page <%= new Date() %>
✅ Example of Scriptlet:
jsp
<% int num1 = 5, num2 = 10; %>
Sum: <%= num1 + num2 %>
Output:
makefile
CopyEdit
Sum: 15

5. What are JSP Directives? Explain their types.


Answer:
JSP directives provide instructions to the JSP container on how to process the page.
✅ Types of JSP Directives:
1. Page Directive (<%@ page ... %>)
o Defines global page settings.
o Example:
jsp
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8" %>
2. Include Directive (<%@ include file="..." %>)
o Includes static content from another file at compile-time.
o Example:
jsp
<%@ include file="header.jsp" %>
3. Taglib Directive (<%@ taglib ... %>)
o Used for custom JSP tags from tag libraries (JSTL).
o Example:
jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

6. What are JSP Scopes? Explain with examples.


Answer:
JSP scopes define the visibility and lifetime of objects in a JSP page.
Scope Description Lifetime
Page Available within a single JSP page Until page execution
ends
Request Shared across multiple JSPs for one client request Until request is processed
Session Shared across multiple requests for the same user Until session expires
Applicatio Shared across all users and JSPs in the web application Until the server stops
n
✅ Example of Session Scope:
jsp
<% session.setAttribute("username", "JohnDoe"); %>

7. What is JavaMail API? How can you send an email using JSP?
Answer:
JavaMail API allows sending and receiving emails in Java applications.
✅ Steps to Send an Email in JSP:
1. Add JavaMail Library (mail.jar, activation.jar).
2. Set SMTP Properties (Gmail SMTP: smtp.gmail.com).
3. Authenticate Sender Email.
4. Compose and Send Email.
✅ JSP Code to Send Email:
jsp
<%@ page import="java.util.*, javax.mail.*, javax.mail.internet.*" %>
<%
String recipient = "[email protected]";
String sender = "[email protected]";
String host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");

Session session = Session.getInstance(props, new Authenticator() {


protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "your-password");
}
});

Message message = new MimeMessage(session);


message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject("Test Email");
message.setText("Hello, this is a test email from JSP!");

Transport.send(message);
out.println("Email Sent Successfully!");
%>

8. What is JavaBeans? How do you use JavaBeans in JSP?


Answer:
JavaBeans are reusable components in Java with getter and setter methods.
✅ JavaBean Example (User.java):
java
public class User {
private String name;

public String getName() { return name; }


public void setName(String name) { this.name = name; }
}
✅ Using JavaBean in JSP:
jsp
<jsp:useBean id="user" class="User" scope="session"/>
<jsp:setProperty name="user" property="name" value="John Doe"/>
<jsp:getProperty name="user" property="name"/>
Output:
John Doe

9. What are the different protocols used in JavaMail API?


Answer:
Protoco Purpose Port
l
SMTP Sending emails 25 (Default), 587 (TLS), 465 (SSL)
POP3 Receiving emails (downloads & 110 (Default), 995 (SSL)
deletes)
IMAP Receiving emails (keeps on server) 143 (Default), 993 (SSL)
✅ Example of Receiving Email using IMAP:
java
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "[email protected]", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);

You might also like