You are on page 1of 64

JDBC

Q1. What is JDBC? Explain different types JDBC Drivers with suitable diagram.
JDBC Driver

JDBC Driver is a software component that enables java application to interact with the database. T
JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC
bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged
because of thin driver.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the ODBC
function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

Advantage:

o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

o The Native driver needs to be installed on the each client machine.


o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written
in java.
Advantage:

o No client side library is required because of application server that can


perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

o Network support is required on client machine.


o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.

Advantage:

o Better performance than all other drivers.


o No software is required at client side or server side.

Disadvantage:

o Drivers depend on the Database.

Q2) Write a program to retrieve all student details from a STUDENT_INFO


table with student name starts with letter ‘S’ and display them using JDBC.
// Java Program retrieving contents of
// Table Using JDBC connection

// Java code producing output which is based


// on values stored inside the "cuslogin" table in DB

// Importing SQL libraries to create database


importjava.sql.*;

publicclassGFG {

// Step1: Main driver method


publicstaticvoidmain(String[] args)
{
// Step 2: Making connection using
// Connection type and inbulit function on
Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;

con = connection.connectDB();

// Try block to catch exception/s


try{

// SQL command data stored in String datatype


String sql = "select * from STUDENT_INFO";
p = con.prepareStatement(sql);
rs = p.executeQuery();

// Printing ID, name, email of customers


// of the SQL command above
System.out.println("id\t\tname\t\temail");

// Condiion check
while(rs.next()) {

intid = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println(id + "\t\t"+ name
+ "\t\t"+ email);
}
}
// Catch block to handle exception
catch(SQLException e) {

// Print exception pop-up on scrreen


System.out.println(e);
}
}
}

Q3) Write a program using PreparedStatement to update address of all


students to “New_Hostel” if student belongs to Section “A” of CSE
Department. Display number of records updated in the table.

Q4) Write a program to merge data of Table_1 and Table_2 into Table_1
using JDBC. Both Table_1 and Table_2 contains students details of CSE and
CSIT departments.
// Java Program to Join Contents

// of More than One Table & Display in JDBC

// Step 1: Importing DB files


// Provides the API for accessing and processing

// data stored in a data source

importjava.sql.*;

// Class for Joining of multiple tables

publicclassGFG {

// Main driver method

publicstaticvoidmain(String[] args)

// Display message

System.out.println(

"Joining 2 MySQL tables using Natural Join");

// DB 'Connection' object of Connection class

Connection con = null;

// Try block to check exceptions

try{

// Step 2: Load and register drivers

// Loading driver

// Jars(relevant) or mysql-connector-java-8.0.22

// in build path of project

Class.forName("com.mysql.cj.jdbc.Driver");

// Registering driver

// test is database name here

// serverTimezone=UTC, if not provided we will

// have java.sql.SQLException

// Credentials here are root/""


// i.e. username is root

// password is ""

// Step 3: Establishing a connection

con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/test?serverTimezone=UTC",

"root", "");

// Try block to check java exceptions

try{

// Step 4: Write a statement

// Join

Statement st = con.createStatement();

// Combining two tables in query using

// NATURAL JOIN studentsdetails columns :

// Name,caste,NeetMarks,gender

// studentspersonaldetails columns :

// Name,Address,email

// In both tables, connecting columns are

// Name Name is taken Here res will have the

// data from

// both studentsdetails and

// studentspersonaldetails whenever "Name"

// in both tables are matched join

ResultSet res = st.executeQuery(

"SELECT *FROM "

+ "Tble_1"

+ " NATURAL JOIN "

+ "Table_2");

// Step 5: Execute the query

System.out.println(" StuName"
+ " Gender"

+ " Caste "

+ "Neet Marks"

+ " Email");

// Step 6: Process the statements

// Iterate the resultset and retrieve the

// required fields

while(res.next()) {

String name = res.getString("Name");

String gender = res.getString("gender");

String caste = res.getString("caste");

String neetMarks

= res.getString("NeetMarks");

String email = res.getString("email");

// Beautification of output

System.out.format(

"%10s%10s%10s%10s%20s\n", name,

gender, caste, neetMarks, email);

// Step 7: Close the connection

con.close();

// Catch bloack to handle DB exceptions

catch(SQLException s) {

// If there is error in SQL query, this

// exception occurs

System.out.println(

"SQL statement is not executed!");

}
// Catch bloack to handle generic java

// exceptions

catch(Exception e) {

// General exception apart from SQLException are

// caught here

e.printStackTrace();

Q5) Write a program to authenticate user credentials using JDBC. If userId


matches but not the password then displays invalid password. If both are
matches then display Hello and Username else display invalid credential.
// Java Program to check the validity
// of a Password using User-Defined Exception

// Class for user-defined InvalidPasswordException


classInvalidPasswordException extendsException {

intpasswordConditionViolated = 0;

publicInvalidPasswordException(intconditionViolated)
{
super("Invalid Password: ");
passwordConditionViolated = conditionViolated;
}

publicString printMessage()
{
// Call constructor of parent Exception
// according to the condition violated
switch(passwordConditionViolated) {

// Password length should be


// between 8 to 15 characters
case1:
return("Password length should be"
+ " between 8 to 15 characters");

// Password should not contain any space


case2:
return("Password should not"
+ " contain any space");

// Password should contain// at least one digit(0-9)


case3:
return("Password should contain"
+ " at least one digit(0-9)");

// Password should contain at least


// one special character ( @, #, %, &, !, $ )
case4:
return("Password should contain at "
+ "least one special character");

// Password should contain at least


// one uppercase letter(A-Z)
case5:
return("Password should contain at"
+ " least one uppercase letter(A-Z)");

// Password should contain at least


// one lowercase letter(a-z)
case6:
return("Password should contain at"
+ " least one lowercase letter(a-z)");
}

return("");
}
}

// Driver Class
publicclassPasswordValidator {

// A utility function to check


// whether a password is valid or not
publicstaticvoidisValid(String password)
throwsInvalidPasswordException
{

// for checking if password length


// is between 8 and 15
if(!((password.length() >= 8)
&& (password.length() <= 15))) {
thrownewInvalidPasswordException(1);
}

// to check space
if(password.contains(" ")) {
thrownewInvalidPasswordException(2);
}
if(true) {
intcount = 0;

// check digits from 0 to 9


for(inti = 0; i <= 9; i++) {

// to convert int to string


String str1 = Integer.toString(i);

if(password.contains(str1)) {
count = 1;
}
}
if(count == 0) {
thrownewInvalidPasswordException(3);
}
}

// for special characters


if(!(password.contains("@") || password.contains("#")
|| password.contains("!") || password.contains("~")
|| password.contains("$") || password.contains("%")
|| password.contains("^") || password.contains("&")
|| password.contains("*") || password.contains("(")
|| password.contains(")") || password.contains("-")
|| password.contains("+") || password.contains("/")
|| password.contains(":") || password.contains(".")
|| password.contains(", ") || password.contains("<")
|| password.contains(">") || password.contains("?")
|| password.contains("|"))) {
thrownewInvalidPasswordException(4);
}

if(true) {
intcount = 0;

// checking capital letters


for(inti = 65; i <= 90; i++) {

// type casting
charc = (char)i;

String str1 = Character.toString(c);


if(password.contains(str1)) {
count = 1;
}
}
if(count == 0) {
thrownewInvalidPasswordException(5);
}
}

if(true) {
intcount = 0;

// checking small letters


for(inti = 90; i <= 122; i++) {

// type casting
charc = (char)i;
String str1 = Character.toString(c);

if(password.contains(str1)) {
count = 1;
}
}
if(count == 0) {
thrownewInvalidPasswordException(6);
}
}

// The password is valid


}

// Driver code
publicstaticvoidmain(String[] args)
{

String password1 = "GeeksForGeeks";

try{
System.out.println("Is Password "
+ password1 + " valid?");
isValid(password1);
System.out.println("Valid Password");
}
catch(InvalidPasswordException e) {
System.out.print(e.getMessage());
System.out.println(e.printMessage());
}

String password2 = "Geek007@GFG";


try{
System.out.println("\nIs Password "
+ password2 + " valid?");
isValid(password2);
System.out.println("Hello");
}
catch(InvalidPasswordException e) {
System.out.print(e.getMessage());
System.out.println(e.printMessage());
}
}
}

Q6. What is ResultSet? Give a comparative study among Statement,


PreparedStatement and Callable Statement.
The SQL statements that read data from a database query, return the data in a
result set. The SELECT statement is the standard way to select rows from a
database and view them in a result set. The java.sql.ResultSet interface represents
the result set of a database query.
A ResultSet object maintains a cursor that points to the current row in the result set.
The term "result set" refers to the row and column data contained in a ResultSet
object.
The methods of the ResultSet interface can be broken down into three categories −
• Navigational methods − Used to move the cursor around.
• Get methods − Used to view the data in the columns of the current row being
pointed by the cursor.
• Update methods − Used to update the data in the columns of the current
row. The updates can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties
are designated when the corresponding Statement that generates the ResultSet is
created.
JDBC provides the following connection methods to create statements with desired
ResultSet −
• createStatement(int RSType, int RSConcurrency);
• prepareStatement(String SQL, int RSType, int RSConcurrency);
• prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the second
argument is one of two ResultSet constants for specifying whether a result set is
read-only or updatable.
Statement

Statement interface is used to execute normal SQL queries. You can’t pass the parameters to
SQL query at run time using this interface. This interface is preferred over other two
interfaces if you are executing a particular SQL query only once. The performance of this
interface is also very less compared to other two interfaces. In most of time, Statement
interface is used for DDL statements like CREATE, ALTER, DROP etc. For example,

2) PreparedStatement

PreparedStatement is used to execute dynamic or parameterized SQL queries.


PreparedStatement extends Statement interface. You can pass the parameters to SQL query at
run time using this interface. It is recommended to use PreparedStatement if you
are executing a particular SQL query multiple times. It gives better performance than
Statement interface. Because, PreparedStatement are precompiled and the query plan is
created only once irrespective of how many times you are executing that query. This will
save lots of time.

3) CallableStatement

CallableStatement is used to execute the stored procedures. CallableStatement extends


PreparedStatement. Usng CallableStatement, you can pass 3 types of parameters to stored
procedures. They are : IN – used to pass the values to stored procedure, OUT – used to hold
the result returned by the stored procedure and IN OUT – acts as both IN and OUT
parameter. Before calling the stored procedure, you must register OUT parameters
using registerOutParameter() method of CallableStatement. The performance of this
interface is higher than the other two interfaces. Because, it calls the stored procedures which
are already compiled and stored in the database server.
Statement Vs PreparedStatement Vs CallableStatement In Java :

Servlet
Q1. What is Servlet? Explain life cycle of servlet with an example.

Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to
the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic
web page.
Life Cycle of a Servlet (Servlet Life Cycle)

1. Life Cycle of a Servlet


1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle
of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet performs all the
tasks. When the web container invokes the destroy() method, it shifts to the end
state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
1. public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method.
Notice that servlet is initialized only once. The syntax of the service method of the
Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:

1. public void destroy()

Q2. What is Session Tracking? Explain different session tracking techniques.


Session Tracking in Servlets

1. Session Tracking
2. Session Tracking Techniques

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known


as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking


techniques. Each time user requests to the server, server treats the request as the
new request. So we need to maintain the state of an user to recognize to particular
user.

HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session tracking methods:

1. User authorization
2. Hidden fields
3. URL rewriting
4. Cookies
5. Session tracking API

The first four methods are traditionally used for session tracking in all the server-side
technologies. The session tracking API method is provided by the underlying
technology (java servlet or PHP or likewise). Session tracking API is built on top of
the first four methods.

1. User Authorization

Users can be authorized to use the web application in different ways. Basic concept is
that the user will provide username and password to login to the application. Based
on that the user can be identified and the session can be maintained.

2. Hidden Fields

<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>


Hidden fields like the above can be inserted in the webpages and information can be
sent to the server for session tracking. These fields are not visible directly to the user,
but can be viewed using view source option from the browsers. This type doesn’t
need any special configuration from the browser of server and by default available to
use for session tracking. This cannot be used for session tracking when the
conversation included static resources lik html pages.

3. URL Rewriting

Original URL: http://server:port/servlet/ServletName


Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general
added additional parameter will be sessionid or sometimes the userid. It will suffice
to track the session. This type of session tracking doesn’t need any special support
from the browser. Disadvantage is, implementing this type of session tracking is
tedious. We need to keep track of the parameter as a chain link until the conversation
completes and also should make sure that, the parameter doesn’t clash with other
application parameters.

4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value
pair of information, sent by the server to the browser. This should be saved by the
browser in its space in the client computer. Whenever the browser sends a request to
that server it sends the cookie along with it. Then the server can identify the client
using the cookie.
In java, following is the source code snippet to create a cookie:

Cookie cookie = new Cookie(“userID”, “7456”);


res.addCookie(cookie);

Session tracking is easy to implement and maintain using the cookies. Disadvantage
is that, the users can opt to disable cookies using their browser preferences. In such
case, the browser will not save the cookie at client computer and session tracking
fails.

5. Session tracking API

Session tracking API is built on top of the first four methods. This is inorder to help
the developer to minimize the overhead of session tracking. This type of session
tracking is provided by the underlying technology. Lets take the java servlet example.
Then, the servlet container manages the session tracking task and the user need not
do it explicitly using the java servlets. This is the best of all methods, because all the
management and errors related to session tracking will be taken care of by the
container itself.

Every client of the server will be mapped with a javax.servlet.http.HttpSession object.


Java servlets can use the session object to store and retrieve java objects across the
session. Session tracking is at the best when it is implemented using session tracking
api.

Q3)Write a program to enter user credentials in a login page and validate the
user in the database. If credential is correct redirect to page to display
welcome message else display suitable error message.

Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple client
requests.

A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.

Code Not Found


Q4. What is Cookie? Write a program to explain use of cookie.

Ans
Difference table between Cookies and Session
Session Cookies

A session stores the variables and their values within a file in a Cookies are stored on the user's computer as a text file.
temporary

directory on the server.

The session ends when the user logout from the application or Cookies end on the lifetime set by the user.

closes his web browser.

It can store an unlimited amount of data. It can store only limited data.

We can store as much data as we want within a session, but The maximum size of the browser's cookies is 4 KB.

there is a maximum memory limit, which a script can use at one time,

and it is 128 MB.

We need to call the session_start() function to start the session. We don't need to call a function to start a cookie as it is stored within

the local computer.

In PHP, to set a session data, the $_SESSION global variable is used. In PHP, to get the data from cookies, the $_COOKIE global variable is

used.

In PHP, to destroy or remove the data stored within a session, we We can set an expiration date to delete the cookie's data. It

can use the session_destroy() function, and to unset a specific will automatically delete the data at that specific time. There is no

variable, we can use the unset() function. particular function to remove the data.

Sessions are more secured compared to cookies, as Cookies are not secure, as data is stored in a text file, and if any

they save data in encrypted form. unauthorized user gets access to our system, he can temper the data.

Q5) Give a comparative study on justify which one is better session handling
mechanism between Cookie and HttpSession.
The Session and cookies are used by different websites for storing user's data across different
pages of the site. Both session and cookies are important as they keep track of the information
provided by a visitor for different purposes. The main difference between both of them is that
sessions are saved on the server-side, whereas cookies are saved on the user's browser or
client-side.
HTTP is a stateless protocol; hence it does not store any user information. For this purpose, we
can use Cookies. It allows us to store the information on the user's computer and track the state
of applications.

Q6 What is servlet chaining? Explain servlet chaining with a suitable


example. Create the Manifest file for mapping.

What is Servlet Chaining?

Taking the request from a browser window and processing that request by using multiple servlets as a
chain is called servlet chaining. In servlet chaining, we perform communication between servlet
programs to process the request given by a client.

All servlet programs that participate in a servlet chaining will use the same request and response
objects because they process the same request that is given by the client.
To perform servlet chaining we need the RequestDispatcher object. RequestDispatcher object means
it is the object of a container supplied java class
implementing javax.servlet.RequestDispatcher interface.

Q7 Write a servlet program to submit course name from a HTML page and
display details of all students enrol in that course in a tabular format.

http://mca.ignougroup.com/2017/08/write-and-run-servlet-code-to-fetch-and.html?m=1

q8 Write a program using servlet to add products to a shopping cart and


display all added product from shopping cart.
try{
String selectSQL = "select * from items_table where item_name = '"+
item+"'";

Statement stmt = conn.createStatement();


ResultSet rs1 = stmt.executeQuery(selectSQL);
// Retrieve the results

out.println("<table border=\"1\"><tr><th>Item_ID</th><th>Item_name</th><
Cart</th></tr>");
if(rs1.next()){
out.println("<form action=\"ChildServlet\">");
out.println("<tr><td>"+ rs1.getFloat("item_id") + "</td>");
out.println("<td>"+ rs1.getString("item_name") + "</td>");
out.println("<td>"+"<a href ='"+ request.getContextPath() +
"/ItemDetail?id="+rs1.getFloat("item_id")+ "'>"+ rs1.getString("title")+"</a>"+
out.println("<td>"+ rs1.getString("category") + "</td>");
out.println("<td> "+ rs1.getFloat("price") + "</td>");
out.println("<td>");
out.println("<input type=\"hidden\" name=\"item_id\" value='"+
rs1.getFloat("item_id") +"'>");
out.println("<input type=\"hidden\" name=\"name\" value='"+
rs1.getString("item_name") +"'>");
out.println("<input type=\"hidden\" name=\"title\" value='"+
rs1.getString("title") +"'>");
out.println("<input type=\"hidden\" name=\"price\" value='"+
rs1.getFloat("price") +"'>");

out.println("<input type=\"submit\" value=\"Add to cart\" >");


out.println("</form>");
out.println("</td>");
out.println("</tr>");

}
else
if(!rs1.next()){
out.println("Error");
response.sendRedirect("error.html");

And my attempt at making a shopping cart:

String id = request.getParameter("item_id");
String name = request.getParameter("name");
1
String title = request.getParameter("title");
2
String price = request.getParameter("price");
3
4
5
6
7
8
9 out.println("<table border=\"1\"><tr><th>Item_ID</th><th>Item_name</th><th>

10</th></tr>");
11
12 out.println("<tr><td> "+ id + "</td>");

13 out.println("<td>"+ name + "</td>");

14 out.println("<td>"+ title + "</td>");


15 out.println("<td> "+ price + "</td>");
16
17 out.println("</tr>");

jsp
Q1 What is the advantage of JSP over servlet? Explain Servlet life cycle with a
suitable example.
Advantages of JSP over Servlets

1. Servlets use println statements for printing an HTML document which is


usually very difficult to use. JSP has no such tedius task to maintain.
2. JSP needs no compilation, CLASSPATH setting and packaging.
3. In a JSP page visual content and logic are seperated, which is not possible in
a servlet.
4. There is automatic deployment of a JSP, recompilation is done automatically
when changes are made to JSP pages.
5. Usually with JSP, Java Beans and custom tags web application is simplified.

Life Cycle of a Servlet (Servlet Life Cycle)

2. Life Cycle of a Servlet


1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle
of the servlet:

6. Servlet class is loaded.


7. Servlet instance is created.
8. init method is invoked.
9. service method is invoked.
10. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet performs all the
tasks. When the web container invokes the destroy() method, it shifts to the end
state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init
initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the
below:
2. public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method.
Notice that servlet is initialized only once. The syntax of the service method of the
Servlet interface is given below:

3. public void service(ServletRequest request, ServletResponse response)


4. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:

2. public void destroy()

Q2 What is Scripting Element? Explain different scripting elements with


suitable examples.

JSP Scripting Elements

JSP scripting elements are one of the most vital elements of a JSP code. These <%
%> tags contain JSP scripting elements. These tags are of the utmost importance as,
at the time of translation, the JSP engine will consider anything inside these tags.
Only this code will convert to Java code. Code other than this is plain or HTML text.

The scripting elements thus help to embed java code to the HTML, CSS, JavaScript
code. There are three main subdivisions of scripting elements in JSP.

1. Expression Tags
2. Scriptlet Tags
3. Declaration Tags

They all provide different ways to include java code in a JSP file.

1. Scriptlets in JSP

JSP Scriptlets help in embedding Java in HTML for JSP code. <%___%> tags
contain the Java code and are called as scriptlet tags. Unlike expressions, scriptlets
have a set of statements in Java language. It allows writing java code in it. The Syntax
of Scriptlet tag is as follows:

<% statement; statement ;….%>


The code inside a scriptlet tag goes to the _jspService() method of the generated
servlet for processing the request. For each request sent, the _jsp service() method
will invoke. If multiple scriptlets are present in the code, then they are appended to
this service method in an ordered fashion.

For Example:
scriptlet.jsp

<html>

<head><title>Scriptlets</title>

</head>

<body>
<h3>--DataFlair--</h3>

<h3>Use of scriptlet in JSP</h3>

<% int a=3;

int b=4;

int c=5;

out.println("a is: " +a+ "<br>" + "b is:" +b+ "<br>" + "c is:" +c+ "<br>");

out.println("Multiplication gives: " + a*b*c + "<br>");

out.println("Addition gives:" + (a+b+c));

%>

</body>

</html>
Explanation
The above code shows the use of a scriptlet tag that embeds the java code in it. The
code inside the scriptlet tag will go _jspService() method and will become pure java
code. The following is the output.

Output:

2. JSP Expressions

JSP Expression tags, as the name suggests, evaluates expressions. They incorporate
arithmetic and logical expressions so that they can be evaluated. They form an easy
means to access the value of a Java variable. The Expressions in JSP can be an access
point for other expressions and merge that value in an HTML file. They can easily
access data stored in applications.

Syntax of the expression is:


<%=expression/statement %>
This code will get written to the output stream of the response.

These expressions or statements can be any valid Java statement. This code gets
converted to out.print( ) statement when an auto generated servlet gets formed. Use
of expressions generates scriptless code.
Following are the examples of expressions in JSP.

a. expression.jsp

<html>

<head><title>Expressions</title>

</head>

<body>

<h3>--DataFlair--</h3>

<h3>Use of Expressions in JSP</h3>

<% String s1="expressions: done by kajal"; %>

<% out.print(s1); %></br>

<%=s1.toUpperCase() %>

</body>

</html>
b. expression2.jsp

<html>

<head><title>Expressions2</title>

</head>

<body>

<h3>--DataFlair--</h3>

<h3>Use of Expressions in JSP</h3>

<% int n1=10, n2=20; %>

<% out.print("Addition of numbers is ="); %>

<%=n1+n2 %>

</body>

</html>
Explanation
1. In this example, we can see the use of expression to get the result of the logical
expression. The result is shown in the output below.
Output:
2. Contrary to the first example, we can see the use of arithmetic in the JSP code. The
output is below.
Output:

3. JSP Declarations

Declarations in JSP declare java language statements. <%!___%> tags contain


declarations. They can declare classes/instances/inner classes/variables/methods.

Unlike the other two, this code doesn’t go to _jspService() method. This code rather
goes to the source file that gets generated outside the _jspService method.

Syntax for declarations are:


<%! statement,[statement,….] %>
Declarations have no access to implicit objects as they don’t appear in the service
method. A declaration will remain outside the service method. If a method declared
under declaration wants to access an object from scriptlet then it needs to pass the
object as parameter.

Example of declaration in JSP:


Declaration.jsp

<html>

<head><title>Declaration</title>

</head>

<body>

<h3>--DataFlair--</h3>

<h3>Use of Declaration in JSP</h3>

<%! int num1=2, num2=3, n=0; %>

<% n=num1+num2+1;

out.println("The number after adding declared variables is " + n);


%>

</body>

</html>
Explanation:
In this code, we declared num1 and num2. Then we performed calculations on it. It
will thus generate the following output.
Output:

Q3 What are the implicit objects defined in JSP? Briefly explain about them.
https://www.tutorialspoint.com/jsp/jsp_implicit_objects.htm#:~:text=Th
ese%20Objects%20are%20the%20Java,also%20called%20pre%2Ddefined
%20variables.

Q5 Explain different JSP directive elements with suitable example.


https://www.tutorialspoint.com/jsp/jsp_directives.htm

Q4 Create a registration form in JSP and store the data in a database table. If
successfully registered give a confirmation else print a suitable error
message.

Form to accept username and password : login.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>User Details</h1>
<%-- The form data will be passed to acceptuser.jsp
for validation on clicking submit
--%>
<formmethod="get"action="acceptuser.jsp">
Enter Username : <inputtype="text"name="user"><br/><br/>
Enter Password : <inputtype="password"name="pass"><br/>
<inputtype="submit"value="SUBMIT">
</form>
</body>
</html>

JSP to accept form data and verify a user : acceptuser.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
<title>Accept User Page</title>
</head>
<body>
<h1>Verifying Details</h1>
<%-- Include the ValidateUser.java class whose method
boolean validate(String, String) we will be using
--%>
<%-- Create and instantiate a bean and assign an id to
uniquely identify the action element throughout the jsp
--%>
<jsp:useBeanid="snr"class="saagnik.ValidateUser"/>

<%-- Set the value of the created bean using form data --%>
<jsp:setPropertyname="snr"property="user"/>
<jsp:setPropertyname="snr"property="pass"/>

<%-- Display the form data --%>


The Details Entered Are as Under<br/>
<p>Username : <jsp:getPropertyname="snr"property="user"/></p>
<p>Password : <jsp:getPropertyname="snr"property="pass"/></p>

<%-- Validate the user using the validate() of


ValidateUser.java class
--%>
<%if(snr.validate("GeeksforGeeks", "GfG")){%>
Welcome! You are a VALID USER<br/>
<%}else{%>
Error! You are an INVALID USER<br/>
<%}%>
</body>
</html>

The ValidateUser.java class


packagesaagnik;
importjava.io.Serializable;

// To persist the data for future use,


// implement serializable
publicclassValidateUser implementsSerializable {
privateString user, pass;

// Methods to set username and password


// according to form data
publicvoidsetUser(String u1) { this.user = u1; }
publicvoidsetPass(String p1) { this.pass = p1; }

// Methods to obtain back the values set


// by setter methods
publicString getUser() { returnuser; }
publicString getPass() { returnpass; }

// Method to validate a user


publicbooleanvalidate(String u1, String p1)
{
if(u1.equals(user) && p1.equals(pass))
returntrue;
else
returnfalse;
}
}

Outputs:
login.jsp
Next on clicking ‘SUBMIT’ button following page is generated.
acceptuser.jsp

Q6) Write a program to login to a website and print all students records from
a STUDENT_DETAILS table in tabular format.
Q7) Explain how JSP utilizing rich features of servlet and making it simple.
Mentioned few differences between JSP and Servlet.

JSP
SERVLET
JSP runs slower than servlet as it
Servlets run faster than JSP. takes time to compile the program
and convert into servlets.
It’s easier to code in JSP compared
It is hard to write code in servlet.
to servlets.
In MVC architecture, servlet works as a In MVC architecture, JSP works as a
controller. view for displaying output.
JSP is generally used when there is
It should be use when there is more
no involvement of much data
data processing involved.
processing.
There is no custom tag writing facility You can easily build custom tags
in servlets. that can directly call Java beans.
Servlet is a java code. JSP is a HTML-based code.
It can accept all protocol requests,
It can only accept HTTP requests.
including HTTP.
In JSP, you can’t override the
You can override the service() method.
service() method.
In Servlet, by default, session
In JSP, session management is
management is not enabled, user has
automatically enabled.
to enable it explicitly.
In Servlet, you have to implement both
In JSP, business logic is split from
business logic and presentation logic in
presentation logic using JavaBeans.
the single file.
Modification in Servlet file is a time
JSP modification is fast, as you just
consuming due to reloading,
need to click one refresh button.
recompiling, and restarting the server.

Q8)Explain Session Tracking in JSP. How session object can be used to handle
session in JSP.
Ans- https://www.javawebtutor.com/articles/jsp/jspsession.php

Hibernate:
Q1) What is ORM? Explain the use case for hibernate with a suitable diagram.
Ans- Object-relational mapping (ORM) is a programming technique in which a
metadata descriptor is used to connect object code to a relational database.
Object code is written in object-oriented programming (OOP) languages such as
Java or C#. ORM converts data between type systems that are unable to coexist
within relational databases and OOP languages

https://www.tutorialspoint.com/hibernate/hibernate_quick_guide.htm

Q2) Write a hibernate program to store registration details of a user into a


database table using ORM.
Ans
https://www.javatpoint.com/web-application-with-hibernate
I am not sure pls check

Q3) What is hibernate configuration file. Create a hibernate.cfg.xml file and


add dependency for oracle 9i database.

Hibernate Configuration File(cfg file) is the file loaded into an hibernate application when
working with hibernate.Hibernate uses this file to establish connection to the database
server.It is an XML file which is used to define below information.Standard name for this file
is hibernate.cfg.xml.

• DataBase connection details: Driver class, URL, username and


Password.
• Hibernate properties: Dialect, show_sql, second_level_cache .etc
• Mapping files names.

Sample Configuration File :


hibernate.cfg.xml
?

1<hibernate-configuration>
2<session-factory>
3
4
<! -- Related to the connection START -->
5
<propertyname="connection.driver_class">Driver Class Name </property>
6
<propertyname="connection.url">URL </property>
7
<propertyname="connection.user">USER NAME </property>
8
<propertyname="connection.password">PASSWORD</property>
9
<! -- Related to the connection END -->
10
11
<! -- Related to hibernate properties START -->
12
<propertyname="show_sql">true/false</property>
13
<propertyname="format_sql">true/false</property>
14
<propertyname="use_sql_comments">true/false</property>
15
16<propertyname="dialet">Database dialet class</property>
17<propertyname="hbm2ddl.auto">create/create-drop/update/validate</property>
18<! -- Related to hibernate properties END-->
19
20<! -- Related to mapping START-->
21<mappingresource="hbm file 1 name .xml"/ >
22<mappingresource="hbm file 2 name .xml"/ >
23<! -- Related to the mapping END -->
24
25</session-factory>

</hibernate-configuration>
https://docs.oracle.com/cd/E89497_01/html/rpm_80_installation/GUID-
47D444D6-0C07-4B0B-BA28-0882D9B55683.htm

Q4) What is JPA? Explain hibernate architecture with a suitable example.

The Java Persistence API (JPA) is a specification of Java. It is used to persist data
between Java object and relational database. JPA acts as a bridge between object-
oriented domain models and relational database systems.

As JPA is just a specification, it doesn't perform any operation by itself. It requires an


implementation. So, ORM tools like Hibernate, TopLink and iBatis implements JPA
specifications for data persistence.

Hibernate Architecture:

Configuration:
• Configuration is a class which is present in org.hibernate.cfg
package. It activates Hibernate framework. It reads both
configuration file and mapping files.
• It activate Hibernate Framework
• Configuration cfg=new Configuration();
• It read both cfg file and mapping files
• cfg.configure();
• It checks whether the config file is syntactically correct or not.
•If the config file is not valid then it will throw an exception. If it is
valid then it creates a meta-data in memory and returns the meta-
data to object to represent the config file.
SessionFactory:
• SessionFactory is an Interface which is present in org.hibernate
package and it is used to create Session Object.
• It is immutable and thread-safe in nature.
• buildSessionFactory() method gathers the meta-data which is
in the cfg Object.
• From cfg object it takes the JDBC information and create a
JDBC Connection.
• SessionFactory factory=cfg.buildSessionFactory();
Session:
• Session is an interface which is present in org.hibernate package.
Session object is created based upon SessionFactory object i.e.
factory.
• It opens the Connection/Session with Database software through
Hibernate Framework.
• It is a light-weight object and it is not thread-safe.
• Session object is used to perform CRUD operations.
• Session session=factory.buildSession();
Transaction:
• Transaction object is used whenever we perform any operation and
based upon that operation there is some change in database.
• Transaction object is used to give the instruction to the database to
make the changes that happen because of operation as a
permanent by using commit() method.
• Transaction tx=session.beginTransaction();
• tx.commit();
Query:
• Query is an interface that present inside org.hibernate package.
• A Query instance is obtained by calling Session.createQuery().
• This interface exposes some extra functionality beyond that
provided by Session.iterate() and Session.find():
1. A particular page of the result set may be selected by
calling setMaxResults(), setFirstResult().
2. Named query parameters may be used.
• Query query=session.createQuery();
Criteria:
• Criteria is a simplified API for retrieving entities by composing
Criterion objects.
• The Session is a factory for Criteria. Criterion instances are usually
obtained via the factory methods on Restrictions.
• Criteria criteria=session.createCriteria();
Flow of working during operation in Hibernate Framework :
Suppose We want to insert an Object to the database. Here Object is nothing
but persistence logic which we write on java program and create an object of
that program. If we want to insert that object in the database or we want to
retrieve the object from the database. Now the question is that how hibernate
save the Object to the database or retrieve the object from the database.
There are several layers through which Hibernate framework go to achieve
the above task. Let us understathe nd the layers/flow of Hibernate framework
during performing operations:

Stage I: In first stage, we will write the persistence logic to perform some
specific operations to the database with the help of Hibernate Configuration
file and Hibernate mapping file. And after that we create an object of the
particular class on which we wrote the persistence logic.
Stage II:In second stage, our class which contains the persistence logic will
interact with the hibernate framework where hibernate framework gives some
abstraction do perform some task. Now here the picture of java class is over.
Now Hibernate is responsible to perform the persistence logic with the help
of layers which is below of Hibernate framework or we can say that the
layers which are the internal implementation of Hibernate.
Stage III:In third stage, our hibernate framework interact which JDBC, JNDI,
JTA etc to go to the database to perform that persistence logic.
Stage IV & V:In fourth & fifth stage, hibernate is interact with Database with
the help of JDBC driver. Now here hibernate perform that persistence logic
which is nothing but CRUD operation. If our persistence logic is to retrieve an
record then in the reverse order it will display on the console of our java
program in terms of Object.

Short Questions
Hibernate:
Q1) List out benefits of using Hibernate Framework?

1) Open Source and Lightweight

Hibernate framework is open source under the LGPL license and lightweight.

2) Fast Performance

The performance of hibernate framework is fast because cache is internally used in


hibernate framework. There are two types of cache in hibernate framework first level
cache and second level cache. First level cache is enabled by default.

3) Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates


the database independent queries. So you don't need to write database specific
queries. Before Hibernate, if database is changed for the project, we need to change
the SQL query as well that leads to the maintenance problem.

4) Automatic Table Creation

Hibernate framework provides the facility to create the tables of the database
automatically. So there is no need to create tables in the database manually.

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status

Hibernate supports Query cache and provide statistics about query and database
status.

Q2)What are the advantages of Hibernate over JDBC?


The advantages of Hibernate over JDBC are:

1. Hibernate code will work well for all databases, for ex: Oracle,MySQL, etc. where as
JDBC is database specific.

2. No knowledge of SQL is needed because Hibernate is a set of objects and a table is


treated as an object, where as to work with JDBC, one need to know SQL.

3. Query tuning is not required in Hibernate. The query tuning is automatic in hibernate by
using criteria queries, and the result of performance is at its best. Where as in JDBC the
query tuning is to be done by the database authors.

4. With the support of cache of hibernate, the data can be placed in the cache for better
performance. Where as in JDBC the java cache is to be implemented.

Q3) What is hibernate mapping file?


▪ Hibernate mapping file is used to map java object to the database table.
▪ We can have any number of mapping files in a project.
▪ Each hibernate mapping file must contain only one <id> tag (or relevant tag
<composite-id>)
▪ <id> tag corresponds to either primary key or Non primary key. Hibernate need
unique key to map
▪ Class names and property names are case sensitive in mapping file.
▪ Table names and column names are not case sensitive in mapping file.
▪ If we don’t give <column> tag, then property name will be column name.
▪ If we don’t give table name, then class name will be the table name.

Q4) What is Hibernate SessionFactory and how to configure it?


https://docs.atlassian.com/hibernate2/2.1.8/reference/session-
configuration.html

Q5) What is HQL?


Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but
instead of operating on tables and columns, HQL works with persistent objects and their
properties. HQL queries are translated by Hibernate into conventional SQL queries, which in
turns perform action on database.

Q6) Name some of the important interfaces of Hibernate framework?

The core interfaces of Hibernate framework are:

o Configuration
o SessionFactory
o Session
o Query
o Criteria
o Transaction

Q7) How to achieve mapping in Hibernate?..


Q8) What is One-to-One association in Hibernate?
Q9) What is One-to-Many association in Hibernate?
Q10) What is Many-to-Many association in Hibernate?

Java Server Pages:


Q1) List out few JSP Action Tags.

JSP Action Description


Tags

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include mostly.

jsp:fallback can be used to print the message if plugin is working. It is used in


jsp:plugin.

Q2) List out all Implicit Objects available in JSP.

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse
config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

Q3) How can we stop errors on Display in a JSP Page?


Ans

You first set "errorPage" attribute of PAGE directive to the name of the error page (ie
errorPage="error.jsp")in your jsp page .
Then in the error.jsp page set "isErrorpage=TRUE".
When an error occur in your jsp page, then the control will be automatically forward
to error page.

Q4) What is the procedure to include static files in a JSP?


Static pages are always included using JSP include directive. This way the
inclusion is performed in the translation phase once. Note that a relative
URL must be supplied for file attribute. Although static resources may be
included, it is not preferred as each request requires inclusion.

Q5) What are the different JSP life cycle methods?

• Compilation
• Initialization
• Execution
• Cleanup

Q6) Explain Translation Phase in JSP life cycle.


A Java servlet file is generated from a JSP source file. This is the first step
of JSP life cycle. In translation phase, container validates the syntactic
correctness of JSP page and tag files.

• The JSP container interprets the standard directives and actions, and
the custom actions referencing tag libraries (they are all part of JSP
page and will be discussed in the later section) used in this JSP
page.
• In the above pictorial description, demo.jsp is translated to
demo_jsp.java in the first step

Q7) Differentiate between JSP Scriptlet tag and Declaration tag.

Q8) Mention the advantages of JSP over Servlets?

1. Servlets use println statements for printing an HTML document which is usually very
difficult to use. JSP has no such tedius task to maintain.
2. JSP needs no compilation, CLASSPATH setting and packaging.
3. In a JSP page visual content and logic are seperated, which is not possible in a servlet.
4. There is automatic deployment of a JSP, recompilation is done automatically when
changes are made to JSP pages.
5. Usually with JSP, Java Beans and custom tags web application is simplified.

Q9) Explain the difference between forward and sendRedirect?


Q10) Which implicit object is not available in normal JSP pages?
JSP exception implicit object is not available in normal JSP pages and it's used in JSP error
pages only to catch the exception thrown by the JSP pages and provide useful message to the
client.

Servlet:
Q1) Differentiate between GET and POST method?
Q2) Compare web server and application server?

Q3) What are the advantages of Servlet over CGI?


• Servlet provide better performance that CGI in terms of processing
time, memory utilization because servlets uses benefits of
multithreading and for each request a new thread is created, that is
faster than loading creating new Object for each request with CGI.
• Servlet is platform and system independent, the web application
developed with Servlet can be run on any standard web container
such as Tomcat, JBoss, Glassfish servers and on operating systems
such as Windows, Linux, Unix, Solaris, Mac etc.
• Servlets are robust because container takes care of life cycle of
servlet and we don?t need to worry about memory leaks, security,
garbage collection etc.
• Servlets are easy to maintain and scalable.

Q4) What is Request Dispatcher?


public interface RequestDispatcher
Defines an object that receives requests from the client and sends them to any resource (such as a
servlet, HTML file, or JSP file) on the server. The servlet container creates
the RequestDispatcher object, which is used as a wrapper around a server resource located at
a particular path or given by a particular name.

This interface is intended to wrap servlets, but a servlet container can


create RequestDispatcher objects to wrap any type of resource.

Q5) Differentiate between GenericServlet and HttpServlet?


Q6) What is servlet chaining?
Taking the request from a browser window and processing that request by using
multiple servlets as a chain is called servlet chaining. In servlet chaining, we perform
communication between servlet programs to process the request given by a client.

Q7) List out different phases of servlet life cycle?


• Servlet is borned.
• Servlet is initialized.
• Servlet is ready to service.
• Servlet is servicing.
• Servlet is not ready to service.
• Servlet is destroyed.

Q8) List out different life cycle methods of a servlet?


1. init() method: The Servlet.init() method is called by the Servlet
container to indicate that this Servlet instance is instantiated
successfully and is about to put into service.
2. //init() method
3.
4. public class MyServlet implements Servlet{
5. public void init(ServletConfig config) throws
ServletException {
6. //initialization code
7. }
8. //rest of code
9. }
10. service() method: The service() method of the Servlet is
invoked to inform the Servlet about the client requests.
• This method uses ServletRequest object to collect the
data requested by the client.
• This method uses ServletResponse object to generate
the output content.
11. // service() method
12.
13. public class MyServlet implements Servlet{
14. public void service(ServletRequest res,
ServletResponse res)
15. throws ServletException, IOException {
16. // request handling code
17. }
18. // rest of code
19. }
20. destroy() method: The destroy() method runs only once during
the lifetime of a Servlet and signals the end of the Servlet instance.
21. //destroy() method
22.
23. public void destroy()
As soon as the destroy() method is activated, the Servlet container
releases the Servlet instance.

Q9) What is URL Rewriting?


Url rewriting is a process of appending or modifying any url structure while
loading a page.
The request made by client is always a new request and the server can not
identify whether the current request is send by a new client or the previous
same client. Due to This property of HTTP protocol and Web Servers are
called stateless. But many times we should know who is client in the
processing request.
For example:
In any social networking site during login to till logout the server should know
who is client so that server can manage all the request according to the user
need.
This problem is solved by Session in Servlet.

Q10) What is a Cookie?


A cookie is an amount of information that persists between a server-side and a client-
side. A web browser stores this information at the time of browsing. A cookie contains the
information as a string generally in the form of a name-value pair separated by semi-colons.

Q11) How to get the server information in a servlet?


To display the name of the Server we are using use the method getServerName() of
the HttpServletRequest interface. To display the Server port number use the
method getServerPort(). Use other methods of the HttpServletRequest interface
like getProtocol() to display the protocol we are using and many more methods
depending on our needs.

Example :
Code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ServerInfo extends HttpServlet{


protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("The server name is " + request.getServerName() + "<br>");
out.println("The server port number is " + request.getServerPort()+ "<br>");
out.println("The protocol is " + request.getProtocol()+ "<br>");
out.println("The scheme used is " + request.getScheme());
}
}

Q12) What do you mean by InterServlet communication?


A process where two or more servlets communicates with each other to process the
client request. A servlet can forward the request to another servlet to process the client
request. A servlet can include the output of another servlet to process the client request.

Q13) What do you mean by the Servlet Chaining?


Taking the request from a browser window and processing that request by using
multiple servlets as a chain is called servlet chaining. In servlet chaining, we perform
communication between servlet programs to process the request given by a client.

Q14) Why doesn’t a Servlet include main()? How does it work?


Servlets are designed to run inside a servlet container (eg. Apache Tomcat). Execution of
a servlet happens in the following manner: The servlet container calls
the GenericServlet.service() method on a servlet which typically calls the
appropriate doXxx() method, eg. doGet(), doPost(), etc. The doXxx() method is responsible
for interpreting the HTTP request and serving an appropriate
response. GenericServlet.service() is roughly analagous to main() in a plain old java class.

Q15) How can you create a session in servlet?


To create a new session or gain access to an existing session, use the HttpServletRequest
method getSession(), as shown in the following example: HttpSession mySession =
request. getSession();

JDBC:
Q1) What is the difference between execute, executeQuery, executeUpdate?
Q2) What is JDBC ResultSet?
The Java JDBC ResultSet interface represents the result of a database
query. The text about queries shows how the result of a query is returned
as a java.sql.ResultSet. This ResultSet is then iterated to
inspect the result.
Q3) List out different types of JDBC Drivers?

• Type 1: JDBC-ODBC bridge


• Type 2: partial Java driver
• Type 3: pure Java driver for database middleware
• Type 4: pure Java driver for direct-to-database
• Type 5: highly-functional drivers with superior performance

Q4) What is JDBC API and when do we use it?......


Q5) What are the benefits of PreparedStatement over Statement?
PreparedStatement prevents SQL injection threats as it automatically
escapes the special characters.

Precompiles and caches the SQL statement for faster execution and to
reuse the same SQL statement in batch.
PreparedStatement provides clear separation between the query code and
the parameter values that improves readability.

PreparedStatement provides convenient way to transform Java object types


to SQL Data types to pass input parameters.

Q6) What is the limitation of PreparedStatement and how to overcome it?

One of the limitation of PreparedStatement is that we can’t use it directly with IN


clause statements. Some of the alternative approaches to use PreparedStatement
with IN clause are;

1. Execute Single Queries – very slow performance and not recommended


2. Using Stored Procedure – Database specific and hence not suitable for
multiple database applications.
3. Creating PreparedStatement Query dynamically – Good approach but
looses the benefit of cached PreparedStatement.
4. Using NULL in PreparedStatement Query – A good approach when you
know the maximum number of variables inputs, can be extended to allow
unlimited parameters by executing in parts.

Q7)How can we execute stored procedures using CallableStatement?


You can call the SQL stored procedures using the CallableStatement interface. A
Callable statement can have input parameters, output parameters, or both.
You can create an object of the CallableStatement (interface) using
the prepareCall() method of the Connection interface. This method accepts a string
variable representing a query to call the stored procedures and returns
a CallableStatement object.
Suppose you have a procedure name myProcedure in the database you can
prepare a callable statement as:
//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?,
?, ?)}");
Then you can set values to the place holders using the setter methods of the
CallableStatement interface and execute the callable statement using the execute()
method as shown below.
cstmt.setString(1,"Raghav");
cstmt.setInt(2,3000);
cstmt.setString(3,"Hyderabad");
cstmt.execute();
If there are no input values for the procedure you can simply Prepare the callable
statement and execute it as shown below:
CallableStatement cstmt = con.prepareCall("{call
myProcedure()}");
cstmt.execute();

Q8) Explain the reason why Prepared Statements are faster?


While executing statements using Statement object, especially insert statements,
each time a query is executed the whole statement is compiled and executed again
and again where, the only difference among these statements is the values of the
statements.
Whereas, prepared statement is a precompiled statement i.e. the query is compiled
and stored in the database, using place holders (?) instead of values and values to
these place holders are supplied later.
Thus, avoiding unnecessary compilation and execution of the statement again and
again.

Q9) What is the return value of execute (), executeQuery() and


executeUpdate() methods?
Q10) Write down the broad steps to perform CRUD operations on database
using JDBC.

You might also like