0% found this document useful (0 votes)
3 views19 pages

Java Q Unit4

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
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)
3 views19 pages

Java Q Unit4

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
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

Unit 4 Advanced Java & J2EE Page : 1

1. What are servlets?

Servlets are Java programs that run on a web server to handle client requests and generate dynamic web content.
They are mainly used to:
1. Process user requests from web browsers
2. Interact with databases
3. Generate dynamic web pages
4. Handle form data and sessions
2. List the drawbacks of CGI programs.
1. Slow performance – A new process is created for every client request.
2. High memory usage – Multiple processes consume more system resources.
3. Poor scalability – Performance decreases with many users.
4. Platform dependent – CGI programs may vary across operating systems.
5. Difficult session handling – Maintaining user sessions is not easy.
6. Less efficient – Communication between server and CGI process adds overhead.
7. Security risks – Improper CGI scripts can create security vulnerabilities.

3. List the advantages of servlet.


1. Better performance – Servlets use threads instead of creating a new process for each request.
2. Platform independent – Works on any system with JVM support.
3. Efficient and scalable – Can handle multiple requests simultaneously.
4. Persistent – Servlets remain in memory after loading, improving speed.
5. Secure – Provides better security compared to CGI programs.
6. Easy database connectivity – Easily connects with databases using JDBC.
7. Portable – Can run on different web servers and operating systems.
8. Reusable – Supports modular and reusable code.
4. With syntax write the purpose of getParameter() method.
Syntax : String value = [Link](String name);
• Retrieves the value of a form field or request parameter.
• Used to read user input submitted through HTML forms.
• Returns the parameter value as a String.
Example
String uname = [Link]("username");
Here:
• "username" is the form field name.
• The entered value is stored in uname.
5. What is the purpose of extending the GenericServlet class in t servlet, and what methods does it provide by
default?
Purpose of Extending GenericServlet
• Reduces the effort of implementing all methods of the Servlet interface.
• Provides a protocol-independent servlet class.
• Makes servlet programming easier and simpler.
• Allows developers to override only the required methods.
Methods Provided by GenericServlet by Default
init() Initializes the servlet
destroy() Destroys the servlet
service() Abstract method to handle requests
log() Writes log messages
6. Explain the role of the ServletRequest and ServletResponse objects in the service() method
ServletRequest
• Represents the client request sent to the servlet.
• Used to read request data from the client.
Functions
• Retrieves form data
• Reads request parameters and Gets client information
ServletResponse
Unit 4 Advanced Java & J2EE Page : 2
• Represents the response sent back to the client.
• Used to generate output for the browser.
Functions
• Sends HTML/text response
• Sets content type and Writes data to client

7. What is ServletConfig Interface? Mention any 2 methods


ServletConfig is used to supply initialization and configuration information to servlets, and methods like
getInitParameter() and getInitParameterNames() help access those parameters.
8. What is the purpose and significance of the getWriter() method in the context of generating an HTTP
response in a servlet?
In Java Servlet, the getWriter() method is used to obtain a PrintWriter object for sending character/text data in an
HTTP response to the client browser.
Syntax PrintWriter out = [Link]();
Purpose of getWriter()
• Sends text-based responses to the client.
• Used to generate dynamic web content such as HTML, plain text and XML
Significance
• Enables the servlet to write output directly to the browser.
• Used for displaying results, messages, and dynamically generated pages.
• Essential for creating HTTP responses in servlet applications.
9. ______________ interface declares life cycle methods for a servlet and ______________interface allows
servlets to get initialization parameters.
The Servlet interface declares the life cycle methods for a servlet.
The ServletConfig interface allows servlets to get initialization parameters.
10. What is the role of the getServletConfig() and getServletInfo() methods in the Servlet interface
1. getServletConfig()
ServletConfig config = getServletConfig();
Role
• Returns the ServletConfig object associated with the servlet.
• Used to access servlet initialization parameters and configuration information
2. getServletInfo()
public String getServletInfo()
Role
o Returns information about the servlet such as ( author, version, description)
11. Differentiate between the getInitParameter(String param) and getInitParameterNames() methods in the
ServletConfig interface
getInitParameter(String param) getInitParameterNames()
Returns the value of a specific initialization Returns names of all initialization parameters
parameter
Requires parameter name No argument required
Return type is string return type is enumeration
Access a single parameter values Access all parameter names

12. What the purpose and usage of the getAttribute(String attr) and setAttribute(String attr, Object val)
methods in the ServletContext interface
In Java Servlet, the getAttribute() and setAttribute() methods of the ServletContext interface are used to store and
retrieve shared data across the entire web application.
1. setAttribute(String attr, Object val)
[Link]("company", "ABC Ltd");
• Stores an object in the ServletContext.
• Makes data available to all servlets in the application.
Used for application-wide data sharing.
2. getAttribute(String attr)
Unit 4 Advanced Java & J2EE Page : 3
String name = (String) [Link]("company");
• Retrieves the object stored with the specified attribute name.
Used to access shared application data.
13. What is the purpose of the getParameterNames() and getParameterValues(String name) methods in the
ServletRequest interface.
1. getParameterNames()
• Returns the names of all request parameters.
• The parameter names are returned as an Enumeration object.
Used to access all form field names submitted by the client.
2. getParameterValues(String name)
• Returns all values associated with a given parameter name.
• Useful when multiple values are submitted for the same parameter.
Commonly used with: ( Checkboxes , Multi-select lists )
14. What is the usage of readLine(byte[] buffer, int offset, int size) method in the ServletInputStream class?.
In Java Servlet, the readLine(byte[] buffer, int offset, int size) method of the ServletInputStream class is used to read
a line of input data from the client request into a byte array.
Usage
• Reads one line of data at a time from the input stream.
• Stores the data in the specified byte array.
• Returns the number of bytes actually read.
15. What's the specific purpose of ServletOutputStream and ServletInputStream?
1. ServletInputStream
• Used to read binary data sent by the client in an HTTP request.
• Obtained from the request object.
Uses
• Reading uploaded files
• Reading binary form data
• Processing client request data
2. ServletOutputStream
• Used to send binary data from the servlet to the client.
• Obtained from the response object.
Uses
• Sending images, PDF files, audio, video, etc.
• Downloading files from server to browser
16. List classes that are provided in the [Link] package
HttpServlet :- Used to create HTTP servlets
Cookie :- Used to create and manage cookies
HttpSessionBindingEvent :- Provides session binding event information
HttpServletRequestWrapper:- Wraps request object
HttpServletResponseWrapper:- Wraps response object
17. Write the usage of any two methods described in the HttpServletResponse interface
1. sendRedirect()
[Link]("[Link]");
Usage
• Redirects the client to another resource, webpage, or URL.
• Sends a new request to the specified location.
2. addCookie()
Cookie c = new Cookie("user", "Rahul");
[Link](c);
Usage
• Adds a cookie to the HTTP response.
• Stores small information on the client browser.
18. What is Cookie? How it is helpful?
A cookie is a small piece of data stored in the user's browser by a web server.
It is used to store user-related information such as:
Unit 4 Advanced Java & J2EE Page : 4
• Login details
• User preferences
Usage :
1. Personalization – Stores user preferences and settings.
2. User identification – Recognizes returning users.
3. Improves user experience – Avoids repeated login or data entry.
19. Describe the significance of the valueBound and valueUnbound methods in the HttpSessionBindingListener
interface
valueBound()
• Invoked automatically when an object is added to a session using setAttribute().
• Used to perform actions when the object becomes part of the session.
valueUnbound()
• Invoked automatically when an object is removed from the session using removeAttribute() or when the
session expires.
• Used for cleanup operations or releasing resources.
20. What information can be stored in a cookie?
In HTTP Cookies, a cookie stores small pieces of information sent by a web server and saved in the user’s browser.
A cookie can store:
• User name or user ID
• Login status
• Recently visited pages
• Authentication information
21. What is the significance of the getSession( ) method of HttpServletRequest

In Java Servlet, the getSession() method of HttpServletRequest is used to obtain an HttpSession


object for maintaining user session information.
getSession()
• Creates a new session if one does not already exist.
• Returns the existing session if already available.
• Helps maintain client information across multiple requests.
Uses of Session
• Storing user login details
• Tracking user activities
• Maintaining shopping cart data
• Preserving user-specific data between pages
22. Write the purpose of next() and getString().
next()
• Moves the cursor to the next row in the ResultSet.
• Returns true if the next row exists, otherwise returns false.
Initially, the cursor is positioned before the first row.
next() is used to access rows one by one.
getString()
• Retrieves the value of a specified column as a String.
The column can be specified using:
• Column index
• Column name
23. List the parts of URL that is used in getConnection() method to establish connection.
The JDBC URL used in getConnection() contains:
• protocol,
• driver/subprotocol,
• host name,
• port number,
• and database name required to connect to the DBMS.
24. Write the purpose of setLoginTimeout() and getLoginTimeout()
In Java Database Connectivity (JDBC), setLoginTimeout() and getLoginTimeout() are methods of the DriverManager
class used to manage database connection timeout settings.
setLoginTimeout()
Unit 4 Advanced Java & J2EE Page : 5
• Sets the maximum time (in seconds) a driver waits while attempting to connect to the database.
• If the connection is not established within the specified time, an exception is thrown.
getLoginTimeout()
• Returns the current login timeout value set for database connections.
• The value is returned in seconds.
25. Write the purpose of forName() and createStatement().
forName()
• Loads and registers the JDBC driver into memory.
• Establishes communication between Java application and database driver.
[Link]() dynamically loads the driver class at runtime.
createStatement()
Statement stmt = [Link]();
• Creates a Statement object.
• Used to send SQL queries to the database.
The Statement object executes SQL commands like: SELECT ,INSERT ,UPDATE and DELETE
26.

27. What is the main purpose of the JDBC to ODBC (Type 1) driver?
The main purpose of the JDBC-ODBC Bridge Driver is to connect a Java application to a database through the ODBC
(Open Database Connectivity) interface.
It converts JDBC calls into ODBC calls, which are then understood by the database driver.
• Acts as a bridge between JDBC and ODBC
• Allows Java programs to access databases that support ODBC
• Requires ODBC driver installation on the client machine
• Platform dependent
28. Differentiate between Type 3 and Type 4 JDBC drivers. Which one is considered to be the fastest way to
communicate SQL queries to the DBMS?

Type 3 Driver Type 4 Driver


Network Protocol Driver Thin Driver / Native Protocol Driver
Uses middleware server Directly communicates with DBMS
Converts JDBC calls into DBMS-independent protocol Converts JDBC calls directly into database protocol
Slower due to extra network layer Faster
Platform independent Platform independent
More complex Easier
WebLogic Driver MySQL Connector/J, Oracle Thin Driver
29. What is the difference between the executeQuery() and executeUpdate() methods of a Statement object in
JDBC?

executeQuery()
Executes SELECT queries
Returns a ResultSet object
Used For retrieving data from database
SQL Commands used SELECT statements
Output is in the form of Table of records
executeUpdate()
Executes INSERT, UPDATE, DELETE queries
Returns an integer value
Used For modifying database records
SQL Commands used are INSERT, UPDATE, DELETE, CREATE, DROP
Output is in the form of Number of rows affected
30. Briefly explain what a ResultSet object represents in JDBC.
A ResultSet object in JDBC represents the data obtained from a database query and provides methods to access and
manipulate the retrieved records
1. Stores records retrieved from the database.
2. Allows Java programs to access and process query results row by row.
Unit 4 Advanced Java & J2EE Page : 6
31. What is the main advantage of using a PreparedStatement object over a Statement object in JDBC?
1. Prevents SQL Injection
• Uses placeholders (?) for dynamic values.
• Separates SQL code from user input, making queries safer.
2. Faster Execution
• SQL query is precompiled once and reused multiple times.
• Improves performance for repeated execution.
3. Easier Handling of Dynamic Values
• Uses methods like:
o setInt()
o setString()
o setDouble()
32. How do PreparedStatement objects handle dynamic values in SQL queries?
PreparedStatement handles dynamic values by using placeholders (?) and setter methods to safely insert values into
SQL queries.

Example :
PreparedStatement ps = [Link]("INSERT INTO student VALUES(?, ?, ?)");
Here, each ? represents a dynamic value.
Setting Dynamic Values
[Link](1, 101);
[Link](2, "Rahul");
[Link](3, 20);
33. What are the different parameters used by CallableStatement object?
CallableStatement uses the following types of parameters:
1. IN Parameter
o Used to pass values to the stored procedure.
2. OUT Parameter
o Used to return values from the stored procedure.
3. INOUT Parameter
o Used to pass values to the procedure and also return modified values.
34. How to Insert a Row into the ResultSet
In Java Database Connectivity (JDBC), inserting a row into a ResultSet is similar to updating a row. The updateXXX()
methods are used to specify the column and the value to be inserted, where XXX represents the data type such as
updateInt() or updateString(). These methods take two parameters: the column name or column number, and the new
value for that column. After setting the required values for one or more columns, the insertRow() method is called to
insert the new row into the ResultSet, which also updates the underlying database.

35. Why Savepoints are used in datatabase transaction?


Savepoints are used to create temporary checkpoints within a transaction so that part of the transaction can be
rolled back without rolling back the entire transaction.
If multiple SQL statements are executed and one fails, a savepoint allows rolling back only up to that point instead of
canceling the whole transaction.
36. How to batch sql statement into transaction statement?
Batching SQL statements into a transaction means executing multiple SQL queries together as a single unit of work.
Advantages
• Improves performance
• Reduces database calls
• Ensures data consistency using transactions
37. What are the methods supported by RowSetListener class?
The RowSetListener interface provides the following methods:
1. rowSetChanged(RowSetEvent event)
o Invoked when the entire RowSet changes.
2. rowChanged(RowSetEvent event)
o Invoked when a row in the RowSet is changed.
Unit 4 Advanced Java & J2EE Page : 7
3. cursorMoved(RowSetEvent event)
o Invoked when the cursor position changes.
38. What is JavaServerPages?
Java Server Pages (JSP) is a technology for developing Web pages that supports dynamic content. This helps
developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end
with %>.

39. List any four advantages of using JSP


1. Easy to develop – JSP allows embedding Java code directly into HTML.
2. Platform independent – Runs on any system with JVM support.
3. Better performance – JSP is converted into servlets and executes faster than CGI.
4. Reusable components – Supports JavaBeans and custom tags for code reuse.
40. List any four implicit Objects
request :- This is the HttpServletRequest object associated with the request.
response :- This is the HttpServletResponse object associated with the response to the client.
out :- This is the PrintWriter object used to send output to the client.
session :- This is the HttpSession object associated with the request.
application :- This is the ServletContext object associated with application context.
config :- This is the ServletConfig object associated with the page.
pageContext :- This encapsulates use of server-specific features like higher performance JspWriters.
page :- This is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
Exception :- The Exception object allows the exception data to be accessed by designated JSP.
41. What is the usage of buffer attribute in JSP?
The buffer attribute specifies the buffering characteristics for the server output response object. You may code a
value of "none" to specify no buffering so that the servlet output is immediately directed to the response object or
you may code a maximum buffer size in kilobytes, which directs the servlet to write to the buffer before writing to
the response object.

42. What is page Directive?


The page directive is used to provide instructions to the container. These instructions pertain to the current JSP page.
You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the
JSP page.

(4 to 6 marks)

1. Explain the three key methods in the lifecycle of a servlet (init(), service(), destroy())
The life cycle of a servlet is managed by a servlet container (e.g., Apache Tomcat), which handles its loading,
initialization, request processing, and removal. The main methods in the [Link] interface (or
[Link] in Jakarta EE) that define the life cycle are:

• init(): Called once by the servlet container when the servlet is first loaded into memory and instantiated. It is
used for one-time initialization tasks, such as establishing a database connection or reading configuration
parameters.
• service(): Called by the container for every client request received by the servlet. This method processes the
request and generates the response. For HTTP servlets, the generic service() method dispatches the request
to specific methods based on the HTTP request type (e.g., doGet(), doPost(), doPut(), doDelete()).
• destroy(): Called once by the servlet container before the servlet instance is removed from service and garbage
collected. It is used for cleanup operations like closing file handles or releasing resources
2. Develop a basic servlet program that displays a welcome message to the user
import [Link].*;
import [Link].*;
import [Link].*;

public class WelcomeServlet extends HttpServlet {


Unit 4 Advanced Java & J2EE Page : 8
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html>");
[Link]("<body>");
[Link]("<h1>Welcome to Servlet Programming</h1>");
[Link]("</body>");
[Link]("</html>");
}
}

3. Explain the functionalities of the following methods available in servletConfig Interface


The ServletConfig Interface
The ServletConfig interface allows a servlet to obtain configuration data when it is loaded. The methods declared by
this interface are summarized here:

4. Write the usage of any four methods of servletRequest interface


TheServletRequestinterface enables a servlet toobtaininformationaboutaclientrequest.
Unit 4 Advanced Java & J2EE Page : 9

5. Write the usage of any four methods of servletResponse interface

TheServletResponseinterface enables a servlet to formulate a response for a client.

6. Write a Java servlet named FormProcessorServlet that can handle HTTP POST requests containing form data. The
servlet should: Read Parameters: Extract the names and values of parameters submitted from the form. Process
Data: Access the specific parameter values for fields like "name" and "email"

(assuming those are the form field names). Generate Response: Create an HTML response that displays the
submitted data back to the user in a user-friendly format.

7. Explain the following methods of HttpServletRequest interface with their syntax

i. getCookies

The getCookies() method belongs to the HttpServletRequest interface in Java Servlet.


Unit 4 Advanced Java & J2EE Page : 10
It is used to retrieve all cookies sent by the client browser to the servlet.
Working of getCookies()
1. Browser sends cookies along with HTTP request.
2. Servlet calls [Link]().
3. Server returns all cookies as an array.
4. Servlet reads cookie names and values using:
o getName()
o getValue()
Functionality
• Returns an array of Cookie objects.
• Each object contains a cookie name and value.
• If no cookies are available, it returns null.
ii. getMethod

The getMethod() method belongs to the HttpServletRequest interface in Java Servlet.


It is used to determine the type of HTTP request sent by the client to the servlet.
Working of getMethod()
1. Client sends an HTTP request.
2. Servlet container creates HttpServletRequest object.
3. getMethod() reads the request type from the HTTP header.
4. Servlet processes the request accordingly.
Functionality
• Returns the HTTP method used in the request.
• The return value is a string such as:
o "GET" or "POST" or "PUT" or "DELETE"
iii. getPathInfo
The getPathInfo() method belongs to the HttpServletRequest interface in Java Servlet.
It is used to obtain the extra path information that comes after the servlet path in the request URL.
Functionality
• Returns additional path information associated with the URL.
• The extra path comes after the servlet name but before query parameters.
• If no extra path exists, it returns null.
iv. getSession

The getSession() method belongs to the HttpServletRequest interface in Java Servlet.


It is used to obtain the current user session associated with the request or create a new session if one does not exist.
Working of getSession()
1. Client sends request to server.
2. Server checks whether a session already exists.
3. If session exists:
o Existing session object is returned.
4. Otherwise:
o New session is created.
5. Session ID is maintained using cookies or URL rewriting.
8. With an example, Explain the purpose and behavior of the doGet() method in a servlet class.
Purpose of doGet()
The main purposes of the doGet() method are:
• Handle client GET requests
• Send responses to the browser
• Retrieve request parameters
• Display web pages or data
Behavior of doGet()
1. Browser sends an HTTP GET request.
2. Web container receives the request.
3. Servlet container invokes the doGet() method.
4. Servlet processes the request.
Unit 4 Advanced Java & J2EE Page : 11
5. Response is generated and sent back to the browser.

Here wewill develop a servlet that handles an HTTPGET request. The servlet is invoked when a form on a web page is
submitted. The example contains two files. A web page is defined in [Link], and a servlet is defined in
[Link]. The HTML source code for [Link] is shown in the following listing. It defines a form that
contains a select element and a submit button. Notice that the action parameter of the form tag specifies a URL.
The URL identifies a servlet to process the HTTP GET request.
<html>
<body>
<center>
<form name="Form1"
action="[Link]
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for [Link] is shown in the following listing. The doGet( )
method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( )
method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = [Link]("color");
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>The selected color is: ");
[Link](color);
[Link]();
}
}
9. With an example, Explain the purpose and behavior of the doPost() method in a servlet class.
Purpose of doPost()
The main purposes of the doPost() method are:
• Handle form submission securely
• Send large amounts of data to the server
• Process sensitive information such as passwords
• Insert or update data in databases
Behavior of doPost()
1. Browser sends an HTTP POST request.
2. Web container receives the request.
3. Servlet container invokes the doPost() method.
4. Servlet processes submitted data.
5. Response is generated and sent back to the browser.
This example demonstrates a servlet that handles an HTTP POST request when a form in [Link] is submitted
to [Link].
Unit 4 Advanced Java & J2EE Page : 12
The [Link] file is similar to [Link], except that its form uses the POST method and specifies a different
servlet in the action parameter.
<html>
<body>
<center>
<form name="Form1"
method="post" action="[Link]
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for [Link] is shown in the following listing. The doPost( ) method is overridden to
process any HTTP POST requests that are sent to this servlet. It uses the getParameter( ) method of
HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = [Link]("color");
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>The selected color is: ");
[Link](color);
[Link]();
}
}
10. What are the different methods involved in the process of session management in servlets? Explain their
purpose

Important Methods Used in Session Management


1. getSession()
Creates a new session or returns an existing session.
Used to start or access a user session.
2. setAttribute()
Stores data in the session using key-value pairs.
Stores user information such as username or login status.
3. getAttribute()
Retrieves data stored in the session.
Used to read session data.
4. removeAttribute()
Removes a specific attribute from the session.
Used to delete unwanted session data.
5. invalidate()
Destroys the current session completely.
Used during logout operations.
6. getId()
Unit 4 Advanced Java & J2EE Page : 13
Returns the unique session ID.
Used to identify user sessions uniquely.
7. isNew()
Checks whether the session is newly created.
Used to determine if a new session started.
8. setMaxInactiveInterval()
Sets session timeout duration in seconds.
Automatically invalidates inactive sessions.
9. getCreationTime()
Returns the time when the session was created.
Used for session tracking.
11. How cookies can be handled using servlet
A Cookie is a small piece of data stored on the client’s browser by a web server. In Java Servlet, cookies are used to
maintain user information such as login details, user preferences, session tracking, etc.

Steps to Handle Cookies in Servlet


1. Create a cookie object
2. Store information in the cookie
3. Add the cookie to the response
4. Retrieve cookies from the request
5. Read cookie values
12. Explain why JSP is a compelling choice for web development compared to the Common Gateway
Interface (CGI).

JavaServer Pages is considered a better choice for web development when compared to Common Gateway Interface
because JSP provides better performance, portability, scalability, and ease of development.
1. Better Performance
• In CGI, a new process is created for every client request.
• Creating processes repeatedly consumes more memory and CPU time.
• JSP works using threads inside the web server, so it is much faster.
2. Platform Independence
• JSP is based on Java.
• Java programs can run on any operating system that supports JVM.
3. Easier Web Page Development
• JSP allows embedding Java code directly into HTML.
• Developers can easily design dynamic web pages.
4. Reusability of Components
• JSP supports JavaBeans, custom tags, and reusable components.
• Code can be reused across multiple pages.
5. Built-in Session Management
• JSP provides automatic session tracking using sessions and cookies.
• CGI requires manual handling of session management.
6. Scalability
• JSP is suitable for large enterprise applications.
• CGI becomes slower when the number of users increases.
7. Robust and Secure
• JSP uses Java’s security features such as exception handling and type checking.
• CGI programs are more prone to errors and security issues.
8. Easy Database Connectivity
• JSP easily connects with databases using JDBC.
• CGI database handling is comparatively complex.
13. Explain the key steps involved in how a web server processes a JSP request and generates a web page.
Processing of a JSP Request by a Web Server
When a client requests a JavaServer Pages page, the web server processes the request through several steps to
generate a dynamic web page.
Key Steps in JSP Processing
Unit 4 Advanced Java & J2EE Page : 14
1. Client Sends Request
• The user enters the JSP page URL in the browser.
• The browser sends an HTTP request to the web server.
2. Web Server Receives the Request
• The web server identifies that the requested file is a JSP page.
• The request is forwarded to the JSP container (such as Apache Tomcat).
3. Translation of JSP into Servlet
• The JSP container translates the JSP page into an equivalent Java Servlet source file.
• HTML code becomes [Link]() statements.
• JSP tags and Java code are converted into servlet code.
4. Compilation of Servlet
• The generated servlet source file is compiled into bytecode (.class file).
• If compilation fails, an error page is generated.
5. Loading the Servlet
• The web container loads the compiled servlet class into memory.
• An instance of the servlet is created.
6. Initialization
• The container calls the jspInit() method.
• This method runs only once during the JSP lifecycle.
7. Request Processing
• For every client request, the _jspService() method is executed.
• This method generates dynamic content and processes business logic.
8. Response Generation
• The servlet produces HTML output dynamically.
• The generated response is sent back to the web server.
9. Response Sent to Browser
• The web server sends the generated HTML page to the client browser.
• The browser displays the web page to the user.
14. Explain the key stages involved in the lifecycle of a Java Server Page (JSP).
JSP life cycle The key to understanding the low-level functionality of JSP is to understand the simple life cycle they
follow. A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle
with an additional step which is required to compile a JSP into servlet. Paths Followed By JSP The following are the
paths followed by a JSP
• Compilation
• Initialization
• Execution
• Cleanup

JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has
never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
• Parsing the JSP.
• Turning the JSP in to a servlet.
Unit 4 Advanced Java & J2EE Page : 15
• Compiling the servlet.
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If we need to perform JSP-
specific initialization, override the jspInit() method:
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
CleanUp
The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
15. Write short note on JSP directives and JSP Actions
JSP Directives
The JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of the
JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
Directives can have a number of attributes which you can list down as key-value pairs and separated by commas.
<%@ page attribute="value" %>

Directive Description
<%@ page... %> Defines page-dependent attributes, such as scripting language, error
page, and buffering requirements.
<%@ include... %> Includes a file during the translation phase.
<%@ taglib...%> Declares a tag library, containing custom actions, used in the page
16. Explain any four buffer attributes with examples
1. Buffer Attribute
The buffer attribute specifies the size of the output buffer used by JSP before sending data to the client.
<%@ page buffer="8kb" %>
This creates an 8 KB buffer.
Advantage
• Improves performance by reducing direct output to the browser.
2. autoFlush Attribute
The autoFlush attribute determines whether the buffer should automatically flush when it becomes full.
<%@ page buffer="8kb" autoFlush="true" %>
If the buffer is full, data is automatically sent to the client.
Values
• true → buffer flushes automatically
• false → throws exception if buffer overflows
3. contentType Attribute
The contentType attribute specifies the MIME type and character encoding of the response.
<%@ page contentType="text/html;charset=UTF-8" %>
This tells the browser that the response is HTML with UTF-8 encoding.
Common Types
• text/html
• text/plain
• application/pdf
4. errorPage Attribute
The errorPage attribute specifies the JSP page that handles exceptions or errors.
<%@ page errorPage="[Link]" %>
If an error occurs, control is transferred to [Link].
In Error Page
Use:
<%@ page isErrorPage="true" %>
to access exception details.
17. Explain the steps in the JDBC process.
Unit 4 Advanced Java & J2EE Page : 16
J2ME applications follow a common process to interact with a DBMS using JDBC. The process includes loading the
JDBC driver, connecting to the database, executing statements, processing returned data, and closing the connection.
The next sections give an overview of these routines before explaining each one in detail.
Load the JDBC Driver
Before a J2ME application connects to a DBMS, the JDBC driver must be loaded using the [Link]() method. For
example, to work with Microsoft Access, the JDBC-ODBC Bridge driver [Link] is loaded. The
driver name is passed as an argument to the [Link]() method.
Connect to the DBMS
After loading the driver, the J2ME application connects to the DBMS using the [Link]()
method. The DriverManager class manages database driver information and connections. This method requires the
database URL and, if needed, the user ID and password.
Create and Execute an SQL Statement
After establishing the database connection, the next step is to send an SQL query to the DBMS for processing. An SQL
query contains commands that instruct the database to perform operations such as retrieving data. Query writing and
execution.
Process Data Returned by the DBMS
After the query is processed, the results returned by the DBMS are stored in a [Link] object. The ResultSet
contains methods for accessing and processing the returned data in the J2ME application. The following example
demonstrates a simple routine for extracting data, with error-handling code omitted for clarity.
Terminate the Connection to the DBMS
The connection to the DBMS is terminated by using the close() method of the Connection object once the J2ME
application is finished accessing the DBMS.
18. Write the steps to associate database with JDBC/ODBC bridge.
Associating the JDBC/ODBC Bridge with the Database
You use the ODBC Data Source Administrator to create the association between the database and the JDBC/ODBC Bridge. Here’s
what you need to do:
1. Select Start | Settings | Control Panel.
2. Select ODBC 32 to display the ODBC Data Source Administrator.
3. Add a new user by selecting the Add button.
4. Select the appropriate driver and click Finish. Use the Microsoft Access Driver for MS Access databases; otherwise choose the
driver matching your DBMS, and install it if it is not available in the list.
5. Enter the name of the database as the Data Source name in the ODBC Microsoft Access Setup dialog box. This is the name that
will be used within your Java database program to connect to the DBMS.
6. Enter a description for the data source. This is optional, but will be a reminder of the kind of data stored in the database.
7Click the Select button and browse your computer to locate the database file. After selecting the database, click OK, and its path
and name will appear in the ODBC setup dialog box..
8. If required, click the Advanced button to set a login name and password for the database, then click OK. If authentication is not
needed, skip this step..
9. When the ODBC Microsoft Access Setup dialog box appears, select OK.
10. Select OK to close the ODBC Data Source Administrator dialog box.
19. What is JDBC Driver? Explain different types.
A JDBC Driver is a software component that enables a Java application to connect and interact with a database. It converts JDBC
calls into database-specific commands.
Java applications use JDBC drivers to:
• Establish database connections
• Execute SQL queries
• Retrieve results from databases
Types of JDBC Drivers
1. Type 1 Driver – JDBC-ODBC Bridge Driver
Converts JDBC calls into ODBC calls.
Architecture
Java Application → JDBC Driver → ODBC Driver → Database
Advantages
• Easy to use
• Suitable for small applications
Disadvantages
• Slow performance
• Requires ODBC installation
Unit 4 Advanced Java & J2EE Page : 17
• Removed after Java 8
Example Driver
[Link]("[Link]");
2. Type 2 Driver – Native API Driver
Converts JDBC calls into native database API calls.
Architecture
Java Application → JDBC Driver → Native Library → Database
Advantages
• Better performance than Type 1
Disadvantages
• Requires native libraries on client machine
• Platform dependent
3. Type 3 Driver – JDBC Driver
Uses a middleware server to communicate with the database.
Architecture
Java Application → JDBC Driver → Middleware Server → Database
Advantages
• Platform independent
• Supports multiple databases
Disadvantages
• Requires middleware server
• More network overhead
4. Type 4 Driver – JDBC Driver Pure Java
Directly converts JDBC calls into database-specific protocol.
Architecture
Java Application → JDBC Driver → Database
Advantages
• Fastest performance
• Pure Java and platform independent
• No middleware or native library required
Disadvantages
• Database-specific driver needed

20. Explain the steps to connect to the database in java?

21. What are the JDBC statements? Explain


In JDBC, Statements are used to execute SQL queries and updates on a database. JDBC provides three main types of statement
interfaces.
Types of JDBC Statements
1. Statement
Used to execute simple SQL queries without parameters.
Features
• Suitable for static SQL queries
• SQL is compiled every time
• Less secure for user input
Methods
• executeQuery() → executes SELECT query
• executeUpdate() → executes INSERT, UPDATE, DELETE
• execute() → executes any SQL statement
2. PreparedStatement
Used for parameterized SQL queries.
Features
• Faster execution
• Prevents SQL injection
• Query is precompiled
Advantages
• Better performance
• More secure
• Easy handling of dynamic values
Unit 4 Advanced Java & J2EE Page : 18
3. CallableStatement
Used to execute stored procedures in the database.
Features
• Calls database procedures/functions
• Supports IN, OUT parameters
Advantages
• Improves performance
• Reduces network traffic
• Reusable business logic
22. Describe the following
i) Scrollable Resultset

A Scrollable ResultSet in Java JDBC is a type of ResultSet that allows the cursor to move both forward and backward
through database records, unlike the default ResultSet which moves only forward.
Types of Scrollable ResultSet
1. ResultSet.TYPE_FORWARD_ONLY
o constant restricts the virtual cursor to downward movement, which is the default setting.
2. ResultSet.TYPE_SCROLL_INSENSITIVE
o Does not reflect database changes after ResultSet creation.
3. ResultSet.TYPE_SCROLL_SENSITIVE
o Reflects changes made to the database while ResultSet is open.
Common Cursor Methods
• next() → move to next row
• previous() → move to previous row
• first() → move to first row
• last() → move to last row
• absolute(int row) → move to specific row
• relative(int rows) → move relative rows
Advantages
• Easy navigation through records
• Supports random access to rows
• Useful in GUI applications and reports
ii) Updatable ResultSet

An Updatable ResultSet in Java JDBC allows modifying database records directly through the ResultSet object
without writing separate SQL UPDATE statements.
Features
• Update existing rows
• Insert new rows
• Delete rows
• Changes are reflected in the database
Important Methods
• updateInt()
• updateString()
• updateRow()
• deleteRow()
• moveToInsertRow()
• insertRow()
Advantages
• Easy database modification
• No need for separate SQL update queries
• Simplifies CRUD operations in JDBC
23. Write a note on DatabaseMetaData interface
Metadata is data about data, as discussed in Chapter 9. A J2ME application can access metadata by using the
DatabaseMetaData interface. The DatabaseMetaData interface is used to retrieve information about databases,
tables, columns, and indexes, among other information about the DBMS. A J2ME application retrieves metadata about
the database by calling the getMetaData() method of the Connection object. The getMetaData() method returns a
Unit 4 Advanced Java & J2EE Page : 19
DatabaseMetaData object that contains information about the database and its components. Once the
DatabaseMetaData object is obtained, an assortment of methods contained in the DatabaseMetaData object are
called to retrieve specific metadata. Here are some of the more commonly used DatabaseMetaData object methods:
■ getDatabaseProductName() Returns the product name of the database
■ getUserName() Returns the user name
■ getURL() Returns the URL of the database
■ getSchemas() Returns all the schema names available in this database
■ getPrimaryKeys() Returns primary keys
■ getProcedures() Returns stored procedure names
■ getTables() Returns names of tables in the database
24. Explain the types of Exceptions occur in JDBC.

You might also like