Java Q Unit4
Java Q Unit4
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.
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
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?
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.
(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].*;
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html>");
[Link]("<body>");
[Link]("<h1>Welcome to Servlet Programming</h1>");
[Link]("</body>");
[Link]("</html>");
}
}
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.
i. getCookies
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
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
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.